@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 +161 -304
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +10 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +189 -60
- package/src/core/apply.ts +110 -74
- package/src/core/case-fold.test.ts +40 -0
- package/src/core/case-fold.ts +81 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +170 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/lines.ts +7 -0
- package/src/core/regex.ts +21 -0
- package/src/core/replace-schema.ts +34 -0
- package/src/core/replace.ts +37 -54
- package/src/core/search-analysis.test.ts +199 -0
- package/src/core/search-analysis.ts +375 -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 +16 -11
- package/src/index.ts +25 -15
- package/src/integration/config-registration.test.ts +30 -24
- package/src/integration/forget-grep.test.ts +52 -2
- package/src/integration/fusion-dispatch.test.ts +21 -105
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +280 -0
- package/src/integration/grep-js-completeness.test.ts +208 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-path-matrix.test.ts +132 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +410 -0
- package/src/integration/grep-rg.test.ts +220 -402
- package/src/integration/grep-scan-budget.test.ts +89 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +57 -1
- package/src/integration/model-budget-lifecycle.test.ts +128 -0
- package/src/integration/mutation-file-types.test.ts +12 -25
- 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 +123 -0
- package/src/integration/publication-read-changes.test.ts +344 -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 +33 -0
- package/src/integration/replace-worker-boundary.test.ts +107 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +55 -0
- package/src/pi/action-fusion.test.ts +253 -103
- package/src/pi/action-fusion.ts +116 -290
- package/src/pi/anchor-format.ts +9 -0
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +43 -0
- package/src/pi/argument-error.ts +78 -0
- package/src/pi/argument-format.test.ts +208 -0
- package/src/pi/argument-validation.test.ts +742 -45
- package/src/pi/argument-validation.ts +55 -57
- package/src/pi/budgets.ts +45 -16
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +14 -10
- package/src/pi/config.ts +21 -7
- package/src/pi/diagnostic-buffer.test.ts +52 -16
- package/src/pi/diagnostic-buffer.ts +11 -14
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +100 -93
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +362 -315
- 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 +220 -88
- package/src/pi/failure-context.ts +161 -180
- package/src/pi/failure-path.test.ts +85 -88
- package/src/pi/file-commit.test.ts +78 -45
- package/src/pi/file-commit.ts +218 -151
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/forget-tool.ts +189 -90
- package/src/pi/forget.test.ts +309 -22
- package/src/pi/forget.testing.ts +41 -113
- package/src/pi/fusion-card.test.ts +40 -14
- package/src/pi/fusion-card.ts +84 -50
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +193 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-output.ts +181 -138
- package/src/pi/grep-render.ts +28 -25
- package/src/pi/grep-scope.ts +61 -53
- package/src/pi/grep-search.ts +299 -242
- package/src/pi/grep-tool.ts +150 -140
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +631 -632
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +5 -5
- package/src/pi/mutation-result.test.ts +21 -74
- package/src/pi/mutation-result.ts +74 -87
- package/src/pi/mutation-runner.ts +83 -75
- package/src/pi/output-budgets.test.ts +166 -0
- package/src/pi/path.ts +7 -0
- package/src/pi/read-tool.ts +151 -137
- package/src/pi/read.test.ts +39 -33
- package/src/pi/regex-worker-contract.ts +73 -0
- package/src/pi/regex-worker.ts +101 -0
- package/src/pi/registration.test.ts +111 -92
- package/src/pi/render.test.ts +193 -19
- package/src/pi/render.ts +137 -29
- package/src/pi/replace-regex.ts +11 -44
- package/src/pi/replace-tool.ts +38 -145
- package/src/pi/replace-worker-contract.ts +19 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +93 -160
- package/src/pi/report-cause.ts +99 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +512 -0
- package/src/pi/report.test.ts +276 -0
- package/src/pi/report.ts +288 -0
- package/src/pi/result-safety.test.ts +122 -427
- package/src/pi/rg-process.test.ts +78 -79
- package/src/pi/rg-process.ts +124 -177
- package/src/pi/rg-regex.test.ts +50 -0
- package/src/pi/rg-regex.ts +709 -0
- package/src/pi/text-stream.test.ts +67 -38
- package/src/pi/text-stream.ts +96 -75
- package/src/pi/tool-call.testing.ts +3 -39
- package/src/pi/write-tool.ts +45 -34
- package/src/pi/write.test.ts +45 -37
- 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 +308 -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/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,170 @@
|
|
|
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
|
+
/** String representatives of a class; undefined means a string property is not enumerable here. */
|
|
143
|
+
export function classStrings(node: ClassNode): readonly string[] | undefined {
|
|
144
|
+
switch (node.type) {
|
|
145
|
+
case "ExpressionCharacterClass":
|
|
146
|
+
return node.negate ? [] : classStrings(node.expression);
|
|
147
|
+
case "ClassIntersection":
|
|
148
|
+
return classStrings(node.left) ?? classStrings(node.right);
|
|
149
|
+
case "ClassSubtraction":
|
|
150
|
+
return classStrings(node.left);
|
|
151
|
+
case "CharacterClass": {
|
|
152
|
+
if (node.negate) return [];
|
|
153
|
+
const result: string[] = [];
|
|
154
|
+
for (const child of node.elements) {
|
|
155
|
+
const strings = classStrings(child);
|
|
156
|
+
if (!strings) return undefined;
|
|
157
|
+
result.push(...strings);
|
|
158
|
+
}
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
case "ClassStringDisjunction":
|
|
162
|
+
return node.alternatives
|
|
163
|
+
.filter(({ elements }) => elements.length !== 1)
|
|
164
|
+
.map(({ elements }) => elements.map(({ value }) => String.fromCodePoint(value)).join(""));
|
|
165
|
+
case "CharacterSet":
|
|
166
|
+
return node.kind === "property" && node.strings ? undefined : [];
|
|
167
|
+
default:
|
|
168
|
+
return [];
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -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/lines.ts
CHANGED
|
@@ -100,3 +100,10 @@ export function detectLineEnding(text: string): LineEnding {
|
|
|
100
100
|
export function hasFinalNewline(text: string): boolean {
|
|
101
101
|
return text === "" || text.endsWith("\n");
|
|
102
102
|
}
|
|
103
|
+
|
|
104
|
+
/** Physical lines that line feeds separate; a trailing line feed ends the last line. */
|
|
105
|
+
export function countLines(text: string): number {
|
|
106
|
+
let lines = 0;
|
|
107
|
+
for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) lines++;
|
|
108
|
+
return lines + (text && !text.endsWith("\n") ? 1 : 0);
|
|
109
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** JavaScript regex construction on the shared LF view, used by both grep and replace. */
|
|
2
|
+
import { normalizeLineEndings } from "./lines.ts";
|
|
3
|
+
import { escapeRegex } from "./text.ts";
|
|
4
|
+
|
|
5
|
+
/** JavaScript regex source on the shared LF view; literal text matches exactly. */
|
|
6
|
+
export function regexSource(find: string, isRegex: boolean): string {
|
|
7
|
+
const logical = normalizeLineEndings(find);
|
|
8
|
+
return isRegex ? logical : escapeRegex(logical);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Both matcher modes operate on the shared LF view. Flag characters are validated by the tool
|
|
13
|
+
* schema; replace's and grep's prepareArguments also compile regexes here before any file is read.
|
|
14
|
+
*/
|
|
15
|
+
export function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
|
|
16
|
+
const set = new Set((flagsRaw ?? "").split(""));
|
|
17
|
+
set.add("g");
|
|
18
|
+
const flagStr = [...set].join("");
|
|
19
|
+
// The engine's SyntaxError already names the pattern and flags it compiled.
|
|
20
|
+
return new RegExp(regexSource(find, isRegex), flagStr);
|
|
21
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Tool-validated replacement rules and their engine type; no Pi runtime imports. */
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
|
|
4
|
+
export const REGEX_FLAGS_PATTERN = "^[gimsuyd]*$";
|
|
5
|
+
|
|
6
|
+
export const REPLACEMENT_SCHEMA = Type.Object(
|
|
7
|
+
{
|
|
8
|
+
find: Type.String({
|
|
9
|
+
minLength: 1,
|
|
10
|
+
description:
|
|
11
|
+
"Text, or a JavaScript regex when regex is true. 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.",
|
|
12
|
+
}),
|
|
13
|
+
replace: Type.String({
|
|
14
|
+
description:
|
|
15
|
+
"Replacement text; the file's line endings are kept. Literal mode keeps $ as is; regex mode expands $1, $<name>, and $&.",
|
|
16
|
+
}),
|
|
17
|
+
regex: Type.Optional(
|
|
18
|
+
Type.Boolean({ description: "Treat find as a JavaScript regex (default false)." }),
|
|
19
|
+
),
|
|
20
|
+
flags: Type.Optional(
|
|
21
|
+
Type.String({
|
|
22
|
+
pattern: REGEX_FLAGS_PATTERN,
|
|
23
|
+
description: "Extra regex flags, also applied in literal mode; g is always added.",
|
|
24
|
+
}),
|
|
25
|
+
),
|
|
26
|
+
},
|
|
27
|
+
{ additionalProperties: false },
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
export const REPLACEMENTS_SCHEMA = Type.Array(REPLACEMENT_SCHEMA, {
|
|
31
|
+
minItems: 1,
|
|
32
|
+
description: "Rules applied to the original content; inserted text is not searched again.",
|
|
33
|
+
});
|
|
34
|
+
export type Replacement = Readonly<Static<typeof REPLACEMENT_SCHEMA>>;
|
package/src/core/replace.ts
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Replacement engine: apply literal or regex rules (built by regex.ts) over the
|
|
3
|
+
* shared LF view, expand JavaScript replacement tokens, reject rules that match
|
|
4
|
+
* nothing or overlap, and map each change back to the original text with its
|
|
5
|
+
* line endings restored.
|
|
6
|
+
*
|
|
7
|
+
* @module pi-hashline-edit/core
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { buildRegex } from "./regex.ts";
|
|
2
11
|
import {
|
|
3
12
|
createLfTextView,
|
|
4
13
|
detectLineEnding,
|
|
@@ -6,32 +15,10 @@ import {
|
|
|
6
15
|
restoreLineEndings,
|
|
7
16
|
} from "./lines.ts";
|
|
8
17
|
import { findSortedRangeConflict } from "./ranges.ts";
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
export interface Replacement {
|
|
12
|
-
find: string;
|
|
13
|
-
replace: string;
|
|
14
|
-
regex?: boolean;
|
|
15
|
-
flags?: string;
|
|
16
|
-
}
|
|
18
|
+
import { HashlineError } from "./errors.ts";
|
|
17
19
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
* schema; replace's prepareArguments also compiles regex rules here before any file is read.
|
|
21
|
-
*/
|
|
22
|
-
export function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
|
|
23
|
-
const set = new Set((flagsRaw ?? "").split(""));
|
|
24
|
-
set.add("g");
|
|
25
|
-
const flagStr = [...set].join("");
|
|
26
|
-
const logical = normalizeLineEndings(find);
|
|
27
|
-
const source = isRegex ? logical : escapeRegex(logical);
|
|
28
|
-
try {
|
|
29
|
-
return new RegExp(source, flagStr);
|
|
30
|
-
} catch (e) {
|
|
31
|
-
const msg = errorMessage(e);
|
|
32
|
-
throw new Error(`invalid regex /${source}/${flagStr}: ${msg}`);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
20
|
+
import type { Replacement } from "./replace-schema.ts";
|
|
21
|
+
export type { Replacement } from "./replace-schema.ts";
|
|
35
22
|
|
|
36
23
|
/** Expand JS replacement tokens against the original match, including prefix/suffix context. */
|
|
37
24
|
function expandReplacement(template: string, match: RegExpMatchArray, source: string): string {
|
|
@@ -62,41 +49,37 @@ export function applyReplacements(
|
|
|
62
49
|
const view = createLfTextView(source);
|
|
63
50
|
const fallbackEnding = detectLineEnding(source) === "crlf" ? "\r\n" : "\n";
|
|
64
51
|
for (const [index, rule] of rules.entries()) {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
text:
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
if (count === 0)
|
|
85
|
-
throw new Error(
|
|
86
|
-
`no matches for ${rule.regex ? `/${rule.find}/` : JSON.stringify(rule.find)}. Verify the target text with read or grep; check case sensitivity or regex flags if applicable.`,
|
|
87
|
-
);
|
|
88
|
-
} catch (error) {
|
|
89
|
-
throw new Error(`rule ${index}: ${errorMessage(error)}`);
|
|
52
|
+
const regex = buildRegex(rule.find, rule.regex === true, rule.flags);
|
|
53
|
+
let count = 0;
|
|
54
|
+
const replacement = normalizeLineEndings(rule.replace);
|
|
55
|
+
for (const match of view.text.matchAll(regex)) {
|
|
56
|
+
count++;
|
|
57
|
+
const start = view.sourceOffset(match.index!);
|
|
58
|
+
const end = view.sourceOffset(match.index! + match[0].length);
|
|
59
|
+
changes.push({
|
|
60
|
+
start,
|
|
61
|
+
end,
|
|
62
|
+
rule: index,
|
|
63
|
+
text: restoreLineEndings(
|
|
64
|
+
rule.regex ? expandReplacement(replacement, match, view.text) : replacement,
|
|
65
|
+
source.slice(start, end),
|
|
66
|
+
fallbackEnding,
|
|
67
|
+
),
|
|
68
|
+
});
|
|
90
69
|
}
|
|
70
|
+
if (count === 0)
|
|
71
|
+
throw new HashlineError("NO_MATCH", "The rule matches nothing in the file.", {
|
|
72
|
+
facts: { rule: index },
|
|
73
|
+
});
|
|
91
74
|
}
|
|
92
75
|
changes.sort((a, b) => a.start - b.start || a.end - b.end);
|
|
93
76
|
const conflict = findSortedRangeConflict(changes.map((change) => [change.start, change.end]));
|
|
94
77
|
if (conflict !== undefined) {
|
|
95
78
|
const previous = changes[conflict - 1];
|
|
96
79
|
const current = changes[conflict];
|
|
97
|
-
throw new
|
|
98
|
-
|
|
99
|
-
);
|
|
80
|
+
throw new HashlineError("OVERLAPPING_MATCHES", "Matches of the rules overlap.", {
|
|
81
|
+
facts: { rules: [previous.rule, current.rule], offset: current.start },
|
|
82
|
+
});
|
|
100
83
|
}
|
|
101
84
|
const parts: string[] = [];
|
|
102
85
|
let cursor = 0;
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { extractPrefilter, smartIgnoreCase, type Literal } from "./search-analysis.ts";
|
|
4
|
+
import { searchText, type GrepQuery } from "./search.ts";
|
|
5
|
+
import { hasCandidateBytes } from "./search-matrix.testing.ts";
|
|
6
|
+
|
|
7
|
+
const query = (pattern: string, flags = "m", literal = false): GrepQuery => ({
|
|
8
|
+
patterns: [pattern],
|
|
9
|
+
flags,
|
|
10
|
+
literal,
|
|
11
|
+
multiline: true,
|
|
12
|
+
});
|
|
13
|
+
const literal = (text: string): Literal => [...text].map((char) => [char]);
|
|
14
|
+
|
|
15
|
+
for (const [pattern, flags, expected] of [
|
|
16
|
+
["colou?r", "m", [literal("color"), literal("colour")]],
|
|
17
|
+
["a*", "m", undefined],
|
|
18
|
+
["(?:word|)", "m", undefined],
|
|
19
|
+
["[^a]+", "m", undefined],
|
|
20
|
+
["(?=word)", "m", [literal("word")]],
|
|
21
|
+
["(?i:a)(?-i:b)", "m", [[["A", "a"], ["b"]]]],
|
|
22
|
+
["(?-i:a)(?i:b)", "mi", [[["a"], ["B", "b"]]]],
|
|
23
|
+
["k", "mi", [[["K", "k"]]]],
|
|
24
|
+
["s", "mi", [[["S", "s"]]]],
|
|
25
|
+
["k", "miu", [[["K", "k", "K"]]]],
|
|
26
|
+
["s", "miv", [[["S", "s", "ſ"]]]],
|
|
27
|
+
[
|
|
28
|
+
"abéz",
|
|
29
|
+
"miu",
|
|
30
|
+
[
|
|
31
|
+
[
|
|
32
|
+
["A", "a"],
|
|
33
|
+
["B", "b"],
|
|
34
|
+
["É", "é"],
|
|
35
|
+
["Z", "z"],
|
|
36
|
+
],
|
|
37
|
+
],
|
|
38
|
+
],
|
|
39
|
+
["é", "miu", [[["É", "é"]]]],
|
|
40
|
+
["[\\u0100-\\u0200]", "m", undefined],
|
|
41
|
+
] as const) {
|
|
42
|
+
test(`${pattern.slice(0, 80)} /${flags} → conservative candidate literals`, () => {
|
|
43
|
+
assert.deepEqual(
|
|
44
|
+
extractPrefilter(query(pattern, flags)),
|
|
45
|
+
expected ? { kind: "literals", literals: expected } : { kind: "all" },
|
|
46
|
+
);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
for (const boundary of ["\n", "\r\n", "\uFFFD", "\uD800", "\uDC00", "\0"]) {
|
|
51
|
+
test(`literal ${JSON.stringify(boundary)} boundary → no candidate spans changed bytes`, () => {
|
|
52
|
+
const prefilter = extractPrefilter(query(`left${boundary}xy`, "m", true));
|
|
53
|
+
assert.ok(hasCandidateBytes(Buffer.from(`left${boundary}xy`), prefilter));
|
|
54
|
+
assert.ok(hasCandidateBytes(Buffer.from("left\nxy"), prefilter));
|
|
55
|
+
assert.equal(hasCandidateBytes(Buffer.from("left"), prefilter), false);
|
|
56
|
+
assert.equal(hasCandidateBytes(Buffer.from("xy"), prefilter), false);
|
|
57
|
+
assert.deepEqual(extractPrefilter(query(boundary, "m", true)), { kind: "all" });
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
for (const [patterns, isLiteral, expected, flags] of [
|
|
62
|
+
[["foo", "bar"], false, true],
|
|
63
|
+
[["foo", "Bar"], false, false],
|
|
64
|
+
[["foo\\S*", "\\D", "\\W"], false, true],
|
|
65
|
+
[["\\u0041"], false, false],
|
|
66
|
+
[["\\x41"], false, false],
|
|
67
|
+
[["\\u0061"], false, true],
|
|
68
|
+
[["[A-Z]"], false, false],
|
|
69
|
+
[["(?<UPPER>foo)"], false, true],
|
|
70
|
+
[["ς", "σ"], false, true],
|
|
71
|
+
[["σ", "Σ"], false, false],
|
|
72
|
+
[["foo\\S*"], true, false],
|
|
73
|
+
[["\\u0041"], true, true],
|
|
74
|
+
[["foo", "BAR"], true, false],
|
|
75
|
+
[["\\u{41}"], false, false, "u"],
|
|
76
|
+
[["\\u{41}"], false, false, "v"],
|
|
77
|
+
[["\\u{61}"], false, true, "u"],
|
|
78
|
+
[["\\u{61}"], false, true, "v"],
|
|
79
|
+
[["𐐀"], false, false, "u"],
|
|
80
|
+
[["𐐀"], false, false, "v"],
|
|
81
|
+
[["𐐨"], false, true, "u"],
|
|
82
|
+
[["𐐨"], false, true, "v"],
|
|
83
|
+
] as const) {
|
|
84
|
+
test(`${JSON.stringify(patterns)} literal=${isLiteral} flags=${flags ?? ""} → smart case follows decoded letters`, () => {
|
|
85
|
+
assert.equal(smartIgnoreCase(patterns, isLiteral, flags), expected);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
test("seeded random patterns × raw bytes → a JS hit always retains a candidate byte literal", () => {
|
|
90
|
+
let seed = 0x5eed1234;
|
|
91
|
+
const next = (bound: number) => {
|
|
92
|
+
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
|
93
|
+
return seed % bound;
|
|
94
|
+
};
|
|
95
|
+
const atoms = [
|
|
96
|
+
"a",
|
|
97
|
+
"b",
|
|
98
|
+
"k",
|
|
99
|
+
"s",
|
|
100
|
+
"é",
|
|
101
|
+
"😀",
|
|
102
|
+
"\\n",
|
|
103
|
+
"\\r",
|
|
104
|
+
"\\uFFFD",
|
|
105
|
+
"\\uD83D",
|
|
106
|
+
"[ab]",
|
|
107
|
+
"[^b]",
|
|
108
|
+
"\\w",
|
|
109
|
+
".",
|
|
110
|
+
];
|
|
111
|
+
const pieces = [
|
|
112
|
+
Buffer.from("abksABKSéÉKſ😀"),
|
|
113
|
+
Buffer.from("\r\n"),
|
|
114
|
+
Buffer.from("\n"),
|
|
115
|
+
Buffer.from([0xff]),
|
|
116
|
+
Buffer.from([0xc3, 0x28]),
|
|
117
|
+
Buffer.from([0xed, 0xa0, 0x80]),
|
|
118
|
+
];
|
|
119
|
+
const sources = Array.from({ length: 60 }, (_, index) =>
|
|
120
|
+
index % 2 === 0
|
|
121
|
+
? Buffer.concat(Array.from({ length: 1 + next(8) }, () => pieces[next(pieces.length)]))
|
|
122
|
+
: Buffer.from(Array.from({ length: 1 + next(80) }, () => 1 + next(255))),
|
|
123
|
+
);
|
|
124
|
+
const patterns = [
|
|
125
|
+
"colou?r",
|
|
126
|
+
"a\\uFFFDb",
|
|
127
|
+
"😀",
|
|
128
|
+
"k",
|
|
129
|
+
"s",
|
|
130
|
+
"(?:a|é)?b",
|
|
131
|
+
"a\\nb",
|
|
132
|
+
"[ab]+",
|
|
133
|
+
"(?i:a)(?-i:b)",
|
|
134
|
+
];
|
|
135
|
+
for (let index = 0; index < 200; index++) {
|
|
136
|
+
const a = atoms[next(atoms.length)];
|
|
137
|
+
const b = atoms[next(atoms.length)];
|
|
138
|
+
patterns.push(
|
|
139
|
+
[`${a}${b}`, `(?:${a}|${b})`, `(?:${a})?${b}`, `(?:${a})+${b}`, `(?=${a})${b}`][next(5)],
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
let checkedHits = 0;
|
|
143
|
+
let filteredHits = 0;
|
|
144
|
+
for (const pattern of patterns) {
|
|
145
|
+
for (const flags of ["m", "mi", "miu", "miv"]) {
|
|
146
|
+
// Some generated legacy patterns are invalid in Unicode mode; the real boundary rejects them.
|
|
147
|
+
try {
|
|
148
|
+
new RegExp(pattern, flags);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (error instanceof SyntaxError) continue;
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
for (const multiline of [false, true]) {
|
|
154
|
+
const request = { ...query(pattern, flags), multiline };
|
|
155
|
+
const prefilter = extractPrefilter(request);
|
|
156
|
+
for (const bytes of sources) {
|
|
157
|
+
if (
|
|
158
|
+
!searchText({ source: bytes.toString("utf8"), query: request, limit: 1 }).lines.length
|
|
159
|
+
)
|
|
160
|
+
continue;
|
|
161
|
+
checkedHits++;
|
|
162
|
+
if (prefilter.kind === "all") continue;
|
|
163
|
+
filteredHits++;
|
|
164
|
+
assert.ok(
|
|
165
|
+
hasCandidateBytes(bytes, prefilter),
|
|
166
|
+
JSON.stringify({ pattern, flags, multiline, bytes: bytes.toString("hex"), prefilter }),
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
assert.ok(checkedHits > 1000, `Only ${checkedHits} matching cases exercised`);
|
|
173
|
+
assert.ok(filteredHits > 1000, `Only ${filteredHits} filtered matches exercised`);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test("oversized literal alternation → retains necessary prefixes without dropping a branch", () => {
|
|
177
|
+
const words = Array.from({ length: 100 }, (_, index) => `word${index}`);
|
|
178
|
+
const prefilter = extractPrefilter(query(words.join("|")));
|
|
179
|
+
for (const word of words) assert.ok(hasCandidateBytes(Buffer.from(word), prefilter));
|
|
180
|
+
assert.equal(hasCandidateBytes(Buffer.from("unrelated"), prefilter), false);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test("AND and OR file conditions → retain each alternative and require each conjunction", () => {
|
|
184
|
+
const prefilter = extractPrefilter(query("(?:foo.*bar|baz.*qux)"));
|
|
185
|
+
for (const value of ["foo\nbar", "baz\nqux"])
|
|
186
|
+
assert.ok(hasCandidateBytes(Buffer.from(value), prefilter));
|
|
187
|
+
for (const value of ["foo", "bar", "baz", "qux", "foo\nqux", "baz\nbar"])
|
|
188
|
+
assert.equal(hasCandidateBytes(Buffer.from(value), prefilter), false, value);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test("empty expression with a huge repeat → completes without iterating the repeat count", () => {
|
|
192
|
+
assert.deepEqual(extractPrefilter(query("(?:){1000000000}")), { kind: "all" });
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
test("word escape → keeps word-containing files and rejects punctuation-only files", () => {
|
|
196
|
+
const prefilter = extractPrefilter(query("\\w+"));
|
|
197
|
+
assert.ok(hasCandidateBytes(Buffer.from("---a---"), prefilter));
|
|
198
|
+
assert.equal(hasCandidateBytes(Buffer.from("---"), prefilter), false);
|
|
199
|
+
});
|