@criogaid/pi-hashline-edit 0.5.0 → 0.6.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.
- package/README.md +66 -22
- package/package.json +6 -6
- package/src/core/apply.test.ts +66 -16
- package/src/core/apply.ts +36 -19
- package/src/core/lines.ts +3 -3
- package/src/core/text.test.ts +30 -1
- package/src/core/text.ts +8 -3
- package/src/index.ts +2 -0
- package/src/integration/forget-grep.test.ts +98 -0
- package/src/integration/fusion-dispatch.test.ts +343 -0
- package/src/integration/grep-rg.test.ts +466 -111
- package/src/integration/large-text.test.ts +3 -5
- package/src/integration/mutation-file-types.test.ts +44 -0
- package/src/pi/action-fusion.test.ts +158 -79
- package/src/pi/action-fusion.ts +105 -34
- package/src/pi/anchor-format.test.ts +46 -0
- package/src/pi/anchor-format.ts +21 -2
- package/src/pi/argument-validation.test.ts +136 -0
- package/src/pi/argument-validation.ts +103 -0
- package/src/pi/budgets.ts +4 -1
- package/src/pi/config.test.ts +1 -0
- package/src/pi/config.ts +4 -0
- package/src/pi/diagnostic-buffer.test.ts +58 -0
- package/src/pi/diagnostic-buffer.ts +59 -0
- package/src/pi/directory-sync.test.ts +1 -1
- package/src/pi/edit-tool.ts +56 -37
- package/src/pi/execute.test.ts +185 -645
- package/src/pi/failure-context.test.ts +4 -3
- package/src/pi/failure-path.test.ts +3 -3
- package/src/pi/file-commit.test.ts +24 -17
- package/src/pi/file-commit.ts +36 -9
- package/src/pi/file-snapshot.test.ts +24 -0
- package/src/pi/forget-tool.ts +268 -0
- package/src/pi/forget.test.ts +343 -0
- package/src/pi/forget.testing.ts +273 -0
- package/src/pi/fusion-card.test.ts +26 -0
- package/src/pi/fusion-card.ts +21 -6
- package/src/pi/grep-output.ts +82 -55
- package/src/pi/grep-render.ts +8 -11
- package/src/pi/grep-scope.ts +6 -31
- package/src/pi/grep-search.ts +94 -58
- package/src/pi/grep-tool.ts +50 -59
- package/src/pi/grep.test.ts +412 -208
- package/src/pi/mutation-result.test.ts +23 -0
- package/src/pi/mutation-runner.ts +8 -4
- package/src/pi/path.ts +16 -2
- package/src/pi/pi.test.ts +4 -3
- package/src/pi/read-tool.ts +59 -27
- package/src/pi/read.test.ts +361 -0
- package/src/pi/registration.test.ts +121 -4
- package/src/pi/render.test.ts +172 -15
- package/src/pi/render.ts +28 -5
- package/src/pi/replace-tool.ts +18 -27
- package/src/pi/replace.test.ts +8 -107
- package/src/pi/result-safety.test.ts +123 -149
- package/src/pi/rg-match-bytes.ts +95 -0
- package/src/pi/rg-process.test.ts +40 -59
- package/src/pi/rg-process.ts +8 -5
- package/src/pi/rg-text-view.ts +59 -9
- package/src/pi/text-stream.test.ts +153 -0
- package/src/pi/text-stream.ts +33 -13
- package/src/pi/tool-call.testing.ts +50 -0
- package/src/pi/tool-prompts.ts +15 -0
- package/src/pi/write-tool.ts +19 -26
- package/src/pi/write.test.ts +70 -61
- package/src/pi/e2e-scenarios.test.ts +0 -360
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { createHash, type Hash } from "node:crypto";
|
|
2
|
+
import { searchChangedError } from "./error-text.ts";
|
|
3
|
+
|
|
4
|
+
export interface RawMatchRevision {
|
|
5
|
+
byteOffset: number;
|
|
6
|
+
byteLength: number;
|
|
7
|
+
lineNumber: number;
|
|
8
|
+
endsAtEof: boolean;
|
|
9
|
+
revision: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Retain one bounded digest of the whole rg event, including matched rows omitted by limit. */
|
|
13
|
+
export function rawMatchRevision(
|
|
14
|
+
bytes: Buffer,
|
|
15
|
+
lineNumber: number,
|
|
16
|
+
byteOffset: number | undefined,
|
|
17
|
+
): RawMatchRevision {
|
|
18
|
+
if (
|
|
19
|
+
typeof byteOffset !== "number" ||
|
|
20
|
+
!Number.isSafeInteger(byteOffset) ||
|
|
21
|
+
byteOffset < 0 ||
|
|
22
|
+
!Number.isSafeInteger(byteOffset + bytes.length)
|
|
23
|
+
) {
|
|
24
|
+
throw new Error("Invalid rg raw match byte offset");
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
byteOffset,
|
|
28
|
+
byteLength: bytes.length,
|
|
29
|
+
lineNumber,
|
|
30
|
+
endsAtEof: bytes[bytes.length - 1] !== 10,
|
|
31
|
+
revision: createHash("sha256").update(bytes).digest("hex"),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Verify exact raw match spans and their physical line positions during a bounded file scan. */
|
|
36
|
+
export function rawMatchVerifier(expected: ReadonlySet<RawMatchRevision>) {
|
|
37
|
+
const spans = [...expected].sort((a, b) => a.byteOffset - b.byteOffset);
|
|
38
|
+
let next = 0;
|
|
39
|
+
let offset = 0;
|
|
40
|
+
let lineNumber = 1;
|
|
41
|
+
let lastByte = -1;
|
|
42
|
+
let active: { span: RawMatchRevision; hash: Hash }[] = [];
|
|
43
|
+
return {
|
|
44
|
+
write(bytes: Buffer): void {
|
|
45
|
+
if (next === spans.length && active.length === 0) {
|
|
46
|
+
offset += bytes.length;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const chunkEnd = offset + bytes.length;
|
|
50
|
+
let countedTo = 0;
|
|
51
|
+
const countLinesBefore = (end: number) => {
|
|
52
|
+
let lf: number;
|
|
53
|
+
while ((lf = bytes.indexOf(10, countedTo)) !== -1 && lf < end) {
|
|
54
|
+
lineNumber++;
|
|
55
|
+
countedTo = lf + 1;
|
|
56
|
+
}
|
|
57
|
+
countedTo = end;
|
|
58
|
+
};
|
|
59
|
+
while (next < spans.length && spans[next].byteOffset < chunkEnd) {
|
|
60
|
+
const span = spans[next++];
|
|
61
|
+
const start = span.byteOffset - offset;
|
|
62
|
+
countLinesBefore(start);
|
|
63
|
+
const previousByte = start === 0 ? lastByte : bytes[start - 1];
|
|
64
|
+
if (lineNumber !== span.lineNumber || (span.byteOffset !== 0 && previousByte !== 10)) {
|
|
65
|
+
throw searchChangedError();
|
|
66
|
+
}
|
|
67
|
+
active.push({ span, hash: createHash("sha256") });
|
|
68
|
+
}
|
|
69
|
+
countLinesBefore(bytes.length);
|
|
70
|
+
active = active.filter(({ span, hash }) => {
|
|
71
|
+
const end = span.byteOffset + span.byteLength;
|
|
72
|
+
hash.update(
|
|
73
|
+
bytes.subarray(
|
|
74
|
+
Math.max(0, span.byteOffset - offset),
|
|
75
|
+
Math.min(bytes.length, end - offset),
|
|
76
|
+
),
|
|
77
|
+
);
|
|
78
|
+
if (end > chunkEnd) return true;
|
|
79
|
+
if (hash.digest("hex") !== span.revision) throw searchChangedError();
|
|
80
|
+
return false;
|
|
81
|
+
});
|
|
82
|
+
offset = chunkEnd;
|
|
83
|
+
lastByte = bytes[bytes.length - 1] ?? lastByte;
|
|
84
|
+
},
|
|
85
|
+
end(): void {
|
|
86
|
+
if (
|
|
87
|
+
next !== spans.length ||
|
|
88
|
+
active.length ||
|
|
89
|
+
spans.some((span) => span.endsAtEof && span.byteOffset + span.byteLength !== offset)
|
|
90
|
+
) {
|
|
91
|
+
throw searchChangedError();
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -13,65 +13,46 @@ test("explicit case settings bypass the smart-case probe", async () => {
|
|
|
13
13
|
assert.equal(await resolveIgnoreCase("rg", ["foo"], modes, false, undefined, run), false);
|
|
14
14
|
});
|
|
15
15
|
|
|
16
|
-
test("
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
test("multiline smart-case probe uses the same mode as matching", async () => {
|
|
57
|
-
let args: readonly string[] = [];
|
|
58
|
-
const run: RunText = async (_path, received) => {
|
|
59
|
-
args = received;
|
|
60
|
-
return { code: 0, stdout: "a\n\n", stderr: "" };
|
|
61
|
-
};
|
|
62
|
-
assert.equal(
|
|
63
|
-
await resolveIgnoreCase(
|
|
64
|
-
"rg",
|
|
65
|
-
["foo\\nbar"],
|
|
66
|
-
{ literal: false, multiline: true },
|
|
67
|
-
undefined,
|
|
68
|
-
undefined,
|
|
69
|
-
run,
|
|
70
|
-
),
|
|
71
|
-
true,
|
|
72
|
-
);
|
|
73
|
-
assert.ok(args.includes("--multiline"));
|
|
74
|
-
assert.ok(!args.includes("--no-multiline"));
|
|
16
|
+
test("smart-case probes preserve modes and distinguish the sensor from user matches", async () => {
|
|
17
|
+
for (const { patterns, modes, expectedPatterns } of [
|
|
18
|
+
{ patterns: ["(a)|Foo"], modes: lineModes, expectedPatterns: ["(\\p{Lu})", "(a)|Foo"] },
|
|
19
|
+
{
|
|
20
|
+
patterns: ["foo\\S*"],
|
|
21
|
+
modes: { ...lineModes, literal: true },
|
|
22
|
+
expectedPatterns: ["(\\p{Lu})", "foo\\\\S\\*"],
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
patterns: ["foo\\nbar"],
|
|
26
|
+
modes: { ...lineModes, multiline: true },
|
|
27
|
+
expectedPatterns: ["(\\p{Lu})", "foo\\nbar"],
|
|
28
|
+
},
|
|
29
|
+
]) {
|
|
30
|
+
for (const [code, stdout, expected] of [
|
|
31
|
+
[0, "a\n\n", true],
|
|
32
|
+
[0, "\n", false],
|
|
33
|
+
[1, "", false],
|
|
34
|
+
] as const) {
|
|
35
|
+
let calls = 0;
|
|
36
|
+
const run: RunText = async (_path, args, input) => {
|
|
37
|
+
calls++;
|
|
38
|
+
assert.deepEqual(input, Buffer.from("a\n"));
|
|
39
|
+
assert.ok(args.includes("--smart-case"));
|
|
40
|
+
assert.ok(args.includes("--no-config"));
|
|
41
|
+
assert.equal(args.includes("--multiline"), modes.multiline);
|
|
42
|
+
assert.equal(args.includes("--no-multiline"), !modes.multiline);
|
|
43
|
+
assert.deepEqual(
|
|
44
|
+
args.flatMap((arg, index) => (args[index - 1] === "-e" ? [arg] : [])),
|
|
45
|
+
expectedPatterns,
|
|
46
|
+
);
|
|
47
|
+
return { code, stdout, stderr: "" };
|
|
48
|
+
};
|
|
49
|
+
assert.equal(
|
|
50
|
+
await resolveIgnoreCase("rg", patterns, modes, undefined, undefined, run),
|
|
51
|
+
expected,
|
|
52
|
+
);
|
|
53
|
+
assert.equal(calls, 1);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
75
56
|
});
|
|
76
57
|
|
|
77
58
|
test("smart-case probe propagates parser errors and rejects unknown output", async () => {
|
package/src/pi/rg-process.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* @module pi-hashline-edit/pi
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import { StringDecoder } from "node:string_decoder";
|
|
10
|
+
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
9
11
|
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
10
12
|
import type { Readable } from "node:stream";
|
|
11
13
|
import { escapeRegex } from "../core/text.ts";
|
|
@@ -14,7 +16,7 @@ import { throwIfCancelled } from "./error-text.ts";
|
|
|
14
16
|
export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--no-crlf"];
|
|
15
17
|
export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
|
|
16
18
|
const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB`;
|
|
17
|
-
/**
|
|
19
|
+
/** Bounded ripgrep stderr retains the beginning and end with an omission notice. */
|
|
18
20
|
export const MAX_RG_STDERR_BYTES = 64 * 1024;
|
|
19
21
|
/** Probe runs read only a short stdout; more means an unexpected rg mode. */
|
|
20
22
|
const MAX_RG_PROBE_OUTPUT_BYTES = 64 * 1024;
|
|
@@ -52,7 +54,8 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
|
|
|
52
54
|
shell: false,
|
|
53
55
|
env,
|
|
54
56
|
});
|
|
55
|
-
|
|
57
|
+
const stderr = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
|
|
58
|
+
const stderrDecoder = new StringDecoder("utf8");
|
|
56
59
|
let error: Error | undefined;
|
|
57
60
|
let closed = false;
|
|
58
61
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -66,8 +69,7 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
|
|
|
66
69
|
};
|
|
67
70
|
|
|
68
71
|
child.stderr.on("data", (chunk: Buffer) => {
|
|
69
|
-
|
|
70
|
-
stderr += chunk.toString("utf8").slice(0, MAX_RG_STDERR_BYTES - stderr.length);
|
|
72
|
+
stderr.append(stderrDecoder.write(chunk));
|
|
71
73
|
});
|
|
72
74
|
child.on("error", (cause) => {
|
|
73
75
|
error = cause;
|
|
@@ -83,7 +85,8 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
|
|
|
83
85
|
closed = true;
|
|
84
86
|
if (timer) clearTimeout(timer);
|
|
85
87
|
signal?.removeEventListener("abort", kill);
|
|
86
|
-
|
|
88
|
+
stderr.append(stderrDecoder.end());
|
|
89
|
+
resolve({ code, stderr: stderr.toString(), error });
|
|
87
90
|
});
|
|
88
91
|
});
|
|
89
92
|
signal?.addEventListener("abort", kill, { once: true });
|
package/src/pi/rg-text-view.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
1
3
|
import { mkdtemp, open, rm } from "node:fs/promises";
|
|
2
4
|
import { tmpdir } from "node:os";
|
|
3
5
|
import { join, resolve, sep } from "node:path";
|
|
@@ -11,13 +13,14 @@ import {
|
|
|
11
13
|
runRgPaths,
|
|
12
14
|
type RgRunResult,
|
|
13
15
|
} from "./rg-process.ts";
|
|
14
|
-
import { scopeArgs, type SearchRunner } from "./grep-search.ts";
|
|
16
|
+
import { scopeArgs, type SearchRunner, type SearchTextView } from "./grep-search.ts";
|
|
15
17
|
import { errorMessage } from "../core/errors.ts";
|
|
16
18
|
import { searchChangedError, throwIfCancelled } from "./error-text.ts";
|
|
17
19
|
|
|
18
20
|
/** CRLF snapshot batches flush after this many files or source bytes (README: 64 files / 8 MiB). */
|
|
19
21
|
const SNAPSHOT_BATCH_FILES = 64;
|
|
20
22
|
const SNAPSHOT_BATCH_BYTES = 8 * 1024 * 1024;
|
|
23
|
+
const LF_VIEW = { kind: "lf" } as const;
|
|
21
24
|
|
|
22
25
|
async function writeLfSnapshot(source: string, destination: string, signal?: AbortSignal) {
|
|
23
26
|
const handle = await open(destination, "w");
|
|
@@ -40,15 +43,23 @@ async function writeLfSnapshot(source: string, destination: string, signal?: Abo
|
|
|
40
43
|
}
|
|
41
44
|
|
|
42
45
|
/** Search LF views in batches while reporting original paths and logical match offsets. */
|
|
43
|
-
export const runRgTextView: SearchRunner = async (
|
|
46
|
+
export const runRgTextView: SearchRunner = async (
|
|
47
|
+
rgPath,
|
|
48
|
+
{ matcher, rawMatcher, scope },
|
|
49
|
+
signal,
|
|
50
|
+
onLine,
|
|
51
|
+
) => {
|
|
44
52
|
let directory: string | undefined;
|
|
45
53
|
const result: RgRunResult = { code: 1, stderr: "", stopped: false };
|
|
46
|
-
|
|
54
|
+
const diagnostics = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
|
|
55
|
+
// Only valid UTF-8 CRLF files use LF snapshots; malformed UTF-8 keeps its raw search view.
|
|
47
56
|
const snapshots = new Map<string, string>();
|
|
57
|
+
const views = new Map<string, SearchTextView>();
|
|
48
58
|
const batchPaths: string[] = [];
|
|
49
59
|
let batchBytes = 0;
|
|
50
60
|
const record = (run: RgRunResult) => {
|
|
51
|
-
|
|
61
|
+
diagnostics.append(run.stderr);
|
|
62
|
+
result.stderr = diagnostics.toString();
|
|
52
63
|
if (run.code !== 0 && run.code !== 1 && !run.stopped) result.code = run.code;
|
|
53
64
|
else if (run.code === 0 && result.code === 1) result.code = 0;
|
|
54
65
|
result.stopped ||= run.stopped;
|
|
@@ -57,6 +68,7 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
|
|
|
57
68
|
const searchBatch = async (
|
|
58
69
|
batchPaths: readonly string[],
|
|
59
70
|
rewritePaths: ReadonlyMap<string, string>,
|
|
71
|
+
matcher: readonly string[],
|
|
60
72
|
) => {
|
|
61
73
|
const searchArgs = [
|
|
62
74
|
...matcher,
|
|
@@ -68,13 +80,15 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
|
|
|
68
80
|
];
|
|
69
81
|
const run = await runRg(rgPath, searchArgs, signal, async (line) => {
|
|
70
82
|
const event = JSON.parse(line);
|
|
83
|
+
let view: SearchTextView = LF_VIEW;
|
|
71
84
|
if (event.data?.path) {
|
|
72
85
|
const reported = resolve(rgText(event.data.path));
|
|
86
|
+
view = views.get(reported)!;
|
|
73
87
|
const original = rewritePaths.get(reported);
|
|
74
88
|
if (original) event.data.path = { text: original };
|
|
75
89
|
// Passthrough paths need no rewrite — reported path is already the original.
|
|
76
90
|
}
|
|
77
|
-
return onLine(JSON.stringify(event));
|
|
91
|
+
return onLine(JSON.stringify(event), view);
|
|
78
92
|
});
|
|
79
93
|
record(run);
|
|
80
94
|
};
|
|
@@ -82,9 +96,24 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
|
|
|
82
96
|
const flush = async () => {
|
|
83
97
|
if (!batchPaths.length) return !result.stopped;
|
|
84
98
|
// Scope filtering belongs to the original paths. Snapshot names have no ignore/glob semantics.
|
|
85
|
-
|
|
99
|
+
if (rawMatcher) {
|
|
100
|
+
const groups = new Map<SearchTextView["kind"], string[]>();
|
|
101
|
+
for (const path of batchPaths) {
|
|
102
|
+
const view = views.get(path)!.kind;
|
|
103
|
+
const paths = groups.get(view) ?? [];
|
|
104
|
+
paths.push(path);
|
|
105
|
+
groups.set(view, paths);
|
|
106
|
+
}
|
|
107
|
+
for (const [view, paths] of groups) {
|
|
108
|
+
await searchBatch(paths, snapshots, view === "raw" ? rawMatcher : matcher);
|
|
109
|
+
if (result.stopped) break;
|
|
110
|
+
}
|
|
111
|
+
} else {
|
|
112
|
+
await searchBatch(batchPaths, snapshots, matcher);
|
|
113
|
+
}
|
|
86
114
|
for (const path of snapshots.keys()) await rm(path);
|
|
87
115
|
snapshots.clear();
|
|
116
|
+
views.clear();
|
|
88
117
|
batchPaths.length = 0;
|
|
89
118
|
batchBytes = 0;
|
|
90
119
|
return !result.stopped;
|
|
@@ -109,15 +138,36 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
|
|
|
109
138
|
const original = resolve(path);
|
|
110
139
|
if (directory && original.startsWith(directory + sep)) return true;
|
|
111
140
|
try {
|
|
112
|
-
const
|
|
113
|
-
|
|
141
|
+
const hash = createHash("sha256");
|
|
142
|
+
const info = await scanTextFile(
|
|
143
|
+
original,
|
|
144
|
+
undefined,
|
|
145
|
+
signal,
|
|
146
|
+
(bytes) => hash.update(bytes),
|
|
147
|
+
"lossy",
|
|
148
|
+
);
|
|
149
|
+
if (info.hasNul) return true;
|
|
150
|
+
if (info.hasCrLf && info.validUtf8) {
|
|
114
151
|
const dir = await ensureDirectory();
|
|
115
152
|
const snapshot = join(dir, String(snapshots.size));
|
|
116
153
|
await writeLfSnapshot(original, snapshot, signal);
|
|
117
154
|
snapshots.set(snapshot, original);
|
|
155
|
+
views.set(snapshot, LF_VIEW);
|
|
118
156
|
batchPaths.push(snapshot);
|
|
119
157
|
} else {
|
|
120
|
-
|
|
158
|
+
views.set(
|
|
159
|
+
original,
|
|
160
|
+
info.validUtf8
|
|
161
|
+
? LF_VIEW
|
|
162
|
+
: {
|
|
163
|
+
kind: "raw",
|
|
164
|
+
snapshot: {
|
|
165
|
+
revision: hash.digest("hex"),
|
|
166
|
+
validUtf8: false,
|
|
167
|
+
totalLines: info.totalLines,
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
);
|
|
121
171
|
batchPaths.push(original);
|
|
122
172
|
}
|
|
123
173
|
batchBytes += info.byteLength;
|
|
@@ -116,3 +116,156 @@ test("streamed reads propagate cancellation", async () =>
|
|
|
116
116
|
{ message: "Operation aborted" },
|
|
117
117
|
);
|
|
118
118
|
}));
|
|
119
|
+
|
|
120
|
+
test("lossy decoding reports invalid UTF-8 across chunk boundaries and preserves raw revisions", async () =>
|
|
121
|
+
withFile(async (path) => {
|
|
122
|
+
const source = Buffer.concat([
|
|
123
|
+
Buffer.from("\uFEFF" + "a".repeat(65532)),
|
|
124
|
+
Buffer.from([0xf0, 0x9f]),
|
|
125
|
+
Buffer.from("\r\nneedle "),
|
|
126
|
+
Buffer.from([0xff]),
|
|
127
|
+
Buffer.from("\r\nlast"),
|
|
128
|
+
]);
|
|
129
|
+
await writeFile(path, source);
|
|
130
|
+
const hash = createHash("sha256");
|
|
131
|
+
const lines: string[] = [];
|
|
132
|
+
const stats = await scanTextLines(
|
|
133
|
+
path,
|
|
134
|
+
() => true,
|
|
135
|
+
(line) => lines.push(line.text ?? ""),
|
|
136
|
+
{
|
|
137
|
+
decoding: "lossy",
|
|
138
|
+
onBytes: (bytes) => hash.update(bytes),
|
|
139
|
+
},
|
|
140
|
+
);
|
|
141
|
+
assert.equal(stats.validUtf8, false);
|
|
142
|
+
assert.equal(stats.hasNul, false);
|
|
143
|
+
assert.equal(stats.hasCrLf, true);
|
|
144
|
+
assert.deepEqual(lines, splitLines(source.toString("utf8")));
|
|
145
|
+
assert.equal(hash.digest("hex"), byteRevision(source));
|
|
146
|
+
await assert.rejects(scanTextFile(path), /UNSUPPORTED_ENCODING/);
|
|
147
|
+
}));
|
|
148
|
+
|
|
149
|
+
test("strict scans read all bytes but stop emitting text after a decoding error", async () =>
|
|
150
|
+
withFile(async (path) => {
|
|
151
|
+
const chunkBytes = 64 * 1024;
|
|
152
|
+
const prefix = Buffer.alloc(chunkBytes, "a");
|
|
153
|
+
const invalid = Buffer.alloc(chunkBytes, "b");
|
|
154
|
+
invalid[0] = 0xff;
|
|
155
|
+
const source = Buffer.concat([prefix, invalid, Buffer.from("later text\n")]);
|
|
156
|
+
await writeFile(path, source);
|
|
157
|
+
const emitted: string[] = [];
|
|
158
|
+
const scanned: Buffer[] = [];
|
|
159
|
+
await assert.rejects(
|
|
160
|
+
scanTextFile(
|
|
161
|
+
path,
|
|
162
|
+
(text) => {
|
|
163
|
+
emitted.push(text);
|
|
164
|
+
},
|
|
165
|
+
undefined,
|
|
166
|
+
(bytes) => scanned.push(bytes),
|
|
167
|
+
),
|
|
168
|
+
/UNSUPPORTED_ENCODING/,
|
|
169
|
+
);
|
|
170
|
+
assert.equal(emitted.join(""), prefix.toString("utf8"));
|
|
171
|
+
assert.deepEqual(Buffer.concat(scanned), source);
|
|
172
|
+
}));
|
|
173
|
+
|
|
174
|
+
test("lossy scans flush a multibyte sequence split across chunks and incomplete at EOF", async () =>
|
|
175
|
+
withFile(async (path) => {
|
|
176
|
+
const chunkBytes = 64 * 1024;
|
|
177
|
+
const prefix = Buffer.alloc(chunkBytes - 1, "a");
|
|
178
|
+
const source = Buffer.concat([prefix, Buffer.from([0xf0, 0x9f])]);
|
|
179
|
+
await writeFile(path, source);
|
|
180
|
+
const emitted: string[] = [];
|
|
181
|
+
const stats = await scanTextFile(
|
|
182
|
+
path,
|
|
183
|
+
(text) => {
|
|
184
|
+
emitted.push(text);
|
|
185
|
+
},
|
|
186
|
+
undefined,
|
|
187
|
+
undefined,
|
|
188
|
+
"lossy",
|
|
189
|
+
);
|
|
190
|
+
assert.equal(emitted.join(""), prefix.toString("utf8") + "�");
|
|
191
|
+
assert.equal(emitted.at(-1), "�");
|
|
192
|
+
assert.equal(stats.validUtf8, false);
|
|
193
|
+
assert.equal(stats.hasNul, false);
|
|
194
|
+
assert.equal(stats.byteLength, source.length);
|
|
195
|
+
}));
|
|
196
|
+
|
|
197
|
+
test("lossy scans without a text consumer report validity and retain all raw bytes", async () =>
|
|
198
|
+
withFile(async (path) => {
|
|
199
|
+
const source = Buffer.concat([
|
|
200
|
+
Buffer.from("\ufeffbefore\r\n"),
|
|
201
|
+
Buffer.from([0xff, 0xf0, 0x9f]),
|
|
202
|
+
]);
|
|
203
|
+
await writeFile(path, source);
|
|
204
|
+
const scanned: Buffer[] = [];
|
|
205
|
+
const stats = await scanTextFile(
|
|
206
|
+
path,
|
|
207
|
+
undefined,
|
|
208
|
+
undefined,
|
|
209
|
+
(bytes) => scanned.push(bytes),
|
|
210
|
+
"lossy",
|
|
211
|
+
);
|
|
212
|
+
assert.deepEqual(Buffer.concat(scanned), source);
|
|
213
|
+
assert.equal(stats.validUtf8, false);
|
|
214
|
+
assert.equal(stats.hasNul, false);
|
|
215
|
+
assert.equal(stats.hasCrLf, true);
|
|
216
|
+
assert.equal(stats.totalLines, 2);
|
|
217
|
+
assert.equal(stats.finalNewline, false);
|
|
218
|
+
assert.equal(stats.byteLength, source.length);
|
|
219
|
+
}));
|
|
220
|
+
|
|
221
|
+
test("NUL suppresses its chunk and all later text without flushing a pending sequence", async () =>
|
|
222
|
+
withFile(async (path) => {
|
|
223
|
+
const chunkBytes = 64 * 1024;
|
|
224
|
+
const prefix = Buffer.alloc(chunkBytes - 1, "a");
|
|
225
|
+
const source = Buffer.concat([
|
|
226
|
+
prefix,
|
|
227
|
+
Buffer.from([0xf0, 0, 0x9f]),
|
|
228
|
+
Buffer.alloc(chunkBytes, "b"),
|
|
229
|
+
]);
|
|
230
|
+
await writeFile(path, source);
|
|
231
|
+
for (const decoding of ["strict", "lossy"] as const) {
|
|
232
|
+
const emitted: string[] = [];
|
|
233
|
+
const scanned: Buffer[] = [];
|
|
234
|
+
const stats = await scanTextFile(
|
|
235
|
+
path,
|
|
236
|
+
(text) => {
|
|
237
|
+
emitted.push(text);
|
|
238
|
+
},
|
|
239
|
+
undefined,
|
|
240
|
+
(bytes) => scanned.push(bytes),
|
|
241
|
+
decoding,
|
|
242
|
+
);
|
|
243
|
+
assert.equal(stats.hasNul, true);
|
|
244
|
+
assert.equal(emitted.join(""), prefix.toString("utf8"));
|
|
245
|
+
assert.deepEqual(Buffer.concat(scanned), source);
|
|
246
|
+
}
|
|
247
|
+
}));
|
|
248
|
+
|
|
249
|
+
test("NUL takes precedence over earlier malformed UTF-8 in strict and lossy scans", async () =>
|
|
250
|
+
withFile(async (path) => {
|
|
251
|
+
const chunkBytes = 64 * 1024;
|
|
252
|
+
const invalid = Buffer.alloc(chunkBytes, "a");
|
|
253
|
+
invalid[0] = 0xff;
|
|
254
|
+
const source = Buffer.concat([invalid, Buffer.from("\0later\n")]);
|
|
255
|
+
await writeFile(path, source);
|
|
256
|
+
for (const decoding of ["strict", "lossy"] as const) {
|
|
257
|
+
const emitted: string[] = [];
|
|
258
|
+
const stats = await scanTextFile(
|
|
259
|
+
path,
|
|
260
|
+
(text) => {
|
|
261
|
+
emitted.push(text);
|
|
262
|
+
},
|
|
263
|
+
undefined,
|
|
264
|
+
undefined,
|
|
265
|
+
decoding,
|
|
266
|
+
);
|
|
267
|
+
assert.equal(stats.hasNul, true);
|
|
268
|
+
assert.equal(stats.validUtf8, false);
|
|
269
|
+
assert.equal(emitted.join(""), decoding === "strict" ? "" : invalid.toString("utf8"));
|
|
270
|
+
}
|
|
271
|
+
}));
|
package/src/pi/text-stream.ts
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { createReadStream } from "node:fs";
|
|
2
|
-
import { createUtf8Decoder } from "../core/text.ts";
|
|
2
|
+
import { createUtf8Decoder, type Utf8Decoding } from "../core/text.ts";
|
|
3
3
|
import { throwIfCancelled } from "./error-text.ts";
|
|
4
4
|
|
|
5
|
-
/** Scan
|
|
5
|
+
/** Scan whole-file bytes; lossy decoding reports validity without rejecting malformed UTF-8. */
|
|
6
6
|
export async function scanTextFile(
|
|
7
7
|
path: string,
|
|
8
8
|
onChunk?: (text: string) => void | Promise<void>,
|
|
9
9
|
signal?: AbortSignal,
|
|
10
10
|
onBytes?: (bytes: Buffer) => void,
|
|
11
|
+
decoding: Utf8Decoding = "strict",
|
|
11
12
|
) {
|
|
12
13
|
const decode = createUtf8Decoder();
|
|
14
|
+
// Strict decoding always decides validity; lossy text is decoded only for a chunk consumer.
|
|
15
|
+
const lossy = decoding === "lossy" && onChunk ? createUtf8Decoder("lossy") : undefined;
|
|
13
16
|
let byteLength = 0;
|
|
14
17
|
let lineFeeds = 0;
|
|
15
18
|
let lastByte = -1;
|
|
@@ -31,15 +34,17 @@ export async function scanTextFile(
|
|
|
31
34
|
offset++;
|
|
32
35
|
}
|
|
33
36
|
// NUL takes precedence even when an earlier chunk contained malformed UTF-8.
|
|
34
|
-
if (hasNul
|
|
35
|
-
let text: string;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
if (hasNul) continue;
|
|
38
|
+
let text: string | undefined;
|
|
39
|
+
if (!decodingError) {
|
|
40
|
+
try {
|
|
41
|
+
text = decode(bytes, true);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
decodingError = error;
|
|
44
|
+
}
|
|
41
45
|
}
|
|
42
|
-
|
|
46
|
+
if (lossy) text = lossy(bytes, true);
|
|
47
|
+
if (text !== undefined) await onChunk?.(text);
|
|
43
48
|
}
|
|
44
49
|
} catch (error) {
|
|
45
50
|
// Node's stream abort raises its own AbortError; report the shared cancellation text.
|
|
@@ -48,8 +53,16 @@ export async function scanTextFile(
|
|
|
48
53
|
}
|
|
49
54
|
throwIfCancelled(signal);
|
|
50
55
|
if (!hasNul) {
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
let tail: string | undefined;
|
|
57
|
+
if (!decodingError) {
|
|
58
|
+
try {
|
|
59
|
+
tail = decode();
|
|
60
|
+
} catch (error) {
|
|
61
|
+
decodingError = error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (lossy) tail = lossy();
|
|
65
|
+
else if (decodingError && decoding === "strict") throw decodingError;
|
|
53
66
|
if (tail) await onChunk?.(tail);
|
|
54
67
|
}
|
|
55
68
|
return {
|
|
@@ -58,6 +71,7 @@ export async function scanTextFile(
|
|
|
58
71
|
finalNewline: lastByte === -1 || lastByte === 10,
|
|
59
72
|
hasNul,
|
|
60
73
|
hasCrLf,
|
|
74
|
+
validUtf8: !decodingError,
|
|
61
75
|
};
|
|
62
76
|
}
|
|
63
77
|
|
|
@@ -74,7 +88,12 @@ export async function scanTextLines(
|
|
|
74
88
|
path: string,
|
|
75
89
|
select: (number: number) => boolean,
|
|
76
90
|
onLine: (line: ScannedLine) => void,
|
|
77
|
-
options: {
|
|
91
|
+
options: {
|
|
92
|
+
signal?: AbortSignal;
|
|
93
|
+
maxLineBytes?: number;
|
|
94
|
+
onBytes?: (bytes: Buffer) => void;
|
|
95
|
+
decoding?: Utf8Decoding;
|
|
96
|
+
} = {},
|
|
78
97
|
) {
|
|
79
98
|
const maxBytes = options.maxLineBytes ?? Infinity;
|
|
80
99
|
let number = 1;
|
|
@@ -130,6 +149,7 @@ export async function scanTextLines(
|
|
|
130
149
|
},
|
|
131
150
|
options.signal,
|
|
132
151
|
options.onBytes,
|
|
152
|
+
options.decoding,
|
|
133
153
|
);
|
|
134
154
|
if (!stats.hasNul && byteLength > 0) finish(false);
|
|
135
155
|
return stats;
|