@criogaid/pi-hashline-edit 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +59 -50
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1594 -694
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +219 -130
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -1,112 +1,74 @@
1
1
  import { mergeRanges, type HalfOpenRange } from "../core/ranges.ts";
2
2
 
3
- export type LineRange = HalfOpenRange;
4
-
5
- export interface RgSubmatch {
3
+ interface RgSubmatch {
6
4
  start: number;
7
5
  end: number;
8
6
  }
9
7
 
10
- function assertRange(range: LineRange): void {
11
- if (!Number.isSafeInteger(range[0]) || !Number.isSafeInteger(range[1]) || range[0] < 1 || range[1] <= range[0]) {
12
- throw new Error("Invalid physical line range");
13
- }
14
- }
15
-
16
- export function normalizeRanges(ranges: readonly LineRange[]): LineRange[] {
17
- for (const range of ranges) assertRange(range);
18
- return mergeRanges(ranges);
19
- }
20
-
21
- export function unionRanges(left: readonly LineRange[], right: readonly LineRange[]): LineRange[] {
22
- return normalizeRanges([...left, ...right]);
23
- }
24
-
25
- export function intersectRanges(left: readonly LineRange[], right: readonly LineRange[]): LineRange[] {
26
- const a = normalizeRanges(left);
27
- const b = normalizeRanges(right);
28
- const result: LineRange[] = [];
29
- let i = 0;
30
- let j = 0;
31
- while (i < a.length && j < b.length) {
32
- const start = Math.max(a[i][0], b[j][0]);
33
- const end = Math.min(a[i][1], b[j][1]);
34
- if (start < end) result.push([start, end]);
35
- if (a[i][1] < b[j][1]) i++;
36
- else j++;
8
+ function countLfBefore(lineBreaks: readonly number[], offset: number): number {
9
+ let low = 0;
10
+ let high = lineBreaks.length;
11
+ while (low < high) {
12
+ const middle = Math.floor((low + high) / 2);
13
+ if (lineBreaks[middle] < offset) low = middle + 1;
14
+ else high = middle;
37
15
  }
38
- return result;
16
+ return low;
39
17
  }
40
18
 
41
- export function subtractRanges(left: readonly LineRange[], right: readonly LineRange[]): LineRange[] {
42
- const source = normalizeRanges(left);
43
- const removed = normalizeRanges(right);
44
- const result: LineRange[] = [];
45
- let j = 0;
46
- for (const [start, end] of source) {
47
- let cursor = start;
48
- while (j < removed.length && removed[j][1] <= cursor) j++;
49
- let k = j;
50
- while (k < removed.length && removed[k][0] < end) {
51
- if (removed[k][0] > cursor) result.push([cursor, Math.min(removed[k][0], end)]);
52
- cursor = Math.max(cursor, removed[k][1]);
53
- if (cursor >= end) break;
54
- k++;
55
- }
56
- if (cursor < end) result.push([cursor, end]);
57
- }
58
- return result;
59
- }
60
-
61
- function countLfBefore(bytes: Buffer, offset: number): number {
62
- let count = 0;
63
- for (let i = 0; i < offset; i++) if (bytes[i] === 10) count++;
64
- return count;
65
- }
66
-
67
- function zeroWidthLine(bytes: Buffer, offset: number, eventStartLine: number, fileLineCount: number): number | undefined {
68
- if (fileLineCount === 0) return undefined;
69
- const candidate = eventStartLine + countLfBefore(bytes, offset);
70
- return Math.min(candidate, fileLineCount);
71
- }
72
-
73
- /** Convert rg byte offsets to physical line ranges; optionally record a match's UTF-16 column on its starting line. */
19
+ /** Map rg's byte offsets in a multiline JSON event to existing physical lines. */
74
20
  export function submatchesToLineRanges(
75
21
  bytes: Buffer,
76
22
  eventStartLine: number,
77
23
  submatches: readonly RgSubmatch[],
78
24
  fileLineCount: number,
79
25
  columns?: Map<number, number>,
80
- ): LineRange[] {
81
- if (!Number.isSafeInteger(eventStartLine) || eventStartLine < 1 || !Number.isSafeInteger(fileLineCount) || fileLineCount < 0) {
26
+ ): HalfOpenRange[] {
27
+ if (
28
+ !Number.isSafeInteger(eventStartLine) ||
29
+ eventStartLine < 1 ||
30
+ !Number.isSafeInteger(fileLineCount) ||
31
+ fileLineCount < 0
32
+ ) {
82
33
  throw new Error("Invalid rg physical line metadata");
83
34
  }
84
- const ranges: LineRange[] = [];
35
+ const ranges: HalfOpenRange[] = [];
36
+ const lineBreaks: number[] = [];
37
+ let at = 0;
38
+ while ((at = bytes.indexOf(10, at)) !== -1) {
39
+ lineBreaks.push(at);
40
+ at++;
41
+ }
85
42
  const recordColumn = (line: number, offset: number) => {
86
43
  if (!columns || columns.has(line)) return;
87
44
  const lineStart = offset === 0 ? 0 : bytes.lastIndexOf(10, offset - 1) + 1;
88
45
  columns.set(line, bytes.subarray(lineStart, offset).toString("utf8").length);
89
46
  };
90
- for (const submatch of submatches) {
91
- const { start, end } = submatch;
92
- if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || end > bytes.length) {
47
+ for (const { start, end } of submatches) {
48
+ if (
49
+ !Number.isSafeInteger(start) ||
50
+ !Number.isSafeInteger(end) ||
51
+ start < 0 ||
52
+ end < start ||
53
+ end > bytes.length
54
+ ) {
93
55
  throw new Error("Invalid rg submatch byte offsets");
94
56
  }
95
57
  if (start === end) {
96
- const line = zeroWidthLine(bytes, start, eventStartLine, fileLineCount);
97
- if (line !== undefined) {
98
- ranges.push([line, line + 1]);
99
- const offset = eventStartLine + countLfBefore(bytes, start) > fileLineCount ? Math.max(0, start - 1) : start;
100
- recordColumn(line, offset);
101
- }
58
+ if (fileLineCount === 0) continue;
59
+ const line = eventStartLine + countLfBefore(lineBreaks, start);
60
+ if (line > fileLineCount) throw new Error("File changed during search; rerun the query.");
61
+ ranges.push([line, line + 1]);
62
+ recordColumn(line, start);
102
63
  continue;
103
64
  }
104
- const first = eventStartLine + countLfBefore(bytes, start);
105
- const last = eventStartLine + countLfBefore(bytes, end - 1);
106
- if (first <= fileLineCount) {
107
- ranges.push([first, Math.min(last, fileLineCount) + 1]);
108
- recordColumn(first, start);
65
+ const first = eventStartLine + countLfBefore(lineBreaks, start);
66
+ const last = eventStartLine + countLfBefore(lineBreaks, end - 1);
67
+ if (first > fileLineCount || last > fileLineCount) {
68
+ throw new Error("File changed during search; rerun the query.");
109
69
  }
70
+ ranges.push([first, last + 1]);
71
+ recordColumn(first, start);
110
72
  }
111
- return normalizeRanges(ranges);
73
+ return mergeRanges(ranges);
112
74
  }
@@ -1,18 +1,53 @@
1
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { mkdtemp, open, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, resolve, sep } from "node:path";
4
4
  import { normalizeLineEndings } from "../core/lines.ts";
5
- import { decodeUtf8 } from "../core/text.ts";
6
- import { COMMON_RG_ARGS, rgText, runRg, runRgPaths, type RgRunResult } from "./rg-line-filter.ts";
5
+ import { scanTextFile } from "./text-stream.ts";
6
+ import {
7
+ COMMON_RG_ARGS,
8
+ MAX_RG_STDERR_BYTES,
9
+ rgText,
10
+ runRg,
11
+ runRgPaths,
12
+ type RgRunResult,
13
+ } from "./rg-line-filter.ts";
14
+ import { errorMessage, throwIfCancelled } from "./error-text.ts";
7
15
 
8
- /** Search bounded LF snapshots while reporting original paths and logical match offsets. */
16
+ /** CRLF snapshot batches flush after this many files or source bytes (README: 64 files / 8 MiB). */
17
+ const SNAPSHOT_BATCH_FILES = 64;
18
+ const SNAPSHOT_BATCH_BYTES = 8 * 1024 * 1024;
19
+
20
+ async function writeLfSnapshot(source: string, destination: string, signal?: AbortSignal) {
21
+ const handle = await open(destination, "w");
22
+ let pendingCr = "";
23
+ try {
24
+ const stats = await scanTextFile(
25
+ source,
26
+ async (chunk) => {
27
+ const text = pendingCr + chunk;
28
+ pendingCr = text.endsWith("\r") ? "\r" : "";
29
+ await handle.writeFile(normalizeLineEndings(pendingCr ? text.slice(0, -1) : text));
30
+ },
31
+ signal,
32
+ );
33
+ if (stats.hasNul) throw new Error("File changed during search; rerun the query.");
34
+ if (pendingCr) await handle.writeFile(pendingCr);
35
+ } finally {
36
+ await handle.close();
37
+ }
38
+ }
39
+
40
+ /** Search LF views in batches while reporting original paths and logical match offsets. */
9
41
  export const runRgTextView: typeof runRg = async (rgPath, args, signal, onLine) => {
10
42
  let boundary = args.length;
11
43
  const scope: string[] = [];
12
44
  const matcher: string[] = [];
13
45
  for (let i = 0; i < args.length; i++) {
14
46
  const arg = args[i];
15
- if (arg === "--") { boundary = i; break; }
47
+ if (arg === "--") {
48
+ boundary = i;
49
+ break;
50
+ }
16
51
  if (arg === "--glob") scope.push(arg, args[++i]);
17
52
  else if (["--hidden", "--no-ignore", "--follow"].includes(arg)) scope.push(arg);
18
53
  else {
@@ -20,69 +55,104 @@ export const runRgTextView: typeof runRg = async (rgPath, args, signal, onLine)
20
55
  if (arg === "-e") matcher.push(args[++i]);
21
56
  }
22
57
  }
23
- if (boundary === args.length || args[boundary + 1] === "-") return runRg(rgPath, args, signal, onLine);
24
- // ponytail: bounded snapshots add disk I/O; use a streaming backend if large scans dominate.
25
- const directory = await mkdtemp(join(tmpdir(), "hashline-grep-"));
58
+ if (boundary === args.length || args[boundary + 1] === "-")
59
+ return runRg(rgPath, args, signal, onLine);
60
+ let directory: string | undefined;
26
61
  const result: RgRunResult = { code: 1, stderr: "", stopped: false };
27
- const paths = new Map<string, string>();
28
- let snapshotBytes = 0;
62
+ // LF-only files pass through to rg directly; only CRLF files need temp snapshots.
63
+ const snapshots = new Map<string, string>();
64
+ const searchPaths: string[] = [];
65
+ let batchBytes = 0;
29
66
  const record = (run: RgRunResult) => {
30
- result.stderr = (result.stderr + run.stderr).slice(0, 65536);
67
+ result.stderr = (result.stderr + run.stderr).slice(0, MAX_RG_STDERR_BYTES);
31
68
  if (run.code !== 0 && run.code !== 1 && !run.stopped) result.code = run.code;
32
69
  else if (run.code === 0 && result.code === 1) result.code = 0;
33
70
  result.stopped ||= run.stopped;
34
71
  };
35
- const flush = async () => {
36
- if (!paths.size) return !result.stopped;
37
- // Scope filtering belongs to the original paths. Snapshot names have no ignore/glob semantics.
72
+
73
+ const searchBatch = async (
74
+ searchPaths: readonly string[],
75
+ rewritePaths: ReadonlyMap<string, string>,
76
+ ) => {
38
77
  const searchArgs = [
39
- ...matcher, "--encoding=none", "--no-ignore", "--hidden", "--", ...paths.keys(),
78
+ ...matcher,
79
+ "--encoding=none",
80
+ "--no-ignore",
81
+ "--hidden",
82
+ "--",
83
+ ...searchPaths,
40
84
  ];
41
85
  const run = await runRg(rgPath, searchArgs, signal, async (line) => {
42
86
  const event = JSON.parse(line);
43
87
  if (event.data?.path) {
44
- const original = paths.get(resolve(rgText(event.data.path)));
45
- if (!original) throw new Error("ripgrep returned an unexpected snapshot path");
46
- event.data.path = { text: original };
88
+ const reported = resolve(rgText(event.data.path));
89
+ const original = rewritePaths.get(reported);
90
+ if (original) event.data.path = { text: original };
91
+ // Passthrough paths need no rewrite — reported path is already the original.
47
92
  }
48
93
  return onLine(JSON.stringify(event));
49
94
  });
50
95
  record(run);
51
- for (const path of paths.keys()) await rm(path);
52
- paths.clear();
53
- snapshotBytes = 0;
96
+ };
97
+
98
+ const flush = async () => {
99
+ if (!searchPaths.length) return !result.stopped;
100
+ // Scope filtering belongs to the original paths. Snapshot names have no ignore/glob semantics.
101
+ await searchBatch(searchPaths, snapshots);
102
+ for (const path of snapshots.keys()) await rm(path);
103
+ snapshots.clear();
104
+ searchPaths.length = 0;
105
+ batchBytes = 0;
54
106
  return !result.stopped;
55
107
  };
108
+
109
+ const ensureDirectory = async () => {
110
+ directory ??= await mkdtemp(join(tmpdir(), "hashline-grep-"));
111
+ return directory;
112
+ };
113
+
56
114
  try {
57
115
  const listArgs = [
58
- ...COMMON_RG_ARGS, ...scope, "--files", "--null", "--", ...args.slice(boundary + 1),
116
+ ...COMMON_RG_ARGS,
117
+ ...scope,
118
+ "--files",
119
+ "--null",
120
+ "--",
121
+ ...args.slice(boundary + 1),
59
122
  ];
60
123
  const listed = await runRgPaths(rgPath, listArgs, signal, async (path) => {
61
- signal?.throwIfAborted();
124
+ throwIfCancelled(signal);
62
125
  const original = resolve(path);
63
- if (original.startsWith(directory + sep)) return true;
64
- let text: string | Buffer;
126
+ if (directory && original.startsWith(directory + sep)) return true;
65
127
  try {
66
- const bytes = await readFile(original, { signal });
67
- // Let rg decide whether a NUL file matches; the result reader rejects confirmed binary hits.
68
- text = bytes.includes(0) ? bytes : normalizeLineEndings(decodeUtf8(bytes));
128
+ const info = await scanTextFile(original, undefined, signal);
129
+ if (info.hasCrLf && !info.hasNul) {
130
+ const dir = await ensureDirectory();
131
+ const snapshot = join(dir, String(snapshots.size));
132
+ await writeLfSnapshot(original, snapshot, signal);
133
+ snapshots.set(snapshot, original);
134
+ searchPaths.push(snapshot);
135
+ } else {
136
+ // Binary files retain their raw bytes; confirmed content hits are rejected later.
137
+ searchPaths.push(original);
138
+ }
139
+ batchBytes += info.byteLength;
69
140
  } catch (error) {
70
- signal?.throwIfAborted();
71
- const message = error instanceof Error ? error.message : String(error);
141
+ throwIfCancelled(signal);
142
+ const message = errorMessage(error);
72
143
  record({ code: 2, stopped: false, stderr: `${original}: ${message}\n` });
73
144
  return true;
74
145
  }
75
- const snapshot = join(directory, String(paths.size));
76
- await writeFile(snapshot, text, { signal });
77
- paths.set(snapshot, original);
78
- snapshotBytes += Buffer.byteLength(text);
79
- return (paths.size < 64 && snapshotBytes < 8 * 1024 * 1024) || await flush();
146
+ return (
147
+ (searchPaths.length < SNAPSHOT_BATCH_FILES && batchBytes < SNAPSHOT_BATCH_BYTES) ||
148
+ (await flush())
149
+ );
80
150
  });
81
151
  // A successful listing is not itself a text match.
82
152
  record({ ...listed, code: listed.code === 0 ? 1 : listed.code });
83
153
  if (!result.stopped) await flush();
84
154
  return result;
85
155
  } finally {
86
- await rm(directory, { recursive: true, force: true });
156
+ if (directory) await rm(directory, { recursive: true, force: true });
87
157
  }
88
158
  };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Shared input constraints for tool schemas and settings.
3
+ *
4
+ * Tool parameters and `hashlineEdit` settings use the same integer rules, so
5
+ * both read them from here rather than restating bounds per call site.
6
+ *
7
+ * @module pi-hashline-edit/pi
8
+ */
9
+
10
+ /** JSON Schema keywords for an integer in [minimum, maximum]; fractions are rejected, not rounded. */
11
+ export function integerRange(minimum: number, maximum: number) {
12
+ return { minimum, multipleOf: 1, maximum };
13
+ }
14
+
15
+ /** Positive line numbers, line counts, and match limits. */
16
+ export const POSITIVE_SAFE_INTEGER = integerRange(1, Number.MAX_SAFE_INTEGER);
17
+
18
+ /** Runtime counterpart of {@link integerRange} for values not validated by a schema. */
19
+ export function isIntegerInRange(
20
+ value: unknown,
21
+ minimum: number,
22
+ maximum: number,
23
+ ): value is number {
24
+ return (
25
+ typeof value === "number" && Number.isInteger(value) && value >= minimum && value <= maximum
26
+ );
27
+ }
package/src/pi/state.ts CHANGED
@@ -13,14 +13,14 @@ import { DEFAULT_CONFIG, type HashlineEditConfig } from "./config.ts";
13
13
  const GLOBAL_KEY = "__piHashlineEdit";
14
14
 
15
15
  export interface HashlineEditState {
16
- config: HashlineEditConfig;
16
+ config: HashlineEditConfig;
17
17
  }
18
18
 
19
19
  export function getState(): HashlineEditState {
20
- const g = globalThis as Record<string, unknown>;
21
- const existing = g[GLOBAL_KEY];
22
- if (existing) return existing as HashlineEditState;
23
- const state: HashlineEditState = { config: { ...DEFAULT_CONFIG } };
24
- g[GLOBAL_KEY] = state;
25
- return state;
20
+ const g = globalThis as Record<string, unknown>;
21
+ const existing = g[GLOBAL_KEY];
22
+ if (existing) return existing as HashlineEditState;
23
+ const state: HashlineEditState = { config: { ...DEFAULT_CONFIG } };
24
+ g[GLOBAL_KEY] = state;
25
+ return state;
26
26
  }
@@ -0,0 +1,118 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createHash } from "node:crypto";
4
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { byteRevision } from "./file-commit.ts";
7
+ import { join } from "node:path";
8
+ import { scanTextFile, scanTextLines } from "./text-stream.ts";
9
+ import { splitLines } from "../core/lines.ts";
10
+
11
+ async function withFile(run: (path: string) => Promise<void>) {
12
+ const directory = await mkdtemp(join(tmpdir(), "hashline-stream-"));
13
+ try {
14
+ await run(join(directory, "text"));
15
+ } finally {
16
+ await rm(directory, { recursive: true, force: true });
17
+ }
18
+ }
19
+
20
+ test("streamed lines preserve BOM, standalone CR, and boundaries split across chunks", async () =>
21
+ withFile(async (path) => {
22
+ for (const text of [
23
+ "",
24
+ "\n",
25
+ "\n\n",
26
+ "a\r",
27
+ "a\rb\n",
28
+ "\uFEFFa\r\nb\nlast",
29
+ "x".repeat(65535) + "😀\r\nnext\r",
30
+ "x".repeat(65535) + "\r\nlast\n",
31
+ ]) {
32
+ await writeFile(path, text);
33
+ const lines: string[] = [];
34
+ const stats = await scanTextLines(
35
+ path,
36
+ () => true,
37
+ (line) => {
38
+ assert.equal(line.number, lines.length + 1);
39
+ assert.equal(line.byteLength, Buffer.byteLength(line.text!));
40
+ lines.push(line.text!);
41
+ },
42
+ );
43
+ assert.deepEqual(lines, splitLines(text));
44
+ assert.equal(stats.totalLines, lines.length);
45
+ assert.equal(stats.finalNewline, text === "" || text.endsWith("\n"));
46
+ assert.equal(stats.hasCrLf, text.includes("\r\n"));
47
+ assert.equal(stats.byteLength, Buffer.byteLength(text));
48
+ }
49
+ }));
50
+
51
+ test("streamed byte digests preserve the source revision across BOM, CRLF, and chunk boundaries", async () =>
52
+ withFile(async (path) => {
53
+ const source = Buffer.from(`\uFEFFfirst\r\n${"a".repeat(65536)}\r\nlast\r`);
54
+ await writeFile(path, source);
55
+ const first = createHash("sha256");
56
+ const stats = await scanTextFile(path, undefined, undefined, (bytes) => first.update(bytes));
57
+ assert.equal(stats.hasCrLf, true);
58
+ assert.equal(first.digest("hex"), byteRevision(source));
59
+ const second = createHash("sha256");
60
+ await scanTextLines(
61
+ path,
62
+ (number) => number === 1,
63
+ () => {},
64
+ {
65
+ onBytes: (bytes) => second.update(bytes),
66
+ },
67
+ );
68
+ assert.equal(second.digest("hex"), byteRevision(source));
69
+ }));
70
+
71
+ test("streamed selection discards oversized content and still counts and reads subsequent lines", async () =>
72
+ withFile(async (path) => {
73
+ await writeFile(path, "z".repeat(2 * 1024 * 1024) + "\n界\r\nkeep\nignored\n");
74
+ const seen: unknown[] = [];
75
+ const stats = await scanTextLines(
76
+ path,
77
+ (number) => number <= 3,
78
+ (line) => seen.push(line),
79
+ { maxLineBytes: 4 },
80
+ );
81
+ assert.equal(stats.totalLines, 4);
82
+ assert.deepEqual(seen, [
83
+ { number: 1, byteLength: 2 * 1024 * 1024, carriageReturns: 0, text: undefined },
84
+ { number: 2, byteLength: 3, carriageReturns: 0, text: "界" },
85
+ { number: 3, byteLength: 4, carriageReturns: 0, text: "keep" },
86
+ ]);
87
+ }));
88
+
89
+ test("streamed validation checks the entire file and gives NUL precedence over malformed UTF-8", async () =>
90
+ withFile(async (path) => {
91
+ await writeFile(
92
+ path,
93
+ Buffer.concat([Buffer.from("visible\n"), Buffer.alloc(65536, 97), Buffer.from([0xf0, 0x9f])]),
94
+ );
95
+ await assert.rejects(
96
+ scanTextLines(
97
+ path,
98
+ (number) => number === 1,
99
+ () => {},
100
+ ),
101
+ /UNSUPPORTED_ENCODING/,
102
+ );
103
+ await writeFile(
104
+ path,
105
+ Buffer.concat([Buffer.from([0xff]), Buffer.alloc(65536, 97), Buffer.from([0])]),
106
+ );
107
+ assert.equal((await scanTextFile(path)).hasNul, true);
108
+ }));
109
+
110
+ test("streamed reads propagate cancellation", async () =>
111
+ withFile(async (path) => {
112
+ await writeFile(path, "a".repeat(2 * 65536));
113
+ const controller = new AbortController();
114
+ await assert.rejects(
115
+ scanTextFile(path, () => controller.abort(), controller.signal),
116
+ { message: "Operation aborted" },
117
+ );
118
+ }));
@@ -0,0 +1,136 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { createUtf8Decoder } from "../core/text.ts";
3
+ import { throwIfCancelled } from "./error-text.ts";
4
+
5
+ /** Scan and validate the whole file with bounded chunks, preserving BOM and raw line endings. */
6
+ export async function scanTextFile(
7
+ path: string,
8
+ onChunk?: (text: string) => void | Promise<void>,
9
+ signal?: AbortSignal,
10
+ onBytes?: (bytes: Buffer) => void,
11
+ ) {
12
+ const decode = createUtf8Decoder();
13
+ let byteLength = 0;
14
+ let lineFeeds = 0;
15
+ let lastByte = -1;
16
+ let hasNul = false;
17
+ let hasCrLf = false;
18
+ let decodingError: unknown;
19
+ const stream = createReadStream(path, { highWaterMark: 64 * 1024, signal });
20
+ try {
21
+ for await (const chunk of stream) {
22
+ const bytes = chunk as Buffer;
23
+ onBytes?.(bytes);
24
+ byteLength += bytes.length;
25
+ hasNul ||= bytes.includes(0);
26
+ hasCrLf ||= (lastByte === 13 && bytes[0] === 10) || bytes.includes("\r\n");
27
+ lastByte = bytes[bytes.length - 1];
28
+ let offset = 0;
29
+ while ((offset = bytes.indexOf(10, offset)) !== -1) {
30
+ lineFeeds++;
31
+ offset++;
32
+ }
33
+ // NUL takes precedence even when an earlier chunk contained malformed UTF-8.
34
+ if (hasNul || decodingError) continue;
35
+ let text: string;
36
+ try {
37
+ text = decode(bytes, true);
38
+ } catch (error) {
39
+ decodingError = error;
40
+ continue;
41
+ }
42
+ await onChunk?.(text);
43
+ }
44
+ } catch (error) {
45
+ // Node's stream abort raises its own AbortError; report the shared cancellation text.
46
+ throwIfCancelled(signal);
47
+ throw error;
48
+ }
49
+ throwIfCancelled(signal);
50
+ if (!hasNul) {
51
+ if (decodingError) throw decodingError;
52
+ const tail = decode();
53
+ if (tail) await onChunk?.(tail);
54
+ }
55
+ return {
56
+ byteLength,
57
+ totalLines: lineFeeds + (lastByte !== -1 && lastByte !== 10 ? 1 : 0),
58
+ finalNewline: lastByte === -1 || lastByte === 10,
59
+ hasNul,
60
+ hasCrLf,
61
+ };
62
+ }
63
+
64
+ interface ScannedLine {
65
+ number: number;
66
+ byteLength: number;
67
+ carriageReturns: number;
68
+ /** Absent when the selected line exceeds maxLineBytes. */
69
+ text: string | undefined;
70
+ }
71
+
72
+ /** Visit selected logical lines, retaining at most maxLineBytes of content per line. */
73
+ export async function scanTextLines(
74
+ path: string,
75
+ select: (number: number) => boolean,
76
+ onLine: (line: ScannedLine) => void,
77
+ options: { signal?: AbortSignal; maxLineBytes?: number; onBytes?: (bytes: Buffer) => void } = {},
78
+ ) {
79
+ const maxBytes = options.maxLineBytes ?? Infinity;
80
+ let number = 1;
81
+ let byteLength = 0;
82
+ let carriageReturns = 0;
83
+ let parts: string[] = [];
84
+ let selected = select(number);
85
+ let lastChar = "";
86
+ const finish = (terminated: boolean) => {
87
+ if (selected) {
88
+ const stripCr = terminated && lastChar === "\r";
89
+ const logicalBytes = byteLength - (stripCr ? 1 : 0);
90
+ let text = logicalBytes <= maxBytes ? parts.join("") : undefined;
91
+ if (stripCr && text !== undefined) text = text.slice(0, -1);
92
+ onLine({
93
+ number,
94
+ byteLength: logicalBytes,
95
+ carriageReturns: carriageReturns - (stripCr ? 1 : 0),
96
+ text,
97
+ });
98
+ carriageReturns = 0;
99
+ byteLength = 0;
100
+ parts = [];
101
+ lastChar = "";
102
+ }
103
+ number++;
104
+ selected = select(number);
105
+ };
106
+ const stats = await scanTextFile(
107
+ path,
108
+ (text) => {
109
+ let start = 0;
110
+ while (start < text.length) {
111
+ const lf = text.indexOf("\n", start);
112
+ if (selected) {
113
+ const end = lf === -1 ? text.length : lf;
114
+ const fragment = text.slice(start, end);
115
+ byteLength += Buffer.byteLength(fragment);
116
+ let cr = 0;
117
+ while ((cr = fragment.indexOf("\r", cr)) !== -1) {
118
+ carriageReturns++;
119
+ cr++;
120
+ }
121
+ if (fragment) lastChar = fragment[fragment.length - 1];
122
+ // Keep one extra byte until the terminator decides whether a final CR is content.
123
+ if (byteLength <= maxBytes + 1) parts.push(fragment);
124
+ else parts = [];
125
+ }
126
+ if (lf === -1) break;
127
+ finish(true);
128
+ start = lf + 1;
129
+ }
130
+ },
131
+ options.signal,
132
+ options.onBytes,
133
+ );
134
+ if (!stats.hasNul && byteLength > 0) finish(false);
135
+ return stats;
136
+ }