fs-text-encoding.test.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import { mkdtemp, open, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { createNodeFileSystemAdapter } from "@zcode/adapters/fs";
  5. import iconv from "iconv-lite";
  6. import { afterEach, describe, expect, it, vi } from "vitest";
  7. const SAMPLE_BYTES = 4096;
  8. const LARGE_FILE_BYTES = 11 * 1024 * 1024;
  9. const UTF8_BOUNDARIES = [
  10. { char: "é", keptBytes: 1 },
  11. { char: "中", keptBytes: 1 },
  12. { char: "中", keptBytes: 2 },
  13. { char: "😀", keptBytes: 1 },
  14. { char: "😀", keptBytes: 2 },
  15. { char: "😀", keptBytes: 3 },
  16. ];
  17. describe("text encoding at a sampled file boundary", () => {
  18. const directories: string[] = [];
  19. const fs = createNodeFileSystemAdapter();
  20. afterEach(async () => {
  21. vi.restoreAllMocks();
  22. await Promise.all(
  23. directories.splice(0).map((path) => rm(path, { recursive: true, force: true })),
  24. );
  25. });
  26. async function createFile(bytes: Buffer): Promise<string> {
  27. const dir = await mkdtemp(join(tmpdir(), "zcode-text-encoding-"));
  28. directories.push(dir);
  29. const path = join(dir, "sample.txt");
  30. await writeFile(path, bytes);
  31. return path;
  32. }
  33. function largeText(head: string, encoding = "utf8"): Buffer {
  34. const tail = "这是合法的文本行。\n";
  35. const repeats = Math.ceil(LARGE_FILE_BYTES / iconv.encode(tail, encoding).length);
  36. return iconv.encode(head + tail.repeat(repeats), encoding);
  37. }
  38. it.each(UTF8_BOUNDARIES)(
  39. "preserves $char when the sample keeps $keptBytes bytes",
  40. async ({ char, keptBytes }) => {
  41. const firstLine = "a".repeat(SAMPLE_BYTES - keptBytes) + char + "正文";
  42. const path = await createFile(largeText(`${firstLine}\n`));
  43. const read = await fs.readTextFileRange({ path, limitLines: 2 });
  44. expect(read.encoding).toBe("utf8");
  45. expect(read.content).toBe(`${firstLine}\n这是合法的文本行。`);
  46. expect(read.lineCount).toBe(2);
  47. // Bug 根因:旧实现将样本末尾的半个字符当成完整文件错误,导致拒读或误判为 legacy 编码。
  48. const later = await fs.readTextFileRange({ path, offsetLine: 2500, limitLines: 2 });
  49. expect(later.content).toBe("这是合法的文本行。\n这是合法的文本行。");
  50. },
  51. );
  52. it.each(UTF8_BOUNDARIES)(
  53. "does not accept an incomplete $char at actual EOF ($keptBytes bytes) as UTF-8",
  54. async ({ char, keptBytes }) => {
  55. const sample = Buffer.concat([
  56. Buffer.from("a".repeat(SAMPLE_BYTES - keptBytes)),
  57. Buffer.from(char).subarray(0, keptBytes),
  58. ]);
  59. const path = await createFile(sample);
  60. // 完整输入不能沿用前缀宽容模式;已有 legacy 检测可拒绝或选择其他编码。
  61. const read = await fs.readTextFile({ path }).catch((error: { code: string }) => {
  62. expect(error.code).toBe("unsupported");
  63. return null;
  64. });
  65. expect(read?.encoding).not.toBe("utf8");
  66. },
  67. );
  68. it("rejects invalid UTF-8 inside the sample instead of replacing it", async () => {
  69. const path = await createFile(Buffer.concat([Buffer.from([0xff]), largeText("\n")]));
  70. await expect(fs.readTextFileRange({ path, limitLines: 2 })).rejects.toMatchObject({
  71. code: "unsupported",
  72. });
  73. });
  74. it("keeps GBK after an ASCII prefix when its lead byte resembles pending UTF-8", async () => {
  75. const firstLine = "a".repeat(SAMPLE_BYTES - 1) + "中文";
  76. const path = await createFile(largeText(`${firstLine}\n`, "gbk"));
  77. // D6 | D0:单看 D6 可等待 UTF-8 续字节,但 D0 会排除 UTF-8;不能提前接受候选。
  78. const read = await fs.readTextFileRange({ path, limitLines: 2 });
  79. expect(read.content).toBe(`${firstLine}\n这是合法的文本行。`);
  80. expect(read.encoding).toBe("gb2312");
  81. });
  82. it.each([
  83. { name: "invalid continuation", prefix: [0xe4], rest: [0xff, 0xad] },
  84. { name: "overlong sequence", prefix: [0xe0], rest: [0x80, 0x80] },
  85. { name: "surrogate", prefix: [0xed], rest: [0xa0, 0x80] },
  86. { name: "out-of-range code point", prefix: [0xf4], rest: [0x90, 0x80, 0x80] },
  87. ])("does not accept $name beyond the sample as UTF-8", async ({ prefix, rest }) => {
  88. const path = await createFile(
  89. Buffer.concat([
  90. Buffer.alloc(SAMPLE_BYTES - prefix.length, "a"),
  91. Buffer.from(prefix),
  92. Buffer.from(rest),
  93. largeText("\n"),
  94. ]),
  95. );
  96. const read = await fs
  97. .readTextFileRange({ path, limitLines: 1 })
  98. .catch((error: { code: string }) => {
  99. expect(error.code).toBe("unsupported");
  100. return null;
  101. });
  102. expect(read?.encoding).not.toBe("utf8");
  103. });
  104. it("completes the boundary sequence across short reads without consuming the next character", async () => {
  105. const firstLine = "a".repeat(SAMPLE_BYTES - 1) + "😀中";
  106. const path = await createFile(largeText(`${firstLine}\n`));
  107. const probe = await open(path, "r");
  108. const prototype = Object.getPrototypeOf(probe) as { read: typeof probe.read };
  109. const originalRead = prototype.read;
  110. await probe.close();
  111. vi.spyOn(prototype, "read").mockImplementation(async function (
  112. this: typeof probe,
  113. buffer: Buffer,
  114. offset: number,
  115. length: number,
  116. position: number | null,
  117. ) {
  118. return originalRead.call(
  119. this,
  120. buffer,
  121. offset,
  122. position === 0 ? length : Math.min(1, length),
  123. position,
  124. );
  125. } as never);
  126. const read = await fs.readTextFileRange({ path, limitLines: 1 });
  127. expect(read.encoding).toBe("utf8");
  128. expect(read.content).toBe(firstLine);
  129. });
  130. it.each([
  131. { encoding: "gb2312", firstLine: "这是中文文本。" },
  132. { encoding: "gbk", firstLine: "丂这是中文文本。" },
  133. { encoding: "gb18030", firstLine: "𠀀这是中文文本。" },
  134. ])(
  135. "keeps $encoding text readable across the sample boundary",
  136. async ({ encoding, firstLine }) => {
  137. const path = await createFile(largeText(`${firstLine}\n`, encoding));
  138. const read = await fs.readTextFileRange({ path, limitLines: 2 });
  139. expect(read.content).toBe(`${firstLine}\n这是合法的文本行。`);
  140. expect(read.encoding).not.toBe("utf8");
  141. },
  142. );
  143. it.each(["utf8", "utf16le"])("preserves %s BOM detection", async (encoding) => {
  144. const path = await createFile(largeText("\uFEFF中文\n", encoding));
  145. const read = await fs.readTextFileRange({ path, limitLines: 2 });
  146. expect(read.encoding).toBe(encoding);
  147. expect(read.content).toBe("\uFEFF中文\n这是合法的文本行。");
  148. });
  149. it("continues sampling after a short read before selecting the encoding", async () => {
  150. const path = await createFile(largeText("a这是中文文本。\n", "gb2312"));
  151. const probe = await open(path, "r");
  152. const prototype = Object.getPrototypeOf(probe) as { read: typeof probe.read };
  153. const originalRead = prototype.read;
  154. await probe.close();
  155. let first = true;
  156. vi.spyOn(prototype, "read").mockImplementation(async function (
  157. this: typeof probe,
  158. buffer: Buffer,
  159. offset: number,
  160. length: number,
  161. position: number | null,
  162. ) {
  163. const size = first ? 1 : length;
  164. first = false;
  165. return originalRead.call(this, buffer, offset, size, position);
  166. } as never);
  167. const read = await fs.readTextFileRange({ path, limitLines: 1 });
  168. expect(read.encoding).toBe("gb2312");
  169. expect(read.content).toBe("a这是中文文本。");
  170. });
  171. it.each([1, 2, 3])(
  172. "uses actual EOF when only %i emoji bytes remain after stat",
  173. async (keptBytes) => {
  174. const path = await createFile(largeText("完整文本\n"));
  175. const incomplete = Buffer.concat([
  176. Buffer.from("a".repeat(SAMPLE_BYTES - 1)),
  177. Buffer.from("😀").subarray(0, keptBytes),
  178. ]);
  179. const probe = await open(path, "r");
  180. const prototype = Object.getPrototypeOf(probe) as { read: typeof probe.read };
  181. const originalRead = prototype.read;
  182. await probe.close();
  183. let first = true;
  184. vi.spyOn(prototype, "read").mockImplementation(async function (
  185. this: typeof probe,
  186. buffer: Buffer,
  187. offset: number,
  188. length: number,
  189. position: number | null,
  190. ) {
  191. if (first) {
  192. first = false;
  193. await writeFile(path, incomplete);
  194. }
  195. return originalRead.call(this, buffer, offset, length, position);
  196. } as never);
  197. const read = await fs
  198. .readTextFileRange({ path, limitLines: 1 })
  199. .catch((error: { code: string }) => {
  200. expect(error.code).toBe("unsupported");
  201. return null;
  202. });
  203. expect(read?.encoding).not.toBe("utf8");
  204. },
  205. );
  206. });