@criogaid/pi-hashline-edit 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -4,12 +4,19 @@ import { computeLineHash } from "./hash.ts";
4
4
 
5
5
  const ALLOWED = new Set("0123456789ABCDEFGHJKMNPQRSTVWXYZ");
6
6
 
7
- test("computeLineHash is stable and base32", () => {
7
+ test("computeLineHash is stable and uses the configured base32 length", () => {
8
8
  const a = computeLineHash(3, "code", 4);
9
9
  const b = computeLineHash(3, "code", 4);
10
10
  assert.equal(a, b);
11
11
  assert.equal(a.length, 4);
12
12
  for (const ch of a) assert.ok(ALLOWED.has(ch), `bad char ${ch}`);
13
+ for (let i = 0; i < 2000; i++) {
14
+ const hash = computeLineHash(i + 1, `line ${i}`, 4);
15
+ for (const ch of hash) assert.ok(ALLOWED.has(ch), `bad char ${ch} in ${hash}`);
16
+ }
17
+ for (let i = 1; i <= 20; i++) {
18
+ assert.equal(computeLineHash(i, `content ${i}`, 8).length, 8);
19
+ }
13
20
  });
14
21
 
15
22
  test("different line number → different hash (even for identical content)", () => {
@@ -21,26 +28,11 @@ test("different content → different hash", () => {
21
28
  assert.notEqual(computeLineHash(1, "a", 4), computeLineHash(1, "b", 4));
22
29
  });
23
30
 
24
- test("base32 alphabet (without I/L/O/U) in bulk", () => {
25
- for (let i = 0; i < 2000; i++) {
26
- const h = computeLineHash(i + 1, `line ${i}`, 4);
27
- for (const ch of h) assert.ok(ALLOWED.has(ch), `bad char ${ch} in ${h}`);
28
- }
29
- });
30
-
31
31
  test("truncated checksums can collide", () => {
32
32
  assert.equal(computeLineHash(1, "const value = 558;", 4), "TM02");
33
33
  assert.equal(computeLineHash(1, "const value = 9344;", 4), "TM02");
34
34
  });
35
35
 
36
- test("hashLen 8 has a leading zero due to the 32-bit hash limit", () => {
37
- for (let i = 1; i <= 20; i++) {
38
- const h = computeLineHash(i, `content ${i}`, 8);
39
- assert.equal(h.length, 8);
40
- assert.equal(h[0], "0");
41
- }
42
- });
43
-
44
36
  test("computeLineHash produces output identical to hashing full interpolated string", () => {
45
37
  function referenceHash(line: number, content: string, len: number): string {
46
38
  let h = 0x811c9dc5;
package/src/core/hash.ts CHANGED
@@ -28,8 +28,8 @@ export const HASH_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
28
28
  * distributed, non-cryptographic. Uses `Math.imul` for correct 32-bit integer
29
29
  * multiplication under JS.
30
30
  */
31
- function fnv1a32(str: string, seed = 0x811c9dc5): number {
32
- let h = seed;
31
+ function fnv1a32(str: string): number {
32
+ let h = 0x811c9dc5;
33
33
  for (let i = 0; i < str.length; i++) {
34
34
  h ^= str.charCodeAt(i);
35
35
  h = Math.imul(h, 0x01000193);
@@ -37,26 +37,6 @@ function fnv1a32(str: string, seed = 0x811c9dc5): number {
37
37
  return h >>> 0;
38
38
  }
39
39
 
40
- /**
41
- * Compute the FNV-1a 32-bit hash of `${line}\n${content}` without allocating
42
- * the intermediate template string.
43
- */
44
- function fnv1a32Line(line: number, content: string): number {
45
- let h = 0x811c9dc5;
46
- // Feed digit characters of the line number without String(line) allocation.
47
- let n = line;
48
- let divisor = 1;
49
- while (divisor * 10 <= n) divisor *= 10;
50
- while (divisor >= 1) {
51
- h ^= (((n / divisor) | 0) % 10) + 48;
52
- h = Math.imul(h, 0x01000193);
53
- divisor = (divisor / 10) | 0;
54
- }
55
- h ^= 10;
56
- h = Math.imul(h, 0x01000193);
57
- return fnv1a32(content, h);
58
- }
59
-
60
40
  /**
61
41
  * Encode a 32-bit integer into a base32 string of the given length.
62
42
  *
@@ -84,5 +64,5 @@ export const HASH_LEN_MAX = 8;
84
64
  * @param len caller-selected hash length
85
65
  */
86
66
  export function computeLineHash(line: number, content: string, len: number): string {
87
- return toBase32(fnv1a32Line(line, content), len);
67
+ return toBase32(fnv1a32(`${line}\n${content}`), len);
88
68
  }
package/src/core/lines.ts CHANGED
@@ -16,8 +16,6 @@
16
16
  * @module pi-hashline-edit/core
17
17
  */
18
18
 
19
- import type { LineEnding } from "./types.ts";
20
-
21
19
  /** Normalize CRLF boundaries to LF; standalone CR remains content. */
22
20
  export function normalizeLineEndings(text: string): string {
23
21
  return text.replace(/\r\n/g, "\n");
@@ -69,7 +67,7 @@ export function restoreLineEndings(logical: string, original: string, fallback:
69
67
  /** Build an LF matching view with UTF-16 boundary offsets back into the original text. */
70
68
  export function createLfTextView(source: string) {
71
69
  const removed: number[] = [];
72
- for (const match of source.matchAll(/\r\n/g)) removed.push(match.index! - removed.length);
70
+ for (const match of source.matchAll(/\r\n/g)) removed.push(match.index - removed.length);
73
71
  return {
74
72
  text: normalizeLineEndings(source),
75
73
  sourceOffset(offset: number): number {
@@ -103,7 +101,7 @@ export function splitLines(text: string): string[] {
103
101
  }
104
102
 
105
103
  /** Whether the text uses CRLF at all (any `\r\n` counts; mixed files report "crlf"). */
106
- export function detectLineEnding(text: string): LineEnding {
104
+ export function detectLineEnding(text: string): "lf" | "crlf" {
107
105
  return text.includes("\r\n") ? "crlf" : "lf";
108
106
  }
109
107
 
@@ -1,6 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
- import { findSortedRangeConflict, mergeRanges, type HalfOpenRange } from "./ranges.ts";
3
+ import { findSortedRangeConflict, mergeRanges } from "./ranges.ts";
4
+ type HalfOpenRange = Parameters<typeof findSortedRangeConflict>[0][number];
4
5
 
5
6
  test("sorted ranges sharing or crossing boundaries → report conflicts according to insertion policy", () => {
6
7
  const cases: [HalfOpenRange[], number | undefined, number | undefined][] = [
@@ -1,5 +1,5 @@
1
1
  /** Half-open bounds in a caller-selected unit (line indices or string offsets). */
2
- export type HalfOpenRange = readonly [start: number, end: number];
2
+ type HalfOpenRange = readonly [start: number, end: number];
3
3
 
4
4
  /**
5
5
  * Find the first conflicting pair's second index. Input must be sorted by start, then end.
package/src/core/regex.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  /** JavaScript regex construction on the shared LF view, used by both grep and replace. */
2
2
  import { errorMessage } from "./errors.ts";
3
3
  import { normalizeLineEndings } from "./lines.ts";
4
- import { escapeRegex } from "./text.ts";
5
4
 
6
5
  /** JavaScript regex source on the shared LF view; literal text matches exactly. */
7
6
  export function regexSource(find: string, literal: boolean): string {
8
7
  const logical = normalizeLineEndings(find);
9
- return literal ? escapeRegex(logical) : logical;
8
+ return literal ? logical.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : logical;
10
9
  }
11
10
 
12
11
  /**
@@ -24,7 +23,7 @@ export function buildRegex(find: string, literal: boolean, flagsRaw: string | un
24
23
  /**
25
24
  * Report V8's diagnostics for a rule's flags and, in regex mode, for each pattern that
26
25
  * 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.
26
+ * them; values that are not strings are left to schema validation.
28
27
  */
29
28
  export function checkRegexArguments(
30
29
  flagsField: string,
@@ -41,7 +40,7 @@ export function checkRegexArguments(
41
40
  }
42
41
  if (literal) return;
43
42
  for (const [field, value] of patterns) {
44
- if (typeof value !== "string" || value === "") continue;
43
+ if (typeof value !== "string") continue;
45
44
  try {
46
45
  buildRegex(value, false, flags);
47
46
  } catch (error) {
@@ -1,6 +1,8 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { applyReplacements, type Replacement } from "./replace.ts";
3
+ import { applyReplacements } from "./replace.ts";
4
+ import type { Replacement } from "./replace-schema.ts";
5
+ import { HashlineError } from "./errors.ts";
4
6
 
5
7
  test("replacement joins beside LF → preserve standalone CR content", async (t) => {
6
8
  const literal = (find: string, replace: string): Replacement => ({
@@ -88,3 +90,47 @@ test("replacement joins beside LF → preserve standalone CR content", async (t)
88
90
  });
89
91
  }
90
92
  });
93
+
94
+ test("replacement rejection → reports all unmatched rules or the conflicting rule pair and line", async (t) => {
95
+ const literal = (find: string): Replacement => ({ find, replace: "x", literal: true });
96
+ const cases = [
97
+ {
98
+ name: "multiple unmatched rules",
99
+ source: "present",
100
+ rules: [literal("missing"), literal("present"), literal("absent")],
101
+ code: "NO_MATCH",
102
+ message: "Rules match nothing in the file.",
103
+ facts: { unmatched: ["replacements[0]", "replacements[2]"] },
104
+ },
105
+ ...["\n", "\r\n"].map((eol) => ({
106
+ name: `overlap in reversed input order with ${JSON.stringify(eol)}`,
107
+ source: `head${eol}abcd${eol}tail`,
108
+ rules: [literal("cd"), literal("bc")],
109
+ code: "OVERLAPPING_MATCHES",
110
+ message: "Matches of two rules overlap.",
111
+ facts: { conflict: ["replacements[0]", "replacements[1]"], line: 2 },
112
+ })),
113
+ {
114
+ name: "overlap on first line",
115
+ source: "abcd",
116
+ rules: [literal("ab"), literal("bc")],
117
+ code: "OVERLAPPING_MATCHES",
118
+ message: "Matches of two rules overlap.",
119
+ facts: { conflict: ["replacements[0]", "replacements[1]"], line: 1 },
120
+ },
121
+ ];
122
+ for (const { name, source, rules, code, message, facts } of cases) {
123
+ await t.test(name, () => {
124
+ assert.throws(
125
+ () => applyReplacements(source, rules),
126
+ (error: unknown) => {
127
+ assert.ok(error instanceof HashlineError);
128
+ assert.equal(error.errorCode, code);
129
+ assert.equal(error.message, message);
130
+ assert.deepEqual(error.facts, facts);
131
+ return true;
132
+ },
133
+ );
134
+ });
135
+ }
136
+ });
@@ -19,10 +19,9 @@ import { findSortedRangeConflict } from "./ranges.ts";
19
19
  import { HashlineError } from "./errors.ts";
20
20
 
21
21
  import type { Replacement, ReplacementResult } from "./replace-schema.ts";
22
- export type { Replacement } from "./replace-schema.ts";
23
22
 
24
23
  /** Expand JS replacement tokens against the original match, including prefix/suffix context. */
25
- function expandReplacement(template: string, match: RegExpMatchArray, source: string): string {
24
+ function expandReplacement(template: string, match: RegExpExecArray, source: string): string {
26
25
  // Without named captures, $<...> is ordinary text and may contain other $ tokens.
27
26
  const tokens =
28
27
  match.groups === undefined ? /\$(\$|&|`|'|\d{1,2})/g : /\$(\$|&|`|'|<[^>]*>|\d{1,2})/g;
@@ -30,9 +29,8 @@ function expandReplacement(template: string, match: RegExpMatchArray, source: st
30
29
  if (key === "$") return "$";
31
30
  if (key === "&") return match[0];
32
31
  if (key === "`") return source.slice(0, match.index);
33
- if (key === "'") return source.slice(match.index! + match[0].length);
34
- if (key.startsWith("<"))
35
- return match.groups === undefined ? token : (match.groups[key.slice(1, -1)] ?? "");
32
+ if (key === "'") return source.slice(match.index + match[0].length);
33
+ if (key.startsWith("<")) return match.groups![key.slice(1, -1)] ?? "";
36
34
  const index = Number(key);
37
35
  if (index > 0 && index < match.length) return match[index] ?? "";
38
36
  // $12 falls back to capture 1 plus literal 2 when capture 12 does not exist.
@@ -42,6 +40,9 @@ function expandReplacement(template: string, match: RegExpMatchArray, source: st
42
40
  });
43
41
  }
44
42
 
43
+ /** A rule's field in the tool's arguments, as argument issues name it. */
44
+ const ruleField = (index: number): string => `replacements[${index}]`;
45
+
45
46
  export function applyReplacements(
46
47
  source: string,
47
48
  rules: readonly Replacement[],
@@ -49,14 +50,15 @@ export function applyReplacements(
49
50
  const changes: { start: number; end: number; text: string; rule: number }[] = [];
50
51
  const view = createLfTextView(source);
51
52
  const fallbackEnding = detectLineEnding(source) === "crlf" ? "\r\n" : "\n";
53
+ const unmatched: string[] = [];
52
54
  for (const [index, rule] of rules.entries()) {
53
55
  const regex = buildRegex(rule.find, rule.literal, rule.flags);
54
56
  let count = 0;
55
57
  const replacement = normalizeLineEndings(rule.replace);
56
58
  for (const match of view.text.matchAll(regex)) {
57
59
  count++;
58
- const start = view.sourceOffset(match.index!);
59
- const end = view.sourceOffset(match.index! + match[0].length);
60
+ const start = view.sourceOffset(match.index);
61
+ const end = view.sourceOffset(match.index + match[0].length);
60
62
  changes.push({
61
63
  start,
62
64
  end,
@@ -68,18 +70,22 @@ export function applyReplacements(
68
70
  ),
69
71
  });
70
72
  }
71
- if (count === 0)
72
- throw new HashlineError("NO_MATCH", "The rule matches nothing in the file.", {
73
- facts: { rule: index },
74
- });
73
+ if (count === 0) unmatched.push(ruleField(index));
75
74
  }
75
+ if (unmatched.length)
76
+ throw new HashlineError("NO_MATCH", "Rules match nothing in the file.", {
77
+ facts: { unmatched },
78
+ });
76
79
  changes.sort((a, b) => a.start - b.start || a.end - b.end);
77
80
  const conflict = findSortedRangeConflict(changes.map((change) => [change.start, change.end]));
78
81
  if (conflict !== undefined) {
79
82
  const previous = changes[conflict - 1];
80
83
  const current = changes[conflict];
81
- throw new HashlineError("OVERLAPPING_MATCHES", "Matches of the rules overlap.", {
82
- facts: { rules: [previous.rule, current.rule], offset: current.start },
84
+ throw new HashlineError("OVERLAPPING_MATCHES", "Matches of two rules overlap.", {
85
+ facts: {
86
+ conflict: [previous.rule, current.rule].sort((a, b) => a - b).map(ruleField),
87
+ line: source.slice(0, current.start).split("\n").length,
88
+ },
83
89
  });
84
90
  }
85
91
  const parts: string[] = [];
@@ -38,6 +38,10 @@ for (const [pattern, flags, expected] of [
38
38
  ],
39
39
  ["é", "miu", [[["É", "é"]]]],
40
40
  ["[\\u0100-\\u0200]", "m", undefined],
41
+ ["foo.*bar", "m", [literal("foo")]],
42
+ ["(?:abcdef.*xy|zz.*ghijkl)", "m", [literal("abcdef"), literal("ghijkl")]],
43
+ ["foo|bar.*baz", "m", [literal("foo"), literal("bar")]],
44
+ ["(?=foo|bar).*baz", "m", [literal("baz")]],
41
45
  ] as const) {
42
46
  test(`${pattern.slice(0, 80)} /${flags} → conservative candidate literals`, () => {
43
47
  assert.deepEqual(
@@ -49,29 +53,30 @@ for (const [pattern, flags, expected] of [
49
53
 
50
54
  for (const boundary of ["\n", "\r\n", "\uFFFD", "\uD800", "\uDC00", "\0"]) {
51
55
  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));
56
+ const prefilter = extractPrefilter(query(`left${boundary}right`, "m", true));
57
+ assert.deepEqual(prefilter, { kind: "literals", literals: [literal("right")] });
58
+ assert.ok(hasCandidateBytes(Buffer.from(`left${boundary}right`), prefilter));
59
+ assert.ok(hasCandidateBytes(Buffer.from("left\nright"), prefilter));
55
60
  assert.equal(hasCandidateBytes(Buffer.from("left"), prefilter), false);
56
- assert.equal(hasCandidateBytes(Buffer.from("xy"), prefilter), false);
61
+ assert.ok(hasCandidateBytes(Buffer.from("right"), prefilter));
57
62
  assert.deepEqual(extractPrefilter(query(boundary, "m", true)), { kind: "all" });
58
63
  });
59
64
  }
60
65
 
61
66
  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],
67
+ [["foo", "bar"], false, true, ""],
68
+ [["foo", "Bar"], false, false, ""],
69
+ [["foo\\S*", "\\D", "\\W"], false, true, ""],
70
+ [["\\u0041"], false, false, ""],
71
+ [["\\x41"], false, false, ""],
72
+ [["\\u0061"], false, true, ""],
73
+ [["[A-Z]"], false, false, ""],
74
+ [["(?<UPPER>foo)"], false, true, ""],
75
+ [["ς", "σ"], false, true, ""],
76
+ [["σ", "Σ"], false, false, ""],
77
+ [["foo\\S*"], true, false, ""],
78
+ [["\\u0041"], true, true, ""],
79
+ [["foo", "BAR"], true, false, ""],
75
80
  [["\\u{41}"], false, false, "u"],
76
81
  [["\\u{41}"], false, false, "v"],
77
82
  [["\\u{61}"], false, true, "u"],
@@ -81,7 +86,7 @@ for (const [patterns, isLiteral, expected, flags] of [
81
86
  [["𐐨"], false, true, "u"],
82
87
  [["𐐨"], false, true, "v"],
83
88
  ] as const) {
84
- test(`${JSON.stringify(patterns)} literal=${isLiteral} flags=${flags ?? ""} → smart case follows decoded letters`, () => {
89
+ test(`${JSON.stringify(patterns)} literal=${isLiteral} flags=${flags} → smart case follows decoded letters`, () => {
85
90
  assert.equal(smartIgnoreCase(patterns, isLiteral, flags), expected);
86
91
  });
87
92
  }
@@ -180,14 +185,6 @@ test("oversized literal alternation → retains necessary prefixes without dropp
180
185
  assert.equal(hasCandidateBytes(Buffer.from("unrelated"), prefilter), false);
181
186
  });
182
187
 
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
188
  test("empty expression with a huge repeat → completes without iterating the repeat count", () => {
192
189
  assert.deepEqual(extractPrefilter(query("(?:){1000000000}")), { kind: "all" });
193
190
  });
@@ -202,7 +199,7 @@ test("deeply nested uppercase pattern → smart case stays sensitive and prefilt
202
199
  for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
203
200
  const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
204
201
  assert.equal(new RegExp(pattern).test("A"), true);
205
- assert.equal(smartIgnoreCase([pattern], false), false);
202
+ assert.equal(smartIgnoreCase([pattern], false, ""), false);
206
203
  assert.equal(hasCandidateBytes(Buffer.from("A"), extractPrefilter(query(pattern))), true);
207
204
  }
208
205
  });
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Static analysis of grep queries: smart case, and the necessary literals of grep's
3
3
  * candidate-file prefilter. Every JavaScript match of the query, on the LF view of a
4
- * file without NUL, satisfies every returned clause by containing one of its literals; that text
4
+ * file without NUL, contains one of the returned literals; that text
5
5
  * appears unchanged in the file's original bytes. Native RegExp still decides every
6
6
  * match; an unknown construct only widens the candidate set, down to every file.
7
7
  *
@@ -27,25 +27,20 @@ interface LiteralFilter {
27
27
  readonly kind: "literals";
28
28
  readonly literals: readonly Literal[];
29
29
  }
30
- export type Prefilter =
31
- | { readonly kind: "all" }
32
- | LiteralFilter
33
- | { readonly kind: "and"; readonly filters: readonly LiteralFilter[] };
30
+ export type Prefilter = { readonly kind: "all" } | LiteralFilter;
34
31
 
35
32
  const ALL: Prefilter = { kind: "all" };
36
33
  const MAX_SEQUENCES = 16;
37
34
  const MAX_SEQUENCE_LENGTH = 64;
38
35
  const MAX_CLASS_CHARS = 64;
39
36
  const MAX_LITERALS = 64;
40
- /** Dropping an AND clause widens safely; no OR alternative may be discarded. */
41
- const MAX_PREFILTER_CLAUSES = 8;
42
37
 
43
38
  /** Text of unknown length and content: a literal never spans it. */
44
39
  const GAP = null;
45
40
  type Unit = LiteralChar | typeof GAP;
46
41
  type Sequence = readonly Unit[];
47
42
 
48
- /** A node's bounded exact texts and necessary AND/OR conditions on original bytes. */
43
+ /** A node's bounded exact texts and necessary condition on original bytes. */
49
44
  interface Info {
50
45
  readonly exact?: readonly Sequence[];
51
46
  readonly filter: Prefilter;
@@ -105,61 +100,35 @@ function literalFilter(values: readonly Literal[]): Prefilter {
105
100
  return first === GAP ? ALL : { kind: "literals", literals: [[first]] };
106
101
  }
107
102
 
108
- function implies(left: LiteralFilter, right: LiteralFilter): boolean {
109
- return left.literals.every((long) =>
110
- right.literals.some((short) => {
111
- for (let offset = 0; offset <= long.length - short.length; offset++)
112
- if (
113
- short.every((chars, index) => long[offset + index].every((char) => chars.includes(char)))
114
- )
115
- return true;
116
- return false;
117
- }),
118
- );
119
- }
120
-
121
- function andFilters(filters: readonly Prefilter[]): Prefilter {
122
- const clauses = distinct(
123
- filters.flatMap((filter) =>
124
- filter.kind === "all" ? [] : filter.kind === "and" ? filter.filters : [filter],
125
- ),
126
- );
127
- const kept = clauses.filter(
128
- (clause, index) =>
129
- !clauses.some(
130
- (other, at) =>
131
- at !== index && implies(other, clause) && (!implies(clause, other) || at < index),
132
- ),
133
- );
134
- kept.sort(
135
- (a, b) =>
136
- Math.min(...b.literals.map((literal) => literal.length)) -
137
- Math.min(...a.literals.map((literal) => literal.length)) ||
138
- a.literals.length - b.literals.length,
139
- );
140
- const bounded = kept.slice(0, MAX_PREFILTER_CLAUSES);
141
- return bounded.length === 0
142
- ? ALL
143
- : bounded.length === 1
144
- ? bounded[0]
145
- : { kind: "and", filters: bounded };
103
+ /**
104
+ * Of conditions that all hold, the most selective: the longest shortest literal, then the
105
+ * fewest literals. One rg pass per condition costs more than it saves, and dropping a
106
+ * necessary condition only widens the candidates.
107
+ */
108
+ function strongestFilter(filters: readonly Prefilter[]): Prefilter {
109
+ const shortest = (filter: LiteralFilter) =>
110
+ Math.min(...filter.literals.map((literal) => literal.length));
111
+ let best: Prefilter = ALL;
112
+ for (const filter of filters) {
113
+ if (filter.kind === "all") continue;
114
+ if (
115
+ best.kind === "all" ||
116
+ shortest(filter) > shortest(best) ||
117
+ (shortest(filter) === shortest(best) && filter.literals.length < best.literals.length)
118
+ )
119
+ best = filter;
120
+ }
121
+ return best;
146
122
  }
147
123
 
124
+ /** Any of these conditions may hold, so the result keeps every alternative. */
148
125
  function orFilters(filters: readonly Prefilter[]): Prefilter {
149
- const known = filters.filter((filter) => filter.kind !== "all");
150
- if (!known.length || known.length < filters.length) return ALL;
151
- let result: Prefilter = known[0];
152
- for (const filter of known.slice(1)) {
153
- // Distribution can drop every bounded clause, leaving no condition.
154
- if (result.kind === "all") return ALL;
155
- const left = result.kind === "and" ? result.filters : [result];
156
- const right = filter.kind === "and" ? filter.filters : [filter];
157
- // CNF distribution creates AND clauses; keeping only bounded clauses is a widening.
158
- result = andFilters(
159
- left.flatMap((a) => right.map((b) => literalFilter([...a.literals, ...b.literals]))),
160
- );
126
+ const literals: Literal[] = [];
127
+ for (const filter of filters) {
128
+ if (filter.kind === "all") return ALL;
129
+ literals.push(...filter.literals);
161
130
  }
162
- return result;
131
+ return literalFilter(literals);
163
132
  }
164
133
 
165
134
  function sequenceFilter(sequences: readonly Sequence[]): Prefilter {
@@ -174,13 +143,13 @@ function sequenceFilter(sequences: readonly Sequence[]): Prefilter {
174
143
  run = [];
175
144
  }
176
145
  }
177
- return andFilters(filters);
146
+ return strongestFilter(filters);
178
147
  }),
179
148
  );
180
149
  }
181
150
 
182
151
  const filterOf = (info: Info): Prefilter =>
183
- info.exact ? andFilters([info.filter, sequenceFilter(info.exact)]) : info.filter;
152
+ info.exact ? strongestFilter([info.filter, sequenceFilter(info.exact)]) : info.filter;
184
153
 
185
154
  function cross(left: readonly Sequence[], right: readonly Sequence[]): Sequence[] | undefined {
186
155
  if (left.length * right.length > MAX_SEQUENCES) return undefined;
@@ -208,8 +177,8 @@ function concatenate(infos: readonly Info[]): Info {
208
177
  run = info.exact ?? [[]];
209
178
  }
210
179
  return whole
211
- ? { exact: run, filter: andFilters(filters) }
212
- : { filter: andFilters([...filters, sequenceFilter(run)]) };
180
+ ? { exact: run, filter: strongestFilter(filters) }
181
+ : { filter: strongestFilter([...filters, sequenceFilter(run)]) };
213
182
  }
214
183
 
215
184
  function alternate(infos: readonly Info[]): Info {
@@ -343,7 +312,7 @@ export function analyzeQueryPattern<T>(
343
312
  export function smartIgnoreCase(
344
313
  patterns: readonly string[],
345
314
  literal: boolean,
346
- flags = "",
315
+ flags: string,
347
316
  ): boolean {
348
317
  return !patterns.some((pattern) => {
349
318
  const uppercase = analyzeQueryPattern(pattern, literal, flags, (parsed) => {
@@ -360,7 +329,7 @@ export function smartIgnoreCase(
360
329
  });
361
330
  }
362
331
 
363
- /** Necessary file conditions in bounded conjunctive normal form; every OR retains all alternatives. */
332
+ /** One necessary file condition, its literals bounded; every OR retains all alternatives. */
364
333
  export function extractPrefilter(query: GrepQuery): Prefilter {
365
334
  const unicode = query.flags.includes("u") || query.flags.includes("v");
366
335
  const ctx: Context = {
@@ -143,8 +143,6 @@ export function acceptsNative(query: GrepQuery): boolean {
143
143
  /** Match literal bytes directly, without relying on the candidate regex formatter or expanding products. */
144
144
  export function hasCandidateBytes(bytes: Buffer, prefilter: Prefilter): boolean {
145
145
  if (prefilter.kind === "all") return true;
146
- if (prefilter.kind === "and")
147
- return prefilter.filters.every((filter) => hasCandidateBytes(bytes, filter));
148
146
  return prefilter.literals.some((literal) => {
149
147
  const positions = literal.map((chars) => chars.map((char) => Buffer.from(char)));
150
148
  for (let start = 0; start < bytes.length; start++) {
@@ -3,7 +3,7 @@ import { countLines, normalizeLineEndings } from "./lines.ts";
3
3
  import { buildRegex } from "./regex.ts";
4
4
  import type { SearchResult } from "./search-schema.ts";
5
5
 
6
- /** README's grep flags default links here; explicit flags replace this default. */
6
+ /** Explicit flags replace this default. */
7
7
  export const DEFAULT_GREP_FLAGS = "m";
8
8
 
9
9
  export interface GrepQuery {
@@ -1,18 +1,18 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { createUtf8Decoder, decodeEditableText, decodeUtf8, Utf8DecodingError } from "./text.ts";
3
+ import { createUtf8Decoder, decodeEditableText, Utf8DecodingError } from "./text.ts";
4
4
  import { HashlineError, TEXT_ERROR_MESSAGES } from "./errors.ts";
5
5
 
6
- test("decodeUtf8 rejects malformed input instead of replacing bytes", () => {
6
+ test("decodeEditableText rejects malformed input instead of replacing bytes", () => {
7
7
  assert.throws(
8
- () => decodeUtf8(Uint8Array.from([0xc3, 0x28])),
8
+ () => decodeEditableText(Uint8Array.from([0xc3, 0x28])),
9
9
  (error: unknown) =>
10
10
  error instanceof HashlineError && error.errorCode === "UNSUPPORTED_ENCODING",
11
11
  );
12
12
  });
13
13
 
14
- test("decodeUtf8 preserves a leading BOM", () => {
15
- assert.equal(decodeUtf8(Uint8Array.from([0xef, 0xbb, 0xbf, 0x61])), "\ufeffa");
14
+ test("decodeEditableText preserves a leading BOM", () => {
15
+ assert.equal(decodeEditableText(Uint8Array.from([0xef, 0xbb, 0xbf, 0x61])), "\ufeffa");
16
16
  });
17
17
 
18
18
  test("decodeEditableText rejects NUL bytes", () => {
package/src/core/text.ts CHANGED
@@ -47,19 +47,12 @@ export function createUtf8Decoder(mode: Utf8Decoding = "strict") {
47
47
 
48
48
  const decode = createUtf8Decoder();
49
49
 
50
- /** Decode UTF-8 without replacing malformed bytes; preserve a leading BOM for byte-stable rewrites. */
51
- export function decodeUtf8(bytes: Uint8Array): string {
52
- return decode(bytes);
53
- }
54
-
55
- /** Reject byte-oriented/binary content before entering a text mutation pipeline. */
50
+ /**
51
+ * Reject byte-oriented/binary content before entering a text mutation pipeline; malformed bytes
52
+ * are not replaced and a leading BOM stays for byte-stable rewrites.
53
+ */
56
54
  export function decodeEditableText(bytes: Uint8Array): string {
57
55
  if (bytes.includes(0))
58
56
  throw new HashlineError("UNSUPPORTED_TEXT", TEXT_ERROR_MESSAGES.UNSUPPORTED_TEXT);
59
- return decodeUtf8(bytes);
60
- }
61
-
62
- /** Escape regex metacharacters for a standalone literal pattern in JS or ripgrep. */
63
- export function escapeRegex(text: string): string {
64
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
57
+ return decode(bytes);
65
58
  }