@better-fs-tools/write 0.0.0-tegami-trusted-publish-setup → 0.2.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 (196) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +449 -6
  3. package/dist/authorize/ask-before-write.d.ts +11 -0
  4. package/dist/authorize/ask-before-write.js +49 -0
  5. package/dist/authorize/index.d.ts +3 -0
  6. package/dist/authorize/index.js +3 -0
  7. package/dist/authorize/protect-paths.d.ts +12 -0
  8. package/dist/authorize/protect-paths.js +74 -0
  9. package/dist/authorize/write-authorizers.d.ts +9 -0
  10. package/dist/authorize/write-authorizers.js +48 -0
  11. package/dist/bundle/create-fs-tools.d.ts +93 -0
  12. package/dist/bundle/create-fs-tools.js +130 -0
  13. package/dist/codecs/index.d.ts +1 -0
  14. package/dist/codecs/index.js +1 -0
  15. package/dist/codecs/utf8.d.ts +7 -0
  16. package/dist/codecs/utf8.js +61 -0
  17. package/dist/contract/codec.d.ts +26 -0
  18. package/dist/contract/codec.js +0 -0
  19. package/dist/contract/context.d.ts +14 -0
  20. package/dist/contract/context.js +0 -0
  21. package/dist/contract/deps.d.ts +63 -0
  22. package/dist/contract/deps.js +0 -0
  23. package/dist/contract/extensions.d.ts +103 -0
  24. package/dist/contract/extensions.js +0 -0
  25. package/dist/contract/format.d.ts +15 -0
  26. package/dist/contract/format.js +0 -0
  27. package/dist/contract/input.d.ts +35 -0
  28. package/dist/contract/input.js +0 -0
  29. package/dist/contract/limits.d.ts +26 -0
  30. package/dist/contract/limits.js +0 -0
  31. package/dist/contract/locks.d.ts +14 -0
  32. package/dist/contract/locks.js +0 -0
  33. package/dist/contract/matcher.d.ts +30 -0
  34. package/dist/contract/matcher.js +0 -0
  35. package/dist/contract/messages.d.ts +188 -0
  36. package/dist/contract/messages.js +0 -0
  37. package/dist/contract/patch.d.ts +50 -0
  38. package/dist/contract/patch.js +0 -0
  39. package/dist/contract/preconditions.d.ts +13 -0
  40. package/dist/contract/preconditions.js +5 -0
  41. package/dist/contract/result.d.ts +102 -0
  42. package/dist/contract/result.js +0 -0
  43. package/dist/core/abort.d.ts +4 -0
  44. package/dist/core/abort.js +23 -0
  45. package/dist/core/authorize.d.ts +9 -0
  46. package/dist/core/authorize.js +87 -0
  47. package/dist/core/bytes.d.ts +3 -0
  48. package/dist/core/bytes.js +14 -0
  49. package/dist/core/commit-patch.d.ts +20 -0
  50. package/dist/core/commit-patch.js +224 -0
  51. package/dist/core/commit.d.ts +8 -0
  52. package/dist/core/commit.js +77 -0
  53. package/dist/core/create-tools.d.ts +23 -0
  54. package/dist/core/create-tools.js +54 -0
  55. package/dist/core/deps.d.ts +11 -0
  56. package/dist/core/deps.js +210 -0
  57. package/dist/core/diff.d.ts +10 -0
  58. package/dist/core/diff.js +221 -0
  59. package/dist/core/encode.d.ts +3 -0
  60. package/dist/core/encode.js +26 -0
  61. package/dist/core/extension-error.d.ts +8 -0
  62. package/dist/core/extension-error.js +17 -0
  63. package/dist/core/format.d.ts +4 -0
  64. package/dist/core/format.js +22 -0
  65. package/dist/core/guards.d.ts +3 -0
  66. package/dist/core/guards.js +45 -0
  67. package/dist/core/hints.d.ts +14 -0
  68. package/dist/core/hints.js +75 -0
  69. package/dist/core/hooks.d.ts +15 -0
  70. package/dist/core/hooks.js +108 -0
  71. package/dist/core/input.d.ts +20 -0
  72. package/dist/core/input.js +91 -0
  73. package/dist/core/limits.d.ts +10 -0
  74. package/dist/core/limits.js +48 -0
  75. package/dist/core/line-index.d.ts +10 -0
  76. package/dist/core/line-index.js +38 -0
  77. package/dist/core/load.d.ts +14 -0
  78. package/dist/core/load.js +221 -0
  79. package/dist/core/lock.d.ts +2 -0
  80. package/dist/core/lock.js +56 -0
  81. package/dist/core/match.d.ts +15 -0
  82. package/dist/core/match.js +66 -0
  83. package/dist/core/messages.d.ts +8 -0
  84. package/dist/core/messages.js +140 -0
  85. package/dist/core/outcomes.d.ts +21 -0
  86. package/dist/core/outcomes.js +127 -0
  87. package/dist/core/parse-patch.d.ts +3 -0
  88. package/dist/core/parse-patch.js +64 -0
  89. package/dist/core/patch-hunks.d.ts +25 -0
  90. package/dist/core/patch-hunks.js +177 -0
  91. package/dist/core/patch-pipeline.d.ts +4 -0
  92. package/dist/core/patch-pipeline.js +284 -0
  93. package/dist/core/pipeline.d.ts +22 -0
  94. package/dist/core/pipeline.js +153 -0
  95. package/dist/core/plan-edit.d.ts +15 -0
  96. package/dist/core/plan-edit.js +215 -0
  97. package/dist/core/plan-patch.d.ts +29 -0
  98. package/dist/core/plan-patch.js +169 -0
  99. package/dist/core/plan-write.d.ts +6 -0
  100. package/dist/core/plan-write.js +27 -0
  101. package/dist/core/planned.d.ts +35 -0
  102. package/dist/core/planned.js +36 -0
  103. package/dist/core/precondition.d.ts +10 -0
  104. package/dist/core/precondition.js +65 -0
  105. package/dist/core/record.d.ts +3 -0
  106. package/dist/core/record.js +58 -0
  107. package/dist/core/resolve.d.ts +3 -0
  108. package/dist/core/resolve.js +65 -0
  109. package/dist/core/scope.d.ts +33 -0
  110. package/dist/core/scope.js +109 -0
  111. package/dist/core/snippet.d.ts +4 -0
  112. package/dist/core/snippet.js +36 -0
  113. package/dist/core/splice.d.ts +10 -0
  114. package/dist/core/splice.js +19 -0
  115. package/dist/core/target.d.ts +10 -0
  116. package/dist/core/target.js +46 -0
  117. package/dist/formatters/default.d.ts +22 -0
  118. package/dist/formatters/default.js +140 -0
  119. package/dist/formatters/index.d.ts +2 -0
  120. package/dist/formatters/index.js +1 -0
  121. package/dist/guards/generated-file.d.ts +10 -0
  122. package/dist/guards/generated-file.js +39 -0
  123. package/dist/guards/index.d.ts +19 -0
  124. package/dist/guards/index.js +33 -0
  125. package/dist/guards/non-text.d.ts +7 -0
  126. package/dist/guards/non-text.js +50 -0
  127. package/dist/guards/omission.d.ts +9 -0
  128. package/dist/guards/omission.js +48 -0
  129. package/dist/guards/read-prefix.d.ts +12 -0
  130. package/dist/guards/read-prefix.js +87 -0
  131. package/dist/guards/shared.d.ts +11 -0
  132. package/dist/guards/shared.js +46 -0
  133. package/dist/guards/syntax.d.ts +10 -0
  134. package/dist/guards/syntax.js +54 -0
  135. package/dist/guards/truncation-notice.d.ts +8 -0
  136. package/dist/guards/truncation-notice.js +32 -0
  137. package/dist/hooks/executable-shebang.d.ts +9 -0
  138. package/dist/hooks/executable-shebang.js +46 -0
  139. package/dist/hooks/index.d.ts +2 -0
  140. package/dist/hooks/index.js +2 -0
  141. package/dist/hooks/verify-write.d.ts +9 -0
  142. package/dist/hooks/verify-write.js +63 -0
  143. package/dist/index.d.ts +30 -0
  144. package/dist/index.js +15 -0
  145. package/dist/locks/index.d.ts +1 -0
  146. package/dist/locks/index.js +1 -0
  147. package/dist/locks/memory-locks.d.ts +9 -0
  148. package/dist/locks/memory-locks.js +94 -0
  149. package/dist/matchers/block-anchor.d.ts +9 -0
  150. package/dist/matchers/block-anchor.js +69 -0
  151. package/dist/matchers/escape.d.ts +6 -0
  152. package/dist/matchers/escape.js +32 -0
  153. package/dist/matchers/exact.d.ts +4 -0
  154. package/dist/matchers/exact.js +29 -0
  155. package/dist/matchers/fold.d.ts +11 -0
  156. package/dist/matchers/fold.js +144 -0
  157. package/dist/matchers/indentation.d.ts +3 -0
  158. package/dist/matchers/indentation.js +81 -0
  159. package/dist/matchers/index.d.ts +14 -0
  160. package/dist/matchers/index.js +20 -0
  161. package/dist/matchers/line-trimmed.d.ts +3 -0
  162. package/dist/matchers/line-trimmed.js +32 -0
  163. package/dist/matchers/lines.d.ts +24 -0
  164. package/dist/matchers/lines.js +74 -0
  165. package/dist/matchers/normalized.d.ts +7 -0
  166. package/dist/matchers/normalized.js +69 -0
  167. package/dist/patch/grammar.d.ts +5 -0
  168. package/dist/patch/grammar.js +24 -0
  169. package/dist/patch/index.d.ts +4 -0
  170. package/dist/patch/index.js +3 -0
  171. package/dist/patch/parse.d.ts +11 -0
  172. package/dist/patch/parse.js +209 -0
  173. package/dist/signature/contract.d.ts +8 -0
  174. package/dist/signature/contract.js +0 -0
  175. package/dist/signature/edit.d.ts +19 -0
  176. package/dist/signature/edit.js +158 -0
  177. package/dist/signature/index.d.ts +6 -0
  178. package/dist/signature/index.js +4 -0
  179. package/dist/signature/matching.d.ts +3 -0
  180. package/dist/signature/matching.js +25 -0
  181. package/dist/signature/messages.d.ts +4 -0
  182. package/dist/signature/messages.js +9 -0
  183. package/dist/signature/patch.d.ts +6 -0
  184. package/dist/signature/patch.js +55 -0
  185. package/dist/signature/schema.d.ts +19 -0
  186. package/dist/signature/schema.js +117 -0
  187. package/dist/signature/write.d.ts +9 -0
  188. package/dist/signature/write.js +52 -0
  189. package/dist/state/index.d.ts +2 -0
  190. package/dist/state/index.js +1 -0
  191. package/dist/state/invalidate.d.ts +29 -0
  192. package/dist/state/invalidate.js +37 -0
  193. package/docs/architecture.md +223 -0
  194. package/docs/hosts.md +96 -0
  195. package/docs/result-schema.md +261 -0
  196. package/package.json +53 -2
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Validates edit tool input. Throws TypeError on any key other than path and
3
+ * edits, a bad path, an edit list outside 1 to limits.maxEdits, an empty
4
+ * oldText, a non-string newText, or a non-boolean replaceAll.
5
+ */
6
+ export function parseEditInput(input, limits) {
7
+ const record = inputRecord(input, "edit", ["path", "edits"]);
8
+ const path = validatePath(record.path);
9
+ const { edits } = record;
10
+ if (!Array.isArray(edits) || edits.length === 0) {
11
+ throw new TypeError("edits must be a non-empty array");
12
+ }
13
+ if (edits.length > limits.maxEdits) {
14
+ throw new TypeError(`edits must hold at most ${limits.maxEdits} entries`);
15
+ }
16
+ return { tool: "edit", path, edits: edits.map(parsePair) };
17
+ }
18
+ /**
19
+ * Validates write tool input. Throws TypeError on any key other than path and
20
+ * content, a bad path, or a non-string content.
21
+ */
22
+ export function parseWriteInput(input, _limits) {
23
+ const record = inputRecord(input, "write", ["path", "content"]);
24
+ const path = validatePath(record.path);
25
+ if (typeof record.content !== "string")
26
+ throw new TypeError("content must be a string");
27
+ return { tool: "write", path, content: record.content };
28
+ }
29
+ /**
30
+ * Validates apply_patch tool input. Throws TypeError unless it holds only a
31
+ * non-empty patch of at most limits.maxPatchBytes UTF-8 bytes.
32
+ */
33
+ export function parseApplyPatchInput(input, limits) {
34
+ const record = inputRecord(input, "apply_patch", ["patch"]);
35
+ const { patch } = record;
36
+ if (typeof patch !== "string" || patch.trim() === "") {
37
+ throw new TypeError("patch must be a non-empty string");
38
+ }
39
+ if (utf8LengthComparedTo(patch, limits.maxPatchBytes) > limits.maxPatchBytes) {
40
+ throw new TypeError(`patch must be at most ${limits.maxPatchBytes} bytes of UTF-8`);
41
+ }
42
+ return { tool: "apply_patch", patch };
43
+ }
44
+ function utf8LengthComparedTo(text, max) {
45
+ // Each UTF-16 code unit encodes to between 1 and 3 UTF-8 bytes.
46
+ if (text.length > max)
47
+ return text.length;
48
+ if (text.length * 3 <= max)
49
+ return text.length;
50
+ return new TextEncoder().encode(text).byteLength;
51
+ }
52
+ function inputRecord(input, tool, keys) {
53
+ if (!isRecord(input))
54
+ throw new TypeError(`The ${tool} input must be an object`);
55
+ for (const key of Object.keys(input)) {
56
+ if (!keys.includes(key))
57
+ throw new TypeError(`Unknown ${tool} input key: ${key}`);
58
+ }
59
+ return input;
60
+ }
61
+ function parsePair(value, index) {
62
+ const at = `edits[${index}]`;
63
+ if (!isRecord(value))
64
+ throw new TypeError(`${at} must be an object`);
65
+ for (const key of Object.keys(value)) {
66
+ if (key !== "oldText" && key !== "newText" && key !== "replaceAll") {
67
+ throw new TypeError(`Unknown key in ${at}: ${key}`);
68
+ }
69
+ }
70
+ const { oldText, newText, replaceAll } = value;
71
+ if (typeof oldText !== "string" || oldText === "") {
72
+ throw new TypeError(`${at}.oldText must be a non-empty string`);
73
+ }
74
+ if (typeof newText !== "string")
75
+ throw new TypeError(`${at}.newText must be a string`);
76
+ if (replaceAll !== undefined && typeof replaceAll !== "boolean") {
77
+ throw new TypeError(`${at}.replaceAll must be a boolean`);
78
+ }
79
+ return { oldText, newText, replaceAll: replaceAll ?? false };
80
+ }
81
+ export function isPath(value) {
82
+ return typeof value === "string" && value.trim() !== "" && !value.includes("\0");
83
+ }
84
+ function validatePath(value) {
85
+ if (!isPath(value))
86
+ throw new TypeError("path must be a non-empty string without NUL");
87
+ return value;
88
+ }
89
+ export function isRecord(value) {
90
+ return value !== null && typeof value === "object" && !Array.isArray(value);
91
+ }
@@ -0,0 +1,10 @@
1
+ import type { WriteLimits } from "../contract/limits.ts";
2
+ /** The default write limits. They are not ceilings: a host may raise any of them. */
3
+ export declare const defaultWriteLimits: Readonly<WriteLimits>;
4
+ /**
5
+ * Merges limit overrides onto the defaults key by key. Throws TypeError on an
6
+ * unknown key, a value that is not a positive safe integer, or a `sampleBytes`
7
+ * you set above `maxFileBytes`. A default `sampleBytes` over a `maxFileBytes`
8
+ * you set is lowered to it.
9
+ */
10
+ export declare function resolveWriteLimits(overrides?: Partial<WriteLimits>): Readonly<WriteLimits>;
@@ -0,0 +1,48 @@
1
+ const MIB = 1_024 * 1_024;
2
+ /** The default write limits. They are not ceilings: a host may raise any of them. */
3
+ export const defaultWriteLimits = Object.freeze({
4
+ maxFileBytes: 8 * MIB,
5
+ maxWriteBytes: 8 * MIB,
6
+ maxPatchBytes: 4 * MIB,
7
+ maxPatchFiles: 100,
8
+ maxEdits: 100,
9
+ sampleBytes: 8_192,
10
+ snippetLines: 3,
11
+ maxSnippetLines: 40,
12
+ maxDiffLines: 2_000,
13
+ maxHintLines: 12,
14
+ maxListedMatches: 10,
15
+ maxPatchProblems: 20,
16
+ });
17
+ const LIMIT_KEYS = Object.keys(defaultWriteLimits);
18
+ /**
19
+ * Merges limit overrides onto the defaults key by key. Throws TypeError on an
20
+ * unknown key, a value that is not a positive safe integer, or a `sampleBytes`
21
+ * you set above `maxFileBytes`. A default `sampleBytes` over a `maxFileBytes`
22
+ * you set is lowered to it.
23
+ */
24
+ export function resolveWriteLimits(overrides = {}) {
25
+ if (overrides === null || typeof overrides !== "object" || Array.isArray(overrides)) {
26
+ throw new TypeError("limits must be an object");
27
+ }
28
+ const unknown = Object.keys(overrides).find((key) => !Object.hasOwn(defaultWriteLimits, key));
29
+ if (unknown !== undefined)
30
+ throw new TypeError(`Unknown write limit: ${unknown}`);
31
+ const resolved = { ...defaultWriteLimits };
32
+ for (const key of LIMIT_KEYS) {
33
+ const value = overrides[key];
34
+ if (value === undefined)
35
+ continue;
36
+ if (!Number.isSafeInteger(value) || value <= 0) {
37
+ throw new TypeError(`${key} must be a positive safe integer`);
38
+ }
39
+ resolved[key] = value;
40
+ }
41
+ if (resolved.sampleBytes > resolved.maxFileBytes) {
42
+ if (overrides.sampleBytes !== undefined) {
43
+ throw new TypeError("sampleBytes must not be more than maxFileBytes");
44
+ }
45
+ resolved.sampleBytes = resolved.maxFileBytes;
46
+ }
47
+ return Object.freeze(resolved);
48
+ }
@@ -0,0 +1,10 @@
1
+ /** One-based line numbers for offsets in a text. */
2
+ export declare class LineIndex {
3
+ readonly text: string;
4
+ private readonly breaks;
5
+ constructor(text: string);
6
+ get count(): number;
7
+ lineOf(offset: number): number;
8
+ span(start: number, end: number): [number, number];
9
+ line(number: number): string;
10
+ }
@@ -0,0 +1,38 @@
1
+ /** One-based line numbers for offsets in a text. */
2
+ export class LineIndex {
3
+ text;
4
+ breaks = [];
5
+ constructor(text) {
6
+ this.text = text;
7
+ for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) {
8
+ this.breaks.push(at);
9
+ }
10
+ }
11
+ get count() {
12
+ if (this.text === "")
13
+ return 0;
14
+ return this.breaks.length + (this.text.endsWith("\n") ? 0 : 1);
15
+ }
16
+ lineOf(offset) {
17
+ let low = 0;
18
+ let high = this.breaks.length;
19
+ while (low < high) {
20
+ const middle = (low + high) >>> 1;
21
+ if ((this.breaks[middle] ?? 0) < offset)
22
+ low = middle + 1;
23
+ else
24
+ high = middle;
25
+ }
26
+ return Math.max(1, Math.min(low + 1, this.count));
27
+ }
28
+ span(start, end) {
29
+ const first = this.lineOf(start);
30
+ return [first, end > start ? Math.max(first, this.lineOf(end - 1)) : first];
31
+ }
32
+ line(number) {
33
+ const start = number <= 1 ? 0 : (this.breaks[number - 2] ?? this.text.length) + 1;
34
+ const end = this.breaks[number - 1] ?? this.text.length;
35
+ const line = this.text.slice(start, end);
36
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
37
+ }
38
+ }
@@ -0,0 +1,14 @@
1
+ import type { ExistingFileStat, OpenFile, WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { Codec, TextStyle } from "../contract/codec.ts";
3
+ import type { MutationScope } from "./scope.ts";
4
+ export interface Loaded {
5
+ readonly bytes: Uint8Array;
6
+ readonly text: string;
7
+ readonly style: TextStyle;
8
+ readonly codec: Codec;
9
+ readonly version: string;
10
+ readonly contentId: string | null;
11
+ readonly mode: number | null;
12
+ }
13
+ export declare function loadFile<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, stat: ExistingFileStat, requested: string): Promise<Loaded>;
14
+ export declare function readCapped<THost>(scope: MutationScope<THost>, handle: OpenFile, max: number, requested: string, tooLarge: () => Error): Promise<Uint8Array>;
@@ -0,0 +1,221 @@
1
+ import { AbortStop } from "./abort.js";
2
+ import { hashBytes, sameBytes } from "./bytes.js";
3
+ import { extensionId } from "./extension-error.js";
4
+ import { isRecord } from "./input.js";
5
+ import { WriteStop, isBackendError, messageOf } from "./outcomes.js";
6
+ import { ioFailure } from "./target.js";
7
+ export async function loadFile(scope, fs, stat, requested) {
8
+ scope.enter("load");
9
+ scope.checkAbort();
10
+ const { limits, messages } = scope.deps;
11
+ const tooLarge = () => scope.stop("TOO_LARGE", messages.tooLarge({
12
+ path: requested,
13
+ what: "file",
14
+ limit: limits.maxFileBytes,
15
+ existing: true,
16
+ }), { limit: limits.maxFileBytes });
17
+ const stale = () => scope.stop("STALE", messages.stale({ tool: scope.tool, path: requested }));
18
+ if (stat.size > limits.maxFileBytes)
19
+ throw tooLarge();
20
+ const { signal } = scope;
21
+ const started = [];
22
+ let opened;
23
+ try {
24
+ opened = await scope.race(() => {
25
+ const pending = fs.open(stat.resolvedPath, signal === undefined ? {} : { signal });
26
+ started.push(Promise.resolve(pending));
27
+ return pending;
28
+ });
29
+ }
30
+ catch (error) {
31
+ if (error instanceof AbortStop) {
32
+ for (const pending of started)
33
+ void pending.then(closeHandleOpenedAfterAbort, () => { });
34
+ throw error;
35
+ }
36
+ throw ioFailure(scope, requested, messageOf(error));
37
+ }
38
+ if (isRecord(opened) && opened.ok === false && isBackendError(opened.error)) {
39
+ throw scope.backendFailure(requested, opened.error);
40
+ }
41
+ if (!isRecord(opened) || opened.ok !== true || !isRecord(opened.file)) {
42
+ throw ioFailure(scope, requested, "malformed open outcome");
43
+ }
44
+ const handle = opened.file;
45
+ try {
46
+ const { info } = handle;
47
+ if ((info.version ?? null) !== stat.version)
48
+ throw stale();
49
+ if (info.size !== null && info.size > limits.maxFileBytes)
50
+ throw tooLarge();
51
+ const bytes = await readCapped(scope, handle, limits.maxFileBytes, requested, tooLarge);
52
+ if (info.size !== null && bytes.byteLength !== info.size)
53
+ throw stale();
54
+ const sample = {
55
+ bytes: bytes.subarray(0, limits.sampleBytes),
56
+ complete: bytes.byteLength <= limits.sampleBytes,
57
+ path: info.displayPath,
58
+ mimeType: info.mimeType,
59
+ };
60
+ classify(scope, sample, requested);
61
+ const { codec, text, style } = decode(scope, sample, bytes, requested);
62
+ let verified;
63
+ try {
64
+ verified = await scope.race(() => handle.verify());
65
+ }
66
+ catch (error) {
67
+ if (error instanceof AbortStop)
68
+ throw error;
69
+ throw ioFailure(scope, requested, messageOf(error));
70
+ }
71
+ if (isRecord(verified) && verified.ok === false && isBackendError(verified.error)) {
72
+ throw scope.backendFailure(requested, verified.error);
73
+ }
74
+ if (!isRecord(verified) || verified.ok !== true) {
75
+ throw ioFailure(scope, requested, "malformed verify outcome");
76
+ }
77
+ if (verified.changed !== false)
78
+ throw stale();
79
+ const { digest } = scope.deps;
80
+ return {
81
+ bytes,
82
+ text,
83
+ style,
84
+ codec,
85
+ version: stat.version,
86
+ contentId: digest === null ? null : hashBytes(digest, bytes),
87
+ mode: stat.mode,
88
+ };
89
+ }
90
+ finally {
91
+ await handle.close().catch(() => { });
92
+ }
93
+ }
94
+ export async function readCapped(scope, handle, max, requested, tooLarge) {
95
+ const chunks = [];
96
+ let total = 0;
97
+ let iterator = null;
98
+ try {
99
+ iterator = handle.bytes()[Symbol.asyncIterator]();
100
+ const source = iterator;
101
+ for (;;) {
102
+ scope.checkAbort();
103
+ const item = await scope.race(() => source.next());
104
+ if (!isRecord(item) || typeof item.done !== "boolean") {
105
+ throw ioFailure(scope, requested, "the byte source returned an invalid result");
106
+ }
107
+ if (item.done)
108
+ break;
109
+ if (!(item.value instanceof Uint8Array)) {
110
+ throw ioFailure(scope, requested, "the byte source yielded a non-Uint8Array chunk");
111
+ }
112
+ total += item.value.byteLength;
113
+ if (total > max)
114
+ throw tooLarge();
115
+ chunks.push(item.value);
116
+ }
117
+ }
118
+ catch (error) {
119
+ if (error instanceof AbortStop || error instanceof WriteStop)
120
+ throw error;
121
+ throw ioFailure(scope, requested, messageOf(error));
122
+ }
123
+ finally {
124
+ try {
125
+ await iterator?.return?.(undefined);
126
+ }
127
+ catch {
128
+ // An adapter that fails to unwind cannot fail the call.
129
+ }
130
+ }
131
+ const bytes = new Uint8Array(total);
132
+ let offset = 0;
133
+ for (const chunk of chunks) {
134
+ bytes.set(chunk, offset);
135
+ offset += chunk.byteLength;
136
+ }
137
+ return bytes;
138
+ }
139
+ function classify(scope, sample, requested) {
140
+ const { classifiers, messages } = scope.deps;
141
+ for (const classifier of classifiers) {
142
+ let decision;
143
+ try {
144
+ decision = classifier.classify(sample);
145
+ }
146
+ catch (error) {
147
+ throw scope.extensionFailure("classifiers", extensionId(classifier, error));
148
+ }
149
+ if (decision === null)
150
+ continue;
151
+ if (!isRecord(decision))
152
+ throw scope.extensionFailure("classifiers", extensionId(classifier));
153
+ if (decision.kind === "text")
154
+ return;
155
+ if (decision.kind === "unsupported" && typeof decision.code === "string") {
156
+ const { code } = decision;
157
+ throw scope.stop("NOT_TEXT", messages.notText({ path: requested, code }), {
158
+ code,
159
+ classifier: classifier.id,
160
+ });
161
+ }
162
+ throw scope.extensionFailure("classifiers", extensionId(classifier));
163
+ }
164
+ throw scope.stop("UNSUPPORTED_BACKEND", messages.unsupportedBackend({ path: requested, detail: "its file type is not supported" }));
165
+ }
166
+ function decode(scope, sample, bytes, requested) {
167
+ const { codecs, messages } = scope.deps;
168
+ const notText = (code) => scope.stop("NOT_TEXT", messages.notText({ path: requested, code }), { code });
169
+ let codec;
170
+ for (const candidate of codecs) {
171
+ let accepted;
172
+ try {
173
+ accepted = candidate.accepts(sample);
174
+ }
175
+ catch (error) {
176
+ throw scope.extensionFailure("codecs", extensionId(candidate, error));
177
+ }
178
+ if (accepted === true) {
179
+ codec = candidate;
180
+ break;
181
+ }
182
+ }
183
+ if (codec === undefined)
184
+ throw notText("UNKNOWN_ENCODING");
185
+ const chosen = codec;
186
+ const failed = (error) => scope.extensionFailure("codecs", extensionId(chosen, error));
187
+ let decoded;
188
+ try {
189
+ decoded = codec.decode(bytes);
190
+ }
191
+ catch (error) {
192
+ throw failed(error);
193
+ }
194
+ if (!isRecord(decoded))
195
+ throw failed();
196
+ if (decoded.ok === false)
197
+ throw notText("UNKNOWN_ENCODING");
198
+ if (decoded.ok !== true || typeof decoded.text !== "string" || !isRecord(decoded.style)) {
199
+ throw failed();
200
+ }
201
+ const text = decoded.text;
202
+ const style = decoded.style;
203
+ let encoded;
204
+ try {
205
+ encoded = codec.encode(text, style);
206
+ }
207
+ catch (error) {
208
+ throw failed(error);
209
+ }
210
+ if (!(encoded instanceof Uint8Array))
211
+ throw failed();
212
+ if (!sameBytes(encoded, bytes))
213
+ throw notText("ROUND_TRIP");
214
+ return { codec, text, style };
215
+ }
216
+ function closeHandleOpenedAfterAbort(outcome) {
217
+ if (isRecord(outcome) && outcome.ok === true && isRecord(outcome.file)) {
218
+ const file = outcome.file;
219
+ void file.close().catch(() => { });
220
+ }
221
+ }
@@ -0,0 +1,2 @@
1
+ import type { MutationScope } from "./scope.ts";
2
+ export declare function acquireLocks<THost>(scope: MutationScope<THost>, keys: readonly string[], display: readonly string[]): Promise<() => void>;
@@ -0,0 +1,56 @@
1
+ import { AbortStop } from "./abort.js";
2
+ import { extensionId } from "./extension-error.js";
3
+ import { isRecord } from "./input.js";
4
+ export async function acquireLocks(scope, keys, display) {
5
+ scope.enter("lock");
6
+ scope.checkAbort();
7
+ const { locks } = scope.deps;
8
+ const sorted = [...new Set(keys)].sort();
9
+ const { signal } = scope;
10
+ const started = [];
11
+ let outcome;
12
+ try {
13
+ outcome = await scope.race(() => {
14
+ const pending = locks.acquire(sorted, signal === undefined ? {} : { signal });
15
+ started.push(Promise.resolve(pending));
16
+ return pending;
17
+ });
18
+ }
19
+ catch (error) {
20
+ if (error instanceof AbortStop) {
21
+ for (const pending of started)
22
+ void pending.then(releaseLockGrantedAfterAbort, () => { });
23
+ throw error;
24
+ }
25
+ throw scope.extensionFailure("locks", extensionId(locks, error));
26
+ }
27
+ if (!isRecord(outcome))
28
+ throw scope.extensionFailure("locks", extensionId(locks));
29
+ if (outcome.ok === true && typeof outcome.release === "function") {
30
+ const release = outcome.release;
31
+ return () => {
32
+ try {
33
+ release.call(outcome);
34
+ }
35
+ catch {
36
+ // A lock manager that fails to release cannot fail the call.
37
+ }
38
+ };
39
+ }
40
+ if (outcome.ok === false && outcome.reason === "aborted")
41
+ throw new AbortStop();
42
+ if (outcome.ok === false && outcome.reason === "timeout") {
43
+ throw scope.stop("LOCK_TIMEOUT", scope.deps.messages.lockTimeout({ paths: display }));
44
+ }
45
+ throw scope.extensionFailure("locks", extensionId(locks));
46
+ }
47
+ function releaseLockGrantedAfterAbort(outcome) {
48
+ if (isRecord(outcome) && outcome.ok === true && typeof outcome.release === "function") {
49
+ try {
50
+ outcome.release.call(outcome);
51
+ }
52
+ catch {
53
+ // Nothing waits for this release.
54
+ }
55
+ }
56
+ }
@@ -0,0 +1,15 @@
1
+ import type { Matcher, MatchContext, MatchRange } from "../contract/matcher.ts";
2
+ import type { MutationScope } from "./scope.ts";
3
+ export declare const REPLACE_ALL_CAP = 100000;
4
+ export declare function runChain<THost>(scope: MutationScope<THost>, matchers: readonly Matcher[], haystack: string, needle: string, ctx: MatchContext): {
5
+ readonly matcher: Matcher;
6
+ readonly ranges: readonly MatchRange[];
7
+ } | null;
8
+ export declare function findWith<THost>(scope: MutationScope<THost>, matcher: Matcher, haystack: string, needle: string, ctx: MatchContext): readonly MatchRange[];
9
+ export declare function adaptFor<THost>(scope: MutationScope<THost>, matcher: Matcher, newText: string, hit: {
10
+ readonly haystack: string;
11
+ readonly needle: string;
12
+ readonly range: MatchRange;
13
+ }): string;
14
+ export declare function tooWide(range: MatchRange, needle: string): boolean;
15
+ export declare function escapeDrift(newText: string, region: string): boolean;
@@ -0,0 +1,66 @@
1
+ import { extensionId } from "./extension-error.js";
2
+ import { isRecord } from "./input.js";
3
+ export const REPLACE_ALL_CAP = 100_000;
4
+ const DRIFT_ESCAPE_SEQUENCES = ["\\n", "\\t", '\\"', "\\'", "\\\\"];
5
+ export function runChain(scope, matchers, haystack, needle, ctx) {
6
+ for (const matcher of matchers) {
7
+ scope.checkAbort();
8
+ const ranges = findWith(scope, matcher, haystack, needle, ctx);
9
+ if (ranges.length > 0)
10
+ return { matcher, ranges };
11
+ }
12
+ return null;
13
+ }
14
+ export function findWith(scope, matcher, haystack, needle, ctx) {
15
+ let result;
16
+ try {
17
+ result = matcher.find(haystack, needle, Object.freeze({ ...ctx }));
18
+ }
19
+ catch (error) {
20
+ throw scope.extensionFailure("matchers", extensionId(matcher, error));
21
+ }
22
+ if (!validRanges(result, haystack.length, ctx.from)) {
23
+ throw scope.extensionFailure("matchers", extensionId(matcher));
24
+ }
25
+ return result.slice(0, ctx.maxMatches);
26
+ }
27
+ function validRanges(value, length, from) {
28
+ if (!Array.isArray(value))
29
+ return false;
30
+ let previous = from;
31
+ for (const range of value) {
32
+ if (!isRecord(range))
33
+ return false;
34
+ const { start, end, refused } = range;
35
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end))
36
+ return false;
37
+ const first = start;
38
+ const last = end;
39
+ if (first < previous || last <= first || last > length)
40
+ return false;
41
+ if (refused !== undefined && refused !== "boundary")
42
+ return false;
43
+ previous = last;
44
+ }
45
+ return true;
46
+ }
47
+ export function adaptFor(scope, matcher, newText, hit) {
48
+ if (matcher.adapt === undefined)
49
+ return newText;
50
+ let adapted;
51
+ try {
52
+ adapted = matcher.adapt(newText, hit);
53
+ }
54
+ catch (error) {
55
+ throw scope.extensionFailure("matchers", extensionId(matcher, error));
56
+ }
57
+ if (typeof adapted !== "string")
58
+ throw scope.extensionFailure("matchers", extensionId(matcher));
59
+ return adapted;
60
+ }
61
+ export function tooWide(range, needle) {
62
+ return range.end - range.start > 2 * needle.length + 64;
63
+ }
64
+ export function escapeDrift(newText, region) {
65
+ return DRIFT_ESCAPE_SEQUENCES.some((sequence) => newText.includes(sequence) && !region.includes(sequence));
66
+ }
@@ -0,0 +1,8 @@
1
+ import type { WriteMessageCatalog } from "../contract/messages.ts";
2
+ export declare const defaultWriteMessages: Readonly<WriteMessageCatalog>;
3
+ /**
4
+ * Merges message overrides onto the defaults key by key. Throws TypeError on
5
+ * an unknown key or a non-function value. A `param` override applies to every
6
+ * default message.
7
+ */
8
+ export declare function resolveWriteMessages(overrides?: Partial<WriteMessageCatalog>): Readonly<WriteMessageCatalog>;