@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 +78 -369
- package/README.zh-CN.md +162 -0
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +11 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +328 -161
- package/src/core/apply.ts +129 -95
- package/src/core/case-fold.test.ts +44 -0
- package/src/core/case-fold.ts +77 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +184 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/hash.test.ts +1 -25
- package/src/core/hash.ts +0 -5
- package/src/core/lines.ts +32 -7
- package/src/core/ranges.test.ts +41 -9
- package/src/core/ranges.ts +11 -4
- package/src/core/regex.ts +51 -0
- package/src/core/replace-schema.ts +41 -0
- package/src/core/replace.test.ts +90 -0
- package/src/core/replace.ts +40 -56
- package/src/core/search-analysis.test.ts +208 -0
- package/src/core/search-analysis.ts +379 -0
- package/src/core/search-matrix.test.ts +64 -0
- package/src/core/search-matrix.testing.ts +183 -0
- package/src/core/search-schema.ts +18 -0
- package/src/core/search.test.ts +145 -0
- package/src/core/search.ts +119 -0
- package/src/core/text.test.ts +16 -8
- package/src/core/text.ts +26 -6
- package/src/core/types.ts +20 -17
- package/src/index.ts +24 -16
- package/src/integration/config-registration.test.ts +42 -28
- package/src/integration/fusion-dispatch.test.ts +62 -127
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +273 -0
- package/src/integration/grep-js-completeness.test.ts +218 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-order.test.ts +78 -0
- package/src/integration/grep-path-matrix.test.ts +133 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +407 -0
- package/src/integration/grep-rg.test.ts +294 -436
- package/src/integration/grep-scan-budget.test.ts +111 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +56 -1
- package/src/integration/model-budget-lifecycle.test.ts +137 -0
- package/src/integration/mutation-file-types.test.ts +12 -26
- package/src/integration/mutation-file-types.testing.ts +33 -0
- package/src/integration/npm-package.test.ts +17 -0
- package/src/integration/npm-package.testing.ts +97 -0
- package/src/integration/publication-read-changes.test.ts +376 -0
- package/src/integration/read-changes.test.ts +98 -0
- package/src/integration/replace-package.test.ts +17 -36
- package/src/integration/replace-package.testing.ts +36 -0
- package/src/integration/replace-worker-boundary.test.ts +117 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +54 -0
- package/src/pi/action-fusion.test.ts +256 -251
- package/src/pi/action-fusion.ts +121 -332
- package/src/pi/anchor-format.test.ts +16 -0
- package/src/pi/anchor-format.ts +16 -3
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +46 -0
- package/src/pi/argument-error.ts +76 -0
- package/src/pi/argument-format.test.ts +197 -0
- package/src/pi/argument-validation.test.ts +780 -49
- package/src/pi/argument-validation.ts +55 -58
- package/src/pi/budgets.ts +48 -21
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +29 -15
- package/src/pi/config.ts +27 -13
- package/src/pi/diagnostic-buffer.test.ts +51 -16
- package/src/pi/diagnostic-buffer.ts +13 -16
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +103 -99
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +407 -429
- package/src/pi/extension-loading.test.ts +7 -27
- package/src/pi/extension-loading.testing.ts +2 -14
- package/src/pi/failure-context.test.ts +265 -88
- package/src/pi/failure-context.ts +165 -181
- package/src/pi/failure-path.test.ts +179 -117
- package/src/pi/file-commit.test.ts +90 -73
- package/src/pi/file-commit.ts +216 -178
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-revision.ts +25 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/fusion-card-interaction.test.ts +143 -0
- package/src/pi/fusion-card.test.ts +233 -51
- package/src/pi/fusion-card.ts +246 -142
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +191 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-order.test.ts +323 -0
- package/src/pi/grep-output.testing.ts +24 -0
- package/src/pi/grep-output.ts +187 -151
- package/src/pi/grep-render.ts +31 -25
- package/src/pi/grep-scope.ts +62 -54
- package/src/pi/grep-search.ts +327 -241
- package/src/pi/grep-tool.ts +126 -147
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +813 -713
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +6 -7
- package/src/pi/mutation-result.test.ts +45 -91
- package/src/pi/mutation-result.ts +86 -114
- package/src/pi/mutation-runner.ts +81 -81
- package/src/pi/output-budgets.test.ts +175 -0
- package/src/pi/path.ts +10 -1
- package/src/pi/pi.test.ts +4 -5
- package/src/pi/read-tool.ts +108 -142
- package/src/pi/read.test.ts +155 -96
- package/src/pi/regex-worker-contract.ts +55 -0
- package/src/pi/regex-worker.ts +95 -0
- package/src/pi/registration.test.ts +148 -124
- package/src/pi/render.test.ts +361 -84
- package/src/pi/render.ts +150 -32
- package/src/pi/replace-regex.ts +13 -48
- package/src/pi/replace-tool.ts +52 -158
- package/src/pi/replace-worker-contract.ts +10 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +191 -340
- package/src/pi/report-cause.ts +103 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +524 -0
- package/src/pi/report.test.ts +343 -0
- package/src/pi/report.ts +285 -0
- package/src/pi/result-safety.test.ts +216 -481
- package/src/pi/rg-process.test.ts +101 -76
- package/src/pi/rg-process.ts +130 -177
- package/src/pi/rg-regex.test.ts +67 -0
- package/src/pi/rg-regex.ts +715 -0
- package/src/pi/text-stream.test.ts +97 -69
- package/src/pi/text-stream.ts +97 -76
- package/src/pi/tool-call.testing.ts +20 -46
- package/src/pi/write-tool.ts +50 -41
- package/src/pi/write.test.ts +71 -95
- package/src/testing/extension-loader.testing.ts +24 -0
- package/src/testing/installation.testing.ts +77 -0
- package/src/testing/process.testing.ts +33 -0
- package/src/testing/regex-host.testing.ts +20 -0
- package/src/testing/regex-translation-corpus.ts +324 -0
- package/src/testing/rg-line-listing.fixture.mjs +7 -0
- package/src/testing/run-tests.ts +47 -0
- package/src/testing/session.testing.ts +127 -0
- package/src/integration/forget-grep.test.ts +0 -98
- package/src/pi/forget-tool.ts +0 -268
- package/src/pi/forget.test.ts +0 -343
- package/src/pi/forget.testing.ts +0 -273
- package/src/pi/rg-line-ranges.test.ts +0 -66
- package/src/pi/rg-line-ranges.ts +0 -75
- package/src/pi/rg-match-bytes.ts +0 -95
- package/src/pi/rg-text-view.ts +0 -192
- package/src/pi/tool-prompts.ts +0 -15
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/** Character interpretation, intervals, and membership from the running JavaScript engine. */
|
|
2
|
+
import type { AST } from "@eslint-community/regexpp";
|
|
3
|
+
export type CharacterNode =
|
|
4
|
+
| AST.Character
|
|
5
|
+
| AST.CharacterClass
|
|
6
|
+
| AST.ExpressionCharacterClass
|
|
7
|
+
| AST.CharacterSet;
|
|
8
|
+
type ClassNode =
|
|
9
|
+
| CharacterNode
|
|
10
|
+
| AST.CharacterClassElement
|
|
11
|
+
| AST.ClassIntersection
|
|
12
|
+
| AST.ClassSubtraction;
|
|
13
|
+
/** Sorted, disjoint, inclusive code point intervals. */
|
|
14
|
+
export type Ranges = readonly (readonly [number, number])[];
|
|
15
|
+
export const MAX_UNIT = 0xffff;
|
|
16
|
+
export const MAX_SCALAR = 0x10ffff;
|
|
17
|
+
const HIGH_SURROGATE_START = 0xd800;
|
|
18
|
+
const HIGH_SURROGATE_END = 0xdbff;
|
|
19
|
+
const LOW_SURROGATE_START = 0xdc00;
|
|
20
|
+
const LOW_SURROGATE_END = 0xdfff;
|
|
21
|
+
const SURROGATE_BLOCK_SIZE = LOW_SURROGATE_END - LOW_SURROGATE_START + 1;
|
|
22
|
+
const SUPPLEMENTARY_START = MAX_UNIT + 1;
|
|
23
|
+
/** Bound retained native tables independently of the number of queries in a session. */
|
|
24
|
+
const MAX_CACHED_SETS = 64;
|
|
25
|
+
const MAX_CACHED_RANGES = 16 * 1024;
|
|
26
|
+
const MAX_CACHED_SOURCE_UNITS = 8192;
|
|
27
|
+
let cachedRanges = 0;
|
|
28
|
+
const nativeSets = new Map<string, Ranges>();
|
|
29
|
+
|
|
30
|
+
/** Without u, two adjacent Character nodes can encode one supplementary code point. */
|
|
31
|
+
export function surrogatePair(
|
|
32
|
+
element: AST.Element,
|
|
33
|
+
next: AST.Element | undefined,
|
|
34
|
+
): number | undefined {
|
|
35
|
+
if (element.type !== "Character" || next?.type !== "Character") return undefined;
|
|
36
|
+
const [high, low] = [element.value, next.value];
|
|
37
|
+
if (
|
|
38
|
+
high < HIGH_SURROGATE_START ||
|
|
39
|
+
high > HIGH_SURROGATE_END ||
|
|
40
|
+
low < LOW_SURROGATE_START ||
|
|
41
|
+
low > LOW_SURROGATE_END
|
|
42
|
+
)
|
|
43
|
+
return undefined;
|
|
44
|
+
return (
|
|
45
|
+
(high - HIGH_SURROGATE_START) * SURROGATE_BLOCK_SIZE +
|
|
46
|
+
(low - LOW_SURROGATE_START) +
|
|
47
|
+
SUPPLEMENTARY_START
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function normalize(ranges: Iterable<readonly [number, number]>): Ranges {
|
|
52
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
|
|
53
|
+
const merged: [number, number][] = [];
|
|
54
|
+
for (const [low, high] of sorted) {
|
|
55
|
+
const last = merged.at(-1);
|
|
56
|
+
if (last && low <= last[1] + 1) last[1] = Math.max(last[1], high);
|
|
57
|
+
else merged.push([low, high]);
|
|
58
|
+
}
|
|
59
|
+
return merged;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function complement(ranges: Ranges, max: number): Ranges {
|
|
63
|
+
const result: [number, number][] = [];
|
|
64
|
+
let next = 0;
|
|
65
|
+
for (const [low, high] of ranges) {
|
|
66
|
+
if (low > next) result.push([next, low - 1]);
|
|
67
|
+
next = high + 1;
|
|
68
|
+
}
|
|
69
|
+
if (next <= max) result.push([next, max]);
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function intersect(left: Ranges, right: Ranges): Ranges {
|
|
74
|
+
const result: [number, number][] = [];
|
|
75
|
+
let a = 0;
|
|
76
|
+
let b = 0;
|
|
77
|
+
while (a < left.length && b < right.length) {
|
|
78
|
+
const low = Math.max(left[a][0], right[b][0]);
|
|
79
|
+
const high = Math.min(left[a][1], right[b][1]);
|
|
80
|
+
if (low <= high) result.push([low, high]);
|
|
81
|
+
if (left[a][1] < right[b][1]) a++;
|
|
82
|
+
else b++;
|
|
83
|
+
}
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function subtract(ranges: Ranges, removed: Ranges): Ranges {
|
|
88
|
+
return intersect(ranges, complement(normalize(removed), MAX_SCALAR));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const total = (ranges: Ranges): number =>
|
|
92
|
+
ranges.reduce((sum, [low, high]) => sum + high - low + 1, 0);
|
|
93
|
+
export const contains = (ranges: Ranges, point: number): boolean =>
|
|
94
|
+
ranges.some(([low, high]) => low <= point && point <= high);
|
|
95
|
+
|
|
96
|
+
/** Full-string membership, including empty alternatives without the final-newline exception of $. */
|
|
97
|
+
export const membership = (source: string, flags: string): RegExp =>
|
|
98
|
+
new RegExp(`^(?:${source})(?![\\s\\S])`, flags);
|
|
99
|
+
|
|
100
|
+
/** The exact single-character part of a validated expression; flags contain only i, s, u or v. */
|
|
101
|
+
export function nativeCharacterRanges(source: string, flags: string): Ranges {
|
|
102
|
+
const key = `${flags}:${source}`;
|
|
103
|
+
const cached = nativeSets.get(key);
|
|
104
|
+
if (cached) {
|
|
105
|
+
nativeSets.delete(key);
|
|
106
|
+
nativeSets.set(key, cached);
|
|
107
|
+
return cached;
|
|
108
|
+
}
|
|
109
|
+
const native = membership(source, flags);
|
|
110
|
+
const max = flags.includes("u") || flags.includes("v") ? MAX_SCALAR : MAX_UNIT;
|
|
111
|
+
const ranges: [number, number][] = [];
|
|
112
|
+
let start: number | undefined;
|
|
113
|
+
for (let point = 0; point <= max; point++) {
|
|
114
|
+
if (native.test(String.fromCodePoint(point))) start ??= point;
|
|
115
|
+
else if (start !== undefined) {
|
|
116
|
+
ranges.push([start, point - 1]);
|
|
117
|
+
start = undefined;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (start !== undefined) ranges.push([start, max]);
|
|
121
|
+
if (ranges.length <= MAX_CACHED_RANGES && source.length <= MAX_CACHED_SOURCE_UNITS) {
|
|
122
|
+
while (nativeSets.size >= MAX_CACHED_SETS || cachedRanges + ranges.length > MAX_CACHED_RANGES) {
|
|
123
|
+
const oldest = nativeSets.keys().next().value!;
|
|
124
|
+
cachedRanges -= nativeSets.get(oldest)!.length;
|
|
125
|
+
nativeSets.delete(oldest);
|
|
126
|
+
}
|
|
127
|
+
nativeSets.set(key, ranges);
|
|
128
|
+
cachedRanges += ranges.length;
|
|
129
|
+
}
|
|
130
|
+
return ranges;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Close intervals under V8 case equivalence without shipping a second Unicode version. */
|
|
134
|
+
export function foldRanges(ranges: Ranges, unicode: boolean): Ranges {
|
|
135
|
+
if (!ranges.length) return ranges;
|
|
136
|
+
const escape = (point: number) =>
|
|
137
|
+
unicode ? `\\u{${point.toString(16)}}` : `\\u${point.toString(16).padStart(4, "0")}`;
|
|
138
|
+
const source = `[${ranges.map(([low, high]) => (low === high ? escape(low) : `${escape(low)}-${escape(high)}`)).join("")}]`;
|
|
139
|
+
return nativeCharacterRanges(source, unicode ? "iu" : "i");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The multi-character strings a class node matches under `flags`; undefined when a string
|
|
144
|
+
* property cannot be enumerated here.
|
|
145
|
+
*/
|
|
146
|
+
export function acceptedClassStrings(
|
|
147
|
+
node: CharacterNode,
|
|
148
|
+
flags: string,
|
|
149
|
+
): readonly string[] | undefined {
|
|
150
|
+
const strings = classStrings(node);
|
|
151
|
+
if (!strings?.length) return strings;
|
|
152
|
+
const accepts = membership(node.raw, flags);
|
|
153
|
+
return strings.filter((value) => accepts.test(value));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** String representatives of a class; undefined means a string property is not enumerable here. */
|
|
157
|
+
export function classStrings(node: ClassNode): readonly string[] | undefined {
|
|
158
|
+
switch (node.type) {
|
|
159
|
+
case "ExpressionCharacterClass":
|
|
160
|
+
return node.negate ? [] : classStrings(node.expression);
|
|
161
|
+
case "ClassIntersection":
|
|
162
|
+
return classStrings(node.left) ?? classStrings(node.right);
|
|
163
|
+
case "ClassSubtraction":
|
|
164
|
+
return classStrings(node.left);
|
|
165
|
+
case "CharacterClass": {
|
|
166
|
+
if (node.negate) return [];
|
|
167
|
+
const result: string[] = [];
|
|
168
|
+
for (const child of node.elements) {
|
|
169
|
+
const strings = classStrings(child);
|
|
170
|
+
if (!strings) return undefined;
|
|
171
|
+
result.push(...strings);
|
|
172
|
+
}
|
|
173
|
+
return result;
|
|
174
|
+
}
|
|
175
|
+
case "ClassStringDisjunction":
|
|
176
|
+
return node.alternatives
|
|
177
|
+
.filter(({ elements }) => elements.length !== 1)
|
|
178
|
+
.map(({ elements }) => elements.map(({ value }) => String.fromCodePoint(value)).join(""));
|
|
179
|
+
case "CharacterSet":
|
|
180
|
+
return node.kind === "property" && node.strings ? undefined : [];
|
|
181
|
+
default:
|
|
182
|
+
return [];
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { HashlineError } from "./errors.ts";
|
|
4
|
+
|
|
5
|
+
// npm run typecheck checks these invalid callers; they must never run.
|
|
6
|
+
function invalidErrorConstruction() {
|
|
7
|
+
// @ts-expect-error NO_MATCH requires its rule fact.
|
|
8
|
+
new HashlineError("NO_MATCH", "missing");
|
|
9
|
+
// @ts-expect-error NO_MATCH facts cannot contain unrelated fields.
|
|
10
|
+
new HashlineError("NO_MATCH", "missing", { facts: { rule: 0, ids: [] } });
|
|
11
|
+
// @ts-expect-error TARGET_EXISTS has no code facts.
|
|
12
|
+
new HashlineError("TARGET_EXISTS", "exists", { facts: { rule: 0 } });
|
|
13
|
+
// @ts-expect-error Only PATH_NOT_FOUND permits useCreate recovery.
|
|
14
|
+
new HashlineError("NO_MATCH", "missing", { facts: { rule: 0 }, next: "useCreate" });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
test("classified code with required facts → retains facts and native cause", () => {
|
|
18
|
+
const cause = new Error("native failure");
|
|
19
|
+
const failure = new HashlineError("NO_MATCH", "missing", { facts: { rule: 2 }, cause });
|
|
20
|
+
assert.equal(failure.errorCode, "NO_MATCH");
|
|
21
|
+
assert.deepEqual(failure.facts, { rule: 2 });
|
|
22
|
+
assert.equal(failure.cause, cause);
|
|
23
|
+
});
|
package/src/core/errors.ts
CHANGED
|
@@ -1,9 +1,75 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
/**
|
|
2
|
+
* The classified error shared by core and the tool layer.
|
|
3
|
+
*
|
|
4
|
+
* Codes, their facts, and their recovery are defined once in
|
|
5
|
+
* src/pi/report-schema.ts; core imports only its types, which are erased at
|
|
6
|
+
* runtime. src/pi/report.ts turns every failure into the one model-facing report.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ErrorCode, ErrorFacts, NextVariant } from "../pi/report-schema.ts";
|
|
10
|
+
|
|
11
|
+
export type { ErrorCode } from "../pi/report-schema.ts";
|
|
12
|
+
|
|
13
|
+
/** Options of a failure of `C`: its facts are required exactly when the code has required facts. */
|
|
14
|
+
export type HashlineErrorOptions<C extends ErrorCode> = {
|
|
15
|
+
/** The failure beneath this step; reported as structured `cause`, never folded into `message`. */
|
|
16
|
+
readonly cause?: unknown;
|
|
17
|
+
/** One of the code's recovery alternatives; otherwise its default applies. */
|
|
18
|
+
readonly next?: NextVariant<C>;
|
|
19
|
+
} & ({} extends ErrorFacts<C>
|
|
20
|
+
? { readonly facts?: ErrorFacts<C> }
|
|
21
|
+
: { readonly facts: ErrorFacts<C> });
|
|
22
|
+
|
|
23
|
+
export type HashlineErrorArguments<C extends ErrorCode> =
|
|
24
|
+
{} extends HashlineErrorOptions<C>
|
|
25
|
+
? [options?: HashlineErrorOptions<C>]
|
|
26
|
+
: [options: HashlineErrorOptions<C>];
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A classified failure. `message` states what the throwing step found, in its
|
|
30
|
+
* own words; the code's schema fixes which facts it carries.
|
|
31
|
+
*/
|
|
32
|
+
export class HashlineError<C extends ErrorCode = ErrorCode> extends Error {
|
|
33
|
+
readonly errorCode: C;
|
|
34
|
+
readonly facts: ErrorFacts<C> | undefined;
|
|
35
|
+
readonly next: NextVariant<C> | undefined;
|
|
36
|
+
|
|
37
|
+
constructor(code: C, message: string, ...[options]: HashlineErrorArguments<NoInfer<C>>) {
|
|
38
|
+
super(message, options?.cause === undefined ? undefined : { cause: options.cause });
|
|
39
|
+
this.name = "HashlineError";
|
|
40
|
+
this.errorCode = code;
|
|
41
|
+
this.facts = options?.facts;
|
|
42
|
+
this.next = options?.next;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Messages for text that cannot enter or leave a text mutation; argument issues reuse them as reasons. */
|
|
47
|
+
export const TEXT_ERROR_MESSAGES = {
|
|
48
|
+
UNSUPPORTED_ENCODING: "Expected valid UTF-8.",
|
|
49
|
+
UNSUPPORTED_TEXT: "NUL bytes are not editable.",
|
|
50
|
+
INVALID_UNICODE: "Content cannot be encoded losslessly as UTF-8.",
|
|
51
|
+
} as const satisfies Partial<Record<ErrorCode, string>>;
|
|
5
52
|
|
|
6
53
|
/** Message text for a caught value; non-Error throws are stringified. */
|
|
7
54
|
export function errorMessage(error: unknown): string {
|
|
8
55
|
return error instanceof Error ? error.message : String(error);
|
|
9
56
|
}
|
|
57
|
+
|
|
58
|
+
/** Node's errno code of a filesystem error, if any. */
|
|
59
|
+
export function errnoCode(error: unknown): string | undefined {
|
|
60
|
+
return typeof error === "object" &&
|
|
61
|
+
error !== null &&
|
|
62
|
+
"code" in error &&
|
|
63
|
+
typeof error.code === "string"
|
|
64
|
+
? error.code
|
|
65
|
+
: undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Classify a filesystem error: only ENOENT means a missing path; other errno failures keep their cause. */
|
|
69
|
+
export function filesystemErrorCode(
|
|
70
|
+
error: unknown,
|
|
71
|
+
): "PATH_NOT_FOUND" | "FILESYSTEM_ERROR" | undefined {
|
|
72
|
+
const code = errnoCode(error);
|
|
73
|
+
if (code === undefined) return undefined;
|
|
74
|
+
return code === "ENOENT" ? "PATH_NOT_FOUND" : "FILESYSTEM_ERROR";
|
|
75
|
+
}
|
package/src/core/hash.test.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { computeLineHash
|
|
3
|
+
import { computeLineHash } from "./hash.ts";
|
|
4
4
|
|
|
5
5
|
const ALLOWED = new Set("0123456789ABCDEFGHJKMNPQRSTVWXYZ");
|
|
6
6
|
|
|
@@ -21,10 +21,6 @@ test("different content → different hash", () => {
|
|
|
21
21
|
assert.notEqual(computeLineHash(1, "a", 4), computeLineHash(1, "b", 4));
|
|
22
22
|
});
|
|
23
23
|
|
|
24
|
-
test("same (line, content) → same hash", () => {
|
|
25
|
-
assert.equal(computeLineHash(7, "x", 4), computeLineHash(7, "x", 4));
|
|
26
|
-
});
|
|
27
|
-
|
|
28
24
|
test("base32 alphabet (without I/L/O/U) in bulk", () => {
|
|
29
25
|
for (let i = 0; i < 2000; i++) {
|
|
30
26
|
const h = computeLineHash(i + 1, `line ${i}`, 4);
|
|
@@ -32,31 +28,11 @@ test("base32 alphabet (without I/L/O/U) in bulk", () => {
|
|
|
32
28
|
}
|
|
33
29
|
});
|
|
34
30
|
|
|
35
|
-
test("hashFileLines length equals line count", () => {
|
|
36
|
-
assert.equal(hashFileLines(["a", "b", "c"], 4).length, 3);
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
test("hashFileLines empty file", () => {
|
|
40
|
-
assert.deepEqual(hashFileLines([], 4), []);
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
test("hashFileLines normally disambiguates repeated content without changing hash length", () => {
|
|
44
|
-
const lines = ["", "", "", "", "", "}", "}", "}", "return", "return", ",", ","];
|
|
45
|
-
const hashes = hashFileLines(lines, 4);
|
|
46
|
-
assert.equal(new Set(hashes).size, hashes.length, "unexpected collision in fixture");
|
|
47
|
-
for (const h of hashes) assert.equal(h.length, 4, `hash ${h} is not 4 chars`);
|
|
48
|
-
});
|
|
49
|
-
|
|
50
31
|
test("truncated checksums can collide", () => {
|
|
51
32
|
assert.equal(computeLineHash(1, "const value = 558;", 4), "TM02");
|
|
52
33
|
assert.equal(computeLineHash(1, "const value = 9344;", 4), "TM02");
|
|
53
34
|
});
|
|
54
35
|
|
|
55
|
-
test("hashFileLines respects the length parameter", () => {
|
|
56
|
-
assert.equal(hashFileLines(["a", "b"], 6)[0].length, 6);
|
|
57
|
-
assert.equal(hashFileLines(["a", "b"], 4)[0].length, 4);
|
|
58
|
-
});
|
|
59
|
-
|
|
60
36
|
test("hashLen 8 has a leading zero due to the 32-bit hash limit", () => {
|
|
61
37
|
for (let i = 1; i <= 20; i++) {
|
|
62
38
|
const h = computeLineHash(i, `content ${i}`, 8);
|
package/src/core/hash.ts
CHANGED
|
@@ -86,8 +86,3 @@ export const HASH_LEN_MAX = 8;
|
|
|
86
86
|
export function computeLineHash(line: number, content: string, len: number): string {
|
|
87
87
|
return toBase32(fnv1a32Line(line, content), len);
|
|
88
88
|
}
|
|
89
|
-
|
|
90
|
-
/** Compute compact per-line checksums; callers must treat collisions as possible. */
|
|
91
|
-
export function hashFileLines(lines: readonly string[], len: number): string[] {
|
|
92
|
-
return lines.map((content, i) => computeLineHash(i + 1, content, len));
|
|
93
|
-
}
|
package/src/core/lines.ts
CHANGED
|
@@ -37,11 +37,33 @@ export function replacementSeparator(
|
|
|
37
37
|
return separators[index] || separators[separators.length - 1] || fallback;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
/** Keep a trailing CR as content when the following fragment starts with an LF separator. */
|
|
41
|
+
function preserveBoundaryCarriageReturn(previous: string, next: string): string {
|
|
42
|
+
return previous.endsWith("\r") && next.startsWith("\n") ? `\r${next}` : next;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Join independent raw fragments without absorbing trailing CR content into the next LF. */
|
|
46
|
+
export function joinTextFragments(parts: readonly string[]): string {
|
|
47
|
+
const joined: string[] = [];
|
|
48
|
+
let previous = "";
|
|
49
|
+
for (const part of parts) {
|
|
50
|
+
if (!part) continue;
|
|
51
|
+
joined.push(preserveBoundaryCarriageReturn(previous, part));
|
|
52
|
+
previous = part;
|
|
53
|
+
}
|
|
54
|
+
return joined.join("");
|
|
55
|
+
}
|
|
56
|
+
|
|
40
57
|
/** Restore a logical replacement without normalizing it a second time. */
|
|
41
58
|
export function restoreLineEndings(logical: string, original: string, fallback: string): string {
|
|
42
59
|
const separators = lineSeparators(original);
|
|
43
60
|
let index = 0;
|
|
44
|
-
return logical.replace(/\n/g, (
|
|
61
|
+
return logical.replace(/\n/g, (_match, offset: number) =>
|
|
62
|
+
preserveBoundaryCarriageReturn(
|
|
63
|
+
logical[offset - 1] ?? "",
|
|
64
|
+
replacementSeparator(separators, index++, fallback),
|
|
65
|
+
),
|
|
66
|
+
);
|
|
45
67
|
}
|
|
46
68
|
|
|
47
69
|
/** Build an LF matching view with UTF-16 boundary offsets back into the original text. */
|
|
@@ -76,12 +98,8 @@ export function createLfTextView(source: string) {
|
|
|
76
98
|
*/
|
|
77
99
|
export function splitLines(text: string): string[] {
|
|
78
100
|
if (text === "") return [];
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
}
|
|
82
|
-
const normalized = text.replaceAll("\r\n", "\n");
|
|
83
|
-
const lines = (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
|
|
84
|
-
return lines;
|
|
101
|
+
const normalized = normalizeLineEndings(text);
|
|
102
|
+
return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
|
|
85
103
|
}
|
|
86
104
|
|
|
87
105
|
/** Whether the text uses CRLF at all (any `\r\n` counts; mixed files report "crlf"). */
|
|
@@ -100,3 +118,10 @@ export function detectLineEnding(text: string): LineEnding {
|
|
|
100
118
|
export function hasFinalNewline(text: string): boolean {
|
|
101
119
|
return text === "" || text.endsWith("\n");
|
|
102
120
|
}
|
|
121
|
+
|
|
122
|
+
/** Physical lines that line feeds separate; a trailing line feed ends the last line. */
|
|
123
|
+
export function countLines(text: string): number {
|
|
124
|
+
let lines = 0;
|
|
125
|
+
for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) lines++;
|
|
126
|
+
return lines + (text && !text.endsWith("\n") ? 1 : 0);
|
|
127
|
+
}
|
package/src/core/ranges.test.ts
CHANGED
|
@@ -2,15 +2,16 @@ import assert from "node:assert/strict";
|
|
|
2
2
|
import { test } from "node:test";
|
|
3
3
|
import { findSortedRangeConflict, mergeRanges, type HalfOpenRange } from "./ranges.ts";
|
|
4
4
|
|
|
5
|
-
test("
|
|
6
|
-
const cases: [HalfOpenRange[], number | undefined][] = [
|
|
7
|
-
[[], undefined],
|
|
5
|
+
test("sorted ranges → ordered starts allow only empty ranges before a shared start", () => {
|
|
6
|
+
const cases: [HalfOpenRange[], number | undefined, number | undefined][] = [
|
|
7
|
+
[[], undefined, undefined],
|
|
8
8
|
[
|
|
9
9
|
[
|
|
10
10
|
[0, 2],
|
|
11
11
|
[2, 4],
|
|
12
12
|
],
|
|
13
13
|
undefined,
|
|
14
|
+
undefined,
|
|
14
15
|
],
|
|
15
16
|
[
|
|
16
17
|
[
|
|
@@ -18,6 +19,7 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
|
|
|
18
19
|
[2, 2],
|
|
19
20
|
],
|
|
20
21
|
undefined,
|
|
22
|
+
undefined,
|
|
21
23
|
],
|
|
22
24
|
[
|
|
23
25
|
[
|
|
@@ -25,13 +27,24 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
|
|
|
25
27
|
[0, 0],
|
|
26
28
|
],
|
|
27
29
|
1,
|
|
30
|
+
undefined,
|
|
31
|
+
],
|
|
32
|
+
[
|
|
33
|
+
[
|
|
34
|
+
[0, 0],
|
|
35
|
+
[0, 2],
|
|
36
|
+
],
|
|
37
|
+
1,
|
|
38
|
+
undefined,
|
|
28
39
|
],
|
|
29
40
|
[
|
|
30
41
|
[
|
|
42
|
+
[0, 0],
|
|
31
43
|
[0, 0],
|
|
32
44
|
[0, 2],
|
|
33
45
|
],
|
|
34
46
|
1,
|
|
47
|
+
undefined,
|
|
35
48
|
],
|
|
36
49
|
[
|
|
37
50
|
[
|
|
@@ -39,6 +52,7 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
|
|
|
39
52
|
[1, 1],
|
|
40
53
|
],
|
|
41
54
|
1,
|
|
55
|
+
1,
|
|
42
56
|
],
|
|
43
57
|
[
|
|
44
58
|
[
|
|
@@ -46,6 +60,15 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
|
|
|
46
60
|
[1, 2],
|
|
47
61
|
],
|
|
48
62
|
1,
|
|
63
|
+
1,
|
|
64
|
+
],
|
|
65
|
+
[
|
|
66
|
+
[
|
|
67
|
+
[0, 2],
|
|
68
|
+
[0, 3],
|
|
69
|
+
],
|
|
70
|
+
1,
|
|
71
|
+
1,
|
|
49
72
|
],
|
|
50
73
|
[
|
|
51
74
|
[
|
|
@@ -54,14 +77,23 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
|
|
|
54
77
|
[1, 3],
|
|
55
78
|
],
|
|
56
79
|
2,
|
|
80
|
+
2,
|
|
57
81
|
],
|
|
58
82
|
];
|
|
59
|
-
for (const [ranges,
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
83
|
+
for (const [ranges, strictConflict, orderedConflict] of cases) {
|
|
84
|
+
for (const orderedStarts of [false, true]) {
|
|
85
|
+
const expected = orderedStarts ? orderedConflict : strictConflict;
|
|
86
|
+
for (const shift of [0, 10]) {
|
|
87
|
+
assert.equal(
|
|
88
|
+
findSortedRangeConflict(
|
|
89
|
+
ranges.map(([start, end]) => [start + shift, end + shift]),
|
|
90
|
+
orderedStarts,
|
|
91
|
+
),
|
|
92
|
+
expected,
|
|
93
|
+
JSON.stringify({ ranges, orderedStarts, shift }),
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
65
97
|
}
|
|
66
98
|
});
|
|
67
99
|
|
package/src/core/ranges.ts
CHANGED
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
/** Half-open bounds in a caller-selected unit (line indices or string offsets). */
|
|
2
2
|
export type HalfOpenRange = readonly [start: number, end: number];
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Find the first conflicting pair's second index. Input must be sorted by start, then end,
|
|
6
|
+
* with ties in caller order. A range starting inside an earlier non-empty range always
|
|
7
|
+
* conflicts. An insertion (empty range) at a shared start conflicts unless `orderedStarts`
|
|
8
|
+
* is set; then it applies in input order before the range that starts there.
|
|
9
|
+
*/
|
|
10
|
+
export function findSortedRangeConflict(
|
|
11
|
+
ranges: readonly HalfOpenRange[],
|
|
12
|
+
orderedStarts = false,
|
|
13
|
+
): number | undefined {
|
|
6
14
|
for (let i = 1; i < ranges.length; i++) {
|
|
7
15
|
const previous = ranges[i - 1];
|
|
8
16
|
const current = ranges[i];
|
|
9
|
-
|
|
10
|
-
if (current[0] < previous[1] || current[0] === previous[0]) return i;
|
|
17
|
+
if (current[0] < previous[1] || (!orderedStarts && current[0] === previous[0])) return i;
|
|
11
18
|
}
|
|
12
19
|
return undefined;
|
|
13
20
|
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** JavaScript regex construction on the shared LF view, used by both grep and replace. */
|
|
2
|
+
import { errorMessage } from "./errors.ts";
|
|
3
|
+
import { normalizeLineEndings } from "./lines.ts";
|
|
4
|
+
import { escapeRegex } from "./text.ts";
|
|
5
|
+
|
|
6
|
+
/** JavaScript regex source on the shared LF view; literal text matches exactly. */
|
|
7
|
+
export function regexSource(find: string, literal: boolean): string {
|
|
8
|
+
const logical = normalizeLineEndings(find);
|
|
9
|
+
return literal ? escapeRegex(logical) : logical;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Both matcher modes operate on the shared LF view. Replace's and grep's prepareArguments
|
|
14
|
+
* validate flags and compile regexes through checkRegexArguments before any file is read.
|
|
15
|
+
*/
|
|
16
|
+
export function buildRegex(find: string, literal: boolean, flagsRaw: string | undefined): RegExp {
|
|
17
|
+
const set = new Set((flagsRaw ?? "").split(""));
|
|
18
|
+
set.add("g");
|
|
19
|
+
const flagStr = [...set].join("");
|
|
20
|
+
// The engine's SyntaxError already names the pattern and flags it compiled.
|
|
21
|
+
return new RegExp(regexSource(find, literal), flagStr);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Report V8's diagnostics for a rule's flags and, in regex mode, for each pattern that
|
|
26
|
+
* buildRegex would reject. Invalid flags stop the check, since every pattern compiles with
|
|
27
|
+
* them; values that are not non-empty strings are left to schema validation.
|
|
28
|
+
*/
|
|
29
|
+
export function checkRegexArguments(
|
|
30
|
+
flagsField: string,
|
|
31
|
+
flags: string | undefined,
|
|
32
|
+
literal: boolean,
|
|
33
|
+
patterns: readonly (readonly [field: string, value: unknown])[],
|
|
34
|
+
report: (field: string, reason: string) => void,
|
|
35
|
+
): void {
|
|
36
|
+
try {
|
|
37
|
+
buildRegex("", true, flags);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
report(flagsField, errorMessage(error));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (literal) return;
|
|
43
|
+
for (const [field, value] of patterns) {
|
|
44
|
+
if (typeof value !== "string" || value === "") continue;
|
|
45
|
+
try {
|
|
46
|
+
buildRegex(value, false, flags);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
report(field, errorMessage(error));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Tool-validated replacement rules, the engine's result, and their types; no Pi runtime imports. */
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
|
|
4
|
+
const REPLACEMENT_SCHEMA = Type.Object(
|
|
5
|
+
{
|
|
6
|
+
find: Type.String({
|
|
7
|
+
minLength: 1,
|
|
8
|
+
description:
|
|
9
|
+
"What to match: plain text when literal is true, a JavaScript regex when false. CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
|
|
10
|
+
}),
|
|
11
|
+
literal: Type.Boolean({
|
|
12
|
+
description:
|
|
13
|
+
"true: find matches exactly, including regex punctuation, and replace keeps $ as is. false: find is a JavaScript regex and replace expands $1, $<name>, and $&; use it only for an intentional regex.",
|
|
14
|
+
}),
|
|
15
|
+
replace: Type.String({
|
|
16
|
+
description: "Replacement text; the file's line endings are kept.",
|
|
17
|
+
}),
|
|
18
|
+
flags: Type.Optional(
|
|
19
|
+
Type.String({
|
|
20
|
+
description: "Extra regex flags, also applied in literal mode; g is always added.",
|
|
21
|
+
}),
|
|
22
|
+
),
|
|
23
|
+
},
|
|
24
|
+
{ additionalProperties: false },
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
export const REPLACEMENTS_SCHEMA = Type.Array(REPLACEMENT_SCHEMA, {
|
|
28
|
+
minItems: 1,
|
|
29
|
+
description: "Rules applied to the original content; inserted text is not searched again.",
|
|
30
|
+
});
|
|
31
|
+
export type Replacement = Readonly<Static<typeof REPLACEMENT_SCHEMA>>;
|
|
32
|
+
|
|
33
|
+
/** A replacement batch's new text and match count; the host checks it again across the worker boundary. */
|
|
34
|
+
export const REPLACEMENT_RESULT_SCHEMA = Type.Object(
|
|
35
|
+
{
|
|
36
|
+
text: Type.String(),
|
|
37
|
+
count: Type.Integer({ minimum: 1 }),
|
|
38
|
+
},
|
|
39
|
+
{ additionalProperties: false },
|
|
40
|
+
);
|
|
41
|
+
export type ReplacementResult = Static<typeof REPLACEMENT_RESULT_SCHEMA>;
|