@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,140 @@
1
+ function catalogUsingParam(param) {
2
+ return {
3
+ param,
4
+ pathRepaired: ({ from, to }) => `The requested filename ${JSON.stringify(from)} was repaired to the unique Unicode-equivalent path ${JSON.stringify(to)}.`,
5
+ denied: ({ path, detail }) => `${path} was refused by policy${detail === null ? "" : ` (${detail})`}.`,
6
+ invalidInput: ({ tool, detail }) => `The ${tool} input was rejected: ${detail}`,
7
+ notFound: ({ tool, path }) => {
8
+ if (tool === "edit")
9
+ return `${path} does not exist. Use the write tool to create it.`;
10
+ if (tool === "apply_patch")
11
+ return `${path} does not exist. Use *** Add File to create it.`;
12
+ return `${path} was not found. Check the path and its parent directories.`;
13
+ },
14
+ notAFile: ({ path, kind }) => `${path} is a ${kindLabel(kind)}. Only regular files can be changed.`,
15
+ dangerousPath: ({ path, detail }) => `${path} is refused by policy${detail === null ? "" : ` (${detail})`}. Choose another path.`,
16
+ outsideAllowedRoots: ({ path }) => `${path} is outside every configured allowed root. Choose a path inside the workspace.`,
17
+ permissionDenied: ({ path }) => `Permission was denied for ${path}.`,
18
+ guardRefused: ({ guard, path }) => `The ${guard} check refused the change to ${path}.`,
19
+ readOnly: ({ path }) => `${path} is on a read-only filesystem, so it cannot be changed.`,
20
+ noSpace: ({ path }) => `There is no space left to write ${path}.`,
21
+ unsupportedBackend: ({ path, detail }) => `The backend cannot change ${path}${detail === null ? "" : ` (${detail})`}; this is a configuration problem rather than a property of the file.`,
22
+ ioError: ({ path }) => `The backend failed while changing ${path ?? "the requested path"}. Retry, or read the file to check its state.`,
23
+ aborted: ({ phase }) => `The call was aborted during the ${phase} phase. No file was changed.`,
24
+ extensionFailed: ({ path, extension, phase }) => `The ${extension} extension failed during the ${phase} phase${path === null ? "" : ` while changing ${path}`}; this is a host problem rather than a property of the file.`,
25
+ lockTimeout: ({ paths }) => `Another change to ${paths.join(", ")} is still running. Retry when it has finished.`,
26
+ notRead: ({ path, wholeFile }) => wholeFile
27
+ ? `Read all of ${path} before replacing it. A partial read is not enough for write.`
28
+ : `Read ${path} with the read tool before changing it.`,
29
+ stale: ({ path }) => `${path} changed since it was last read. Read it again, then retry.`,
30
+ staleRematched: ({ path }) => `${path} changed since it was last read, but every old text still matched exactly once, so the edit was applied.`,
31
+ tooLarge: ({ path, what, limit, existing }) => {
32
+ if (what === "patch") {
33
+ return `The patch is over the limit of ${limit}. Split it into smaller patches.`;
34
+ }
35
+ if (what === "file") {
36
+ return `${path ?? "The file"} is larger than the ${limit}-byte limit, so it cannot be changed with this tool.`;
37
+ }
38
+ return existing
39
+ ? `The new content for ${path} is larger than the ${limit}-byte write limit. Change the file in smaller steps with the edit tool.`
40
+ : `The new content for ${path} is larger than the ${limit}-byte write limit. Write a smaller file.`;
41
+ },
42
+ notText: ({ path, code }) => {
43
+ if (code === "ROUND_TRIP") {
44
+ return `${path} does not decode and encode back to the same bytes, so it cannot be changed safely as text.`;
45
+ }
46
+ if (code === "UNKNOWN_ENCODING") {
47
+ return `${path} is not in an encoding this tool can decode, so it cannot be changed as text.`;
48
+ }
49
+ return `${path} is not a text file (${code}), so it cannot be changed with this tool.`;
50
+ },
51
+ exists: ({ tool, path }) => tool === "apply_patch"
52
+ ? `${path} already exists. Use *** Update File, or the write tool to replace it.`
53
+ : `${path} was created while this call ran. Read it, then retry.`,
54
+ noMatch: ({ path, index, closest, trailingNewline }) => {
55
+ const lines = [`Edit ${index + 1}: the ${param("oldText")} was not found in ${path}.`];
56
+ if (trailingNewline !== null)
57
+ lines.push("It differs only by a trailing newline.");
58
+ if (closest !== null)
59
+ lines.push("The closest region is:", closest);
60
+ return lines.join("\n");
61
+ },
62
+ ambiguousMatch: ({ path, index, lines, total }) => `Edit ${index + 1}: the ${param("oldText")} matches ${total} places in ${path} (lines ${lines.join(", ")}${total > lines.length ? ", …" : ""}). Add surrounding lines to make it unique${param("replaceAll") === "" ? "" : `, or set ${param("replaceAll")}`}.`,
63
+ matchRefused: ({ path, index, matcher, reason }) => {
64
+ const found = `Edit ${index + 1}: the ${matcher} matcher found the ${param("oldText")} in ${path}, but the match was refused (${refusalLabel(reason)}).`;
65
+ if (reason === "too-many") {
66
+ return `${found} Change fewer places in each edit, or replace the file with the write tool.`;
67
+ }
68
+ return `${found} Copy the ${param("oldText")} exactly from the file.`;
69
+ },
70
+ overlap: ({ path, first, second }) => `Edits ${first + 1} and ${second + 1} change overlapping text in ${path}. Merge them into one edit.`,
71
+ noChange: ({ path }) => `The edits leave ${path} as it is. Check the ${param("newText")} values, or do not send the edit.`,
72
+ alreadyApplied: ({ path, index }) => `Edit ${index + 1} is already applied: the ${param("newText")} is in ${path} and the ${param("oldText")} is not. Do not send this edit again.`,
73
+ fuzzyMatch: ({ path, index, matcher, lines }) => `Edit ${index + 1} matched ${path} at lines ${lines[0]}-${lines[1]} only with the ${matcher} matcher, not exactly. Check the result.`,
74
+ repeatedMiss: ({ path, misses }) => `This is miss ${misses} in a row on ${path}. Read the file again, include more surrounding lines, or replace the file with the write tool.`,
75
+ patchParse: ({ line, detail }) => `The patch could not be parsed at line ${line}: ${detail}`,
76
+ patchVerifyHeader: () => "Patch validation failed (no files were modified):",
77
+ patchDuplicateTarget: ({ path }) => `${path}: multiple operations target this file.`,
78
+ patchNotFound: ({ path, operation }) => operation === "update"
79
+ ? `${path} does not exist. Use *** Add File to create it.`
80
+ : `${path} does not exist, so it cannot be deleted.`,
81
+ patchMoveExists: ({ path, from }) => `${path} already exists, so ${from} cannot move there. Choose another path, or delete ${path} first.`,
82
+ patchContextNotFound: ({ path, hunk, context }) => `${path}: hunk ${hunk}: failed to find the context line ${JSON.stringify(context)}.`,
83
+ patchLinesNotFound: ({ path, hunk, lines }) => [
84
+ `${path}: hunk ${hunk}: failed to find the expected lines:`,
85
+ ...lines.map((line) => ` ${line}`),
86
+ ].join("\n"),
87
+ patchFuzzyMatch: ({ path, hunk, matcher, lines }) => `Hunk ${hunk} matched ${path} at lines ${lines[0]}-${lines[1]} only with the ${matcher} matcher, not exactly. Check the result.`,
88
+ patchCommitFailed: ({ path, code, rolledBack, files }) => rolledBack
89
+ ? `Patch commit failed at ${path} (${code}). The patch was rolled back. No files are changed.`
90
+ : [
91
+ `Patch commit failed at ${path} (${code}). Rollback failed, so these files are in a mixed state:`,
92
+ ...files.map((file) => `${file.state} ${file.path}`),
93
+ ].join("\n"),
94
+ userModified: ({ path }) => `The user changed the content before it was written to ${path}. The file holds their version. Read it before changing it again.`,
95
+ hookRewrote: ({ hook, path }) => `The ${hook} hook rewrote ${path} after the write. Read it again before relying on its text.`,
96
+ };
97
+ }
98
+ function kindLabel(kind) {
99
+ if (kind === "fifo")
100
+ return "FIFO";
101
+ if (kind === "other")
102
+ return "non-regular file";
103
+ return kind;
104
+ }
105
+ function refusalLabel(reason) {
106
+ if (reason === "span")
107
+ return "the matched region is much longer than the text sent";
108
+ if (reason === "boundary")
109
+ return "the match starts or ends inside normalized text";
110
+ if (reason === "escape")
111
+ return "the new text holds escape sequences the file does not";
112
+ if (reason === "too-many")
113
+ return "it matches more places than one edit may replace";
114
+ return "a loose match cannot replace every occurrence";
115
+ }
116
+ const canonical = (name) => name;
117
+ export const defaultWriteMessages = Object.freeze(catalogUsingParam(canonical));
118
+ /**
119
+ * Merges message overrides onto the defaults key by key. Throws TypeError on
120
+ * an unknown key or a non-function value. A `param` override applies to every
121
+ * default message.
122
+ */
123
+ export function resolveWriteMessages(overrides = {}) {
124
+ if (overrides === null || typeof overrides !== "object" || Array.isArray(overrides)) {
125
+ throw new TypeError("messages must be an object");
126
+ }
127
+ for (const [key, value] of Object.entries(overrides)) {
128
+ if (!Object.hasOwn(defaultWriteMessages, key))
129
+ throw new TypeError(`Unknown message: ${key}`);
130
+ if (value !== undefined && typeof value !== "function") {
131
+ throw new TypeError(`messages.${key} must be a function`);
132
+ }
133
+ }
134
+ const resolved = { ...catalogUsingParam(overrides.param ?? canonical) };
135
+ for (const [key, value] of Object.entries(overrides)) {
136
+ if (value !== undefined)
137
+ resolved[key] = value;
138
+ }
139
+ return Object.freeze(resolved);
140
+ }
@@ -0,0 +1,21 @@
1
+ import type { FileSystemError, MutationError } from "@better-fs-tools/fs";
2
+ import type { JsonObject, Note } from "@better-fs-tools/read";
3
+ import type { WriteToolName } from "../contract/context.ts";
4
+ import type { WriteMessageCatalog } from "../contract/messages.ts";
5
+ import type { MutationFailure, WriteErrorCode, WritePhase } from "../contract/result.ts";
6
+ type Messages = Readonly<WriteMessageCatalog>;
7
+ export declare class WriteStop extends Error {
8
+ readonly report: MutationFailure;
9
+ constructor(report: MutationFailure);
10
+ }
11
+ export declare function noteCode(code: WriteErrorCode): string;
12
+ export declare function errorNote(code: WriteErrorCode, message: string, data?: JsonObject): Note;
13
+ export declare function hostErrorNote(code: WriteErrorCode, note: Note, data?: JsonObject): Note;
14
+ export declare function failure(tool: WriteToolName, phase: WritePhase, note: Note): MutationFailure;
15
+ export declare function codeForReason(reason: MutationError["reason"]): WriteErrorCode;
16
+ export declare function backendErrorNote(messages: Messages, tool: WriteToolName, path: string, error: FileSystemError | MutationError, phase: WritePhase): Note;
17
+ export declare function isBackendError(value: unknown): value is MutationError;
18
+ export declare function isNote(value: unknown): value is Note;
19
+ export declare function isNoteList(value: unknown): value is readonly Note[];
20
+ export declare function messageOf(error: unknown): string;
21
+ export {};
@@ -0,0 +1,127 @@
1
+ import { isRecord } from "./input.js";
2
+ export class WriteStop extends Error {
3
+ report;
4
+ constructor(report) {
5
+ super(`write stopped with ${report.error.code}`);
6
+ this.report = report;
7
+ }
8
+ }
9
+ export function noteCode(code) {
10
+ return code.toLowerCase().replaceAll("_", "-");
11
+ }
12
+ export function errorNote(code, message, data) {
13
+ return {
14
+ code: noteCode(code),
15
+ severity: "warning",
16
+ message,
17
+ ...(data === undefined || Object.keys(data).length === 0 ? {} : { data }),
18
+ };
19
+ }
20
+ export function hostErrorNote(code, note, data = {}) {
21
+ const merged = { ...note.data, ...data };
22
+ return errorNote(code, note.message, note.code === noteCode(code) ? merged : { ...merged, source: note.code });
23
+ }
24
+ export function failure(tool, phase, note) {
25
+ const code = codeOfNote(note);
26
+ return {
27
+ tool,
28
+ status: "error",
29
+ error: {
30
+ code,
31
+ phase,
32
+ message: note.message,
33
+ ...(note.data === undefined ? {} : { data: note.data }),
34
+ },
35
+ changes: [],
36
+ unchanged: [],
37
+ notes: [note],
38
+ commit: null,
39
+ };
40
+ }
41
+ function codeOfNote(note) {
42
+ return note.code.toUpperCase().replaceAll("-", "_");
43
+ }
44
+ const CODE_BY_REASON = {
45
+ "not-found": "NOT_FOUND",
46
+ "not-a-file": "NOT_A_FILE",
47
+ "dangerous-path": "DANGEROUS_PATH",
48
+ "outside-allowed-roots": "OUTSIDE_ALLOWED_ROOTS",
49
+ "permission-denied": "PERMISSION_DENIED",
50
+ denied: "DENIED",
51
+ unsupported: "UNSUPPORTED_BACKEND",
52
+ aborted: "ABORTED",
53
+ io: "IO_ERROR",
54
+ changed: "STALE",
55
+ exists: "EXISTS",
56
+ "read-only": "READ_ONLY",
57
+ "no-space": "NO_SPACE",
58
+ "too-large": "TOO_LARGE",
59
+ };
60
+ export function codeForReason(reason) {
61
+ return CODE_BY_REASON[reason];
62
+ }
63
+ export function backendErrorNote(messages, tool, path, error, phase) {
64
+ const code = codeForReason(error.reason);
65
+ if (code === "ABORTED")
66
+ return errorNote(code, messages.aborted({ phase }), { phase });
67
+ return errorNote(code, messageForError(messages, tool, path, error, phase), errorData(error));
68
+ }
69
+ function errorData(error) {
70
+ return {
71
+ ...(error.reason === "not-a-file" ? { kind: error.kind } : {}),
72
+ ...(error.reason === "too-large" ? { limit: error.limit, size: error.size } : {}),
73
+ ...(error.detail === undefined ? {} : { detail: error.detail }),
74
+ ...(error.cause === undefined ? {} : { cause: { ...error.cause } }),
75
+ };
76
+ }
77
+ function messageForError(messages, tool, path, error, phase) {
78
+ const detail = error.detail ?? null;
79
+ switch (error.reason) {
80
+ case "not-found":
81
+ return messages.notFound({ tool, path });
82
+ case "not-a-file":
83
+ return messages.notAFile({ path, kind: error.kind });
84
+ case "dangerous-path":
85
+ return messages.dangerousPath({ path, detail });
86
+ case "outside-allowed-roots":
87
+ return messages.outsideAllowedRoots({ path });
88
+ case "permission-denied":
89
+ return messages.permissionDenied({ path });
90
+ case "denied":
91
+ return messages.denied({ path, detail });
92
+ case "unsupported":
93
+ return messages.unsupportedBackend({ path, detail });
94
+ case "changed":
95
+ return messages.stale({ tool, path });
96
+ case "exists":
97
+ return messages.exists({ tool, path });
98
+ case "read-only":
99
+ return messages.readOnly({ path });
100
+ case "no-space":
101
+ return messages.noSpace({ path });
102
+ case "too-large":
103
+ return messages.tooLarge({
104
+ path,
105
+ what: phase === "commit" ? "content" : "file",
106
+ limit: error.limit,
107
+ existing: false,
108
+ });
109
+ default:
110
+ return messages.ioError({ path });
111
+ }
112
+ }
113
+ export function isBackendError(value) {
114
+ return isRecord(value) && typeof value.reason === "string" && value.reason in CODE_BY_REASON;
115
+ }
116
+ export function isNote(value) {
117
+ return (isRecord(value) &&
118
+ typeof value.code === "string" &&
119
+ typeof value.message === "string" &&
120
+ (value.severity === "info" || value.severity === "warning"));
121
+ }
122
+ export function isNoteList(value) {
123
+ return Array.isArray(value) && value.every(isNote);
124
+ }
125
+ export function messageOf(error) {
126
+ return error instanceof Error ? error.message : String(error);
127
+ }
@@ -0,0 +1,3 @@
1
+ import type { PatchOperation, PatchParser } from "../contract/patch.ts";
2
+ import type { MutationScope } from "./scope.ts";
3
+ export declare function parsePatchText<THost>(scope: MutationScope<THost>, parser: PatchParser, text: string): readonly PatchOperation[];
@@ -0,0 +1,64 @@
1
+ import { extensionId } from "./extension-error.js";
2
+ import { isPath, isRecord } from "./input.js";
3
+ export function parsePatchText(scope, parser, text) {
4
+ scope.enter("input");
5
+ const { messages, limits } = scope.deps;
6
+ let outcome;
7
+ try {
8
+ outcome = parser.parse(text);
9
+ }
10
+ catch (error) {
11
+ throw scope.extensionFailure("patchParser", extensionId(parser, error));
12
+ }
13
+ const malformed = () => scope.extensionFailure("patchParser", extensionId(parser));
14
+ if (!isRecord(outcome))
15
+ throw malformed();
16
+ if (outcome.ok === false) {
17
+ const { error } = outcome;
18
+ if (!isRecord(error) || !isLine(error.line) || typeof error.detail !== "string") {
19
+ throw malformed();
20
+ }
21
+ const { line, detail } = error;
22
+ throw scope.stop("PATCH_PARSE", messages.patchParse({ line, detail }), { line, detail });
23
+ }
24
+ if (outcome.ok !== true || !isRecord(outcome.plan))
25
+ throw malformed();
26
+ const { operations } = outcome.plan;
27
+ if (!Array.isArray(operations) || operations.length === 0 || !operations.every(isOperation)) {
28
+ throw malformed();
29
+ }
30
+ if (operations.length > limits.maxPatchFiles) {
31
+ const limit = limits.maxPatchFiles;
32
+ throw scope.stop("TOO_LARGE", messages.tooLarge({ path: null, what: "patch", limit, existing: false }), { limit, operations: operations.length });
33
+ }
34
+ return operations;
35
+ }
36
+ function isOperation(value) {
37
+ if (!isRecord(value) || !isPath(value.path) || !isLine(value.line))
38
+ return false;
39
+ if (value.kind === "add")
40
+ return typeof value.content === "string";
41
+ if (value.kind === "delete")
42
+ return true;
43
+ if (value.kind !== "update")
44
+ return false;
45
+ const { moveTo, hunks } = value;
46
+ if (moveTo !== null && !isPath(moveTo))
47
+ return false;
48
+ return Array.isArray(hunks) && hunks.every(isHunk);
49
+ }
50
+ function isHunk(value) {
51
+ if (!isRecord(value) || !isLine(value.line) || typeof value.endOfFile !== "boolean")
52
+ return false;
53
+ if (value.context !== null && typeof value.context !== "string")
54
+ return false;
55
+ const { lines } = value;
56
+ return (Array.isArray(lines) &&
57
+ lines.every((line) => isRecord(line) &&
58
+ (line.kind === " " || line.kind === "-" || line.kind === "+") &&
59
+ typeof line.text === "string" &&
60
+ !line.text.includes("\n")));
61
+ }
62
+ function isLine(value) {
63
+ return Number.isSafeInteger(value) && value >= 1;
64
+ }
@@ -0,0 +1,25 @@
1
+ import type { ChangeFragment } from "../contract/extensions.ts";
2
+ import type { Matcher } from "../contract/matcher.ts";
3
+ import type { PatchHunk } from "../contract/patch.ts";
4
+ import type { MatchInfo } from "../contract/result.ts";
5
+ import type { MutationScope } from "./scope.ts";
6
+ export type HunkProblem = {
7
+ readonly reason: "context-not-found";
8
+ readonly hunk: number;
9
+ readonly context: string;
10
+ } | {
11
+ readonly reason: "lines-not-found";
12
+ readonly hunk: number;
13
+ readonly lines: readonly string[];
14
+ };
15
+ export type HunksOutcome = {
16
+ readonly ok: true;
17
+ readonly text: string;
18
+ readonly matches: readonly MatchInfo[];
19
+ readonly changed: readonly (readonly [number, number])[];
20
+ readonly fragments: readonly ChangeFragment[];
21
+ } | {
22
+ readonly ok: false;
23
+ readonly problem: HunkProblem;
24
+ };
25
+ export declare function applyHunks<THost>(scope: MutationScope<THost>, matchers: readonly Matcher[], text: string, hunks: readonly PatchHunk[]): HunksOutcome;
@@ -0,0 +1,177 @@
1
+ import { findWith } from "./match.js";
2
+ export function applyHunks(scope, matchers, text, hunks) {
3
+ const file = new LineFile(text);
4
+ const replacements = [];
5
+ const found = [];
6
+ let cursor = 0;
7
+ for (const [index, hunk] of hunks.entries()) {
8
+ if (hunk.context !== null) {
9
+ const hit = file.seek(scope, matchers, [hunk.context], cursor, false);
10
+ if (hit === null) {
11
+ return {
12
+ ok: false,
13
+ problem: { reason: "context-not-found", hunk: index, context: hunk.context },
14
+ };
15
+ }
16
+ cursor = hit.line + 1;
17
+ }
18
+ let body = hunk.lines;
19
+ let old = oldLines(body);
20
+ let hit = old.length === 0 ? null : file.seek(scope, matchers, old, cursor, hunk.endOfFile);
21
+ if (hit === null && old.length > 0 && old.at(-1) === "") {
22
+ // A trailing empty old line is often only a blank separator.
23
+ body = withoutLastOldLine(body);
24
+ old = oldLines(body);
25
+ hit = old.length === 0 ? null : file.seek(scope, matchers, old, cursor, hunk.endOfFile);
26
+ }
27
+ if (old.length === 0) {
28
+ const insertAt = hunk.context === null ? file.lines.length : cursor;
29
+ replacements.push({ start: insertAt, remove: 0, lines: body.map((line) => line.text) });
30
+ continue;
31
+ }
32
+ if (hit === null) {
33
+ return { ok: false, problem: { reason: "lines-not-found", hunk: index, lines: old } };
34
+ }
35
+ replacements.push({ start: hit.line, remove: old.length, lines: newLines(body, file, hit) });
36
+ found.push({ index, hit, size: old.length });
37
+ cursor = hit.line + old.length;
38
+ }
39
+ return applyReplacements(file, replacements, found);
40
+ }
41
+ function applyReplacements(file, replacements, found) {
42
+ const order = replacements
43
+ .map((replacement, at) => ({ replacement, at }))
44
+ .sort((a, b) => a.replacement.start - b.replacement.start || a.at - b.at);
45
+ const result = [...file.lines];
46
+ for (let at = order.length - 1; at >= 0; at -= 1) {
47
+ const { start, remove, lines } = order[at].replacement;
48
+ result.splice(start, remove, ...lines);
49
+ }
50
+ const placed = new Map();
51
+ const changed = [];
52
+ let shift = 0;
53
+ for (const { replacement, at } of order) {
54
+ const first = replacement.start + shift + 1;
55
+ const span = [first, Math.max(first, first + replacement.lines.length - 1)];
56
+ placed.set(at, span);
57
+ changed.push(span);
58
+ shift += replacement.lines.length - replacement.remove;
59
+ }
60
+ const matches = [];
61
+ let hitAt = 0;
62
+ for (const [at, replacement] of replacements.entries()) {
63
+ if (replacement.remove === 0)
64
+ continue;
65
+ const { index, hit, size } = found[hitAt];
66
+ hitAt += 1;
67
+ matches.push({
68
+ index,
69
+ matcher: hit.matcher.id,
70
+ fuzzy: hit.matcher.fuzzy,
71
+ lines: [hit.line + 1, hit.line + size],
72
+ count: 1,
73
+ replaced: [placed.get(at)],
74
+ });
75
+ }
76
+ const fragments = replacements.map((replacement) => ({
77
+ oldText: file.lines.slice(replacement.start, replacement.start + replacement.remove).join("\n"),
78
+ newText: replacement.lines.join("\n"),
79
+ }));
80
+ const ending = file.finalNewline && result.length > 0 ? "\n" : "";
81
+ return { ok: true, text: `${result.join("\n")}${ending}`, matches, changed, fragments };
82
+ }
83
+ function oldLines(body) {
84
+ return body.filter((line) => line.kind !== "+").map((line) => line.text);
85
+ }
86
+ function withoutLastOldLine(body) {
87
+ const last = body.findLastIndex((line) => line.kind !== "+");
88
+ const copy = [...body];
89
+ const line = copy[last];
90
+ const followed = copy.slice(last + 1).length > 0;
91
+ if (line.kind === " " && followed)
92
+ copy[last] = { kind: "+", text: line.text };
93
+ else
94
+ copy.splice(last, 1);
95
+ return copy;
96
+ }
97
+ function newLines(body, file, hit) {
98
+ const lines = [];
99
+ let offset = 0;
100
+ for (const line of body) {
101
+ if (line.kind === "+") {
102
+ lines.push(line.text);
103
+ continue;
104
+ }
105
+ if (line.kind === " ")
106
+ lines.push(file.lines[hit.line + offset]);
107
+ offset += 1;
108
+ }
109
+ return lines;
110
+ }
111
+ class LineFile {
112
+ lines;
113
+ finalNewline;
114
+ haystack;
115
+ lineStartOffsets;
116
+ constructor(text) {
117
+ this.lines = text === "" ? [] : text.split("\n");
118
+ if (text.endsWith("\n"))
119
+ this.lines.pop();
120
+ // An empty file takes a final newline once it has lines.
121
+ this.finalNewline = text === "" || text.endsWith("\n");
122
+ this.haystack = this.lines.map((line) => `${line}\n`).join("");
123
+ this.lineStartOffsets = [];
124
+ let offset = 0;
125
+ for (const line of this.lines) {
126
+ this.lineStartOffsets.push(offset);
127
+ offset += line.length + 1;
128
+ }
129
+ this.lineStartOffsets.push(offset);
130
+ }
131
+ seek(scope, matchers, wanted, from, endOfFile) {
132
+ const needle = wanted.map((line) => `${line}\n`).join("");
133
+ const last = this.lines.length - wanted.length;
134
+ const first = endOfFile ? last : from;
135
+ if (first < from || first > last)
136
+ return null;
137
+ for (const matcher of matchers) {
138
+ scope.checkAbort();
139
+ let at = first;
140
+ while (at <= last) {
141
+ const [range] = findWith(scope, matcher, this.haystack, needle, {
142
+ mode: "lines",
143
+ from: this.lineStartOffsets[at],
144
+ maxMatches: 1,
145
+ });
146
+ if (range === undefined)
147
+ break;
148
+ const line = this.lineAt(range.start);
149
+ if (this.coversWholeLines(range, line, wanted.length) && (!endOfFile || line === last)) {
150
+ return { line, matcher };
151
+ }
152
+ if (endOfFile)
153
+ break;
154
+ at = Math.max(at, line) + 1;
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+ coversWholeLines(range, line, count) {
160
+ if (range.refused !== undefined)
161
+ return false;
162
+ return (this.lineStartOffsets[line] === range.start &&
163
+ this.lineStartOffsets[line + count] === range.end);
164
+ }
165
+ lineAt(offset) {
166
+ let low = 0;
167
+ let high = this.lineStartOffsets.length - 1;
168
+ while (low < high) {
169
+ const middle = (low + high + 1) >>> 1;
170
+ if (this.lineStartOffsets[middle] <= offset)
171
+ low = middle;
172
+ else
173
+ high = middle - 1;
174
+ }
175
+ return low;
176
+ }
177
+ }
@@ -0,0 +1,4 @@
1
+ import type { ToolCallContext } from "@better-fs-tools/read";
2
+ import type { ApplyPatchDependencies } from "../contract/deps.ts";
3
+ import type { MutationResult } from "../contract/result.ts";
4
+ export declare function runApplyPatch<THost>(deps: ApplyPatchDependencies<THost>, input: unknown, call: ToolCallContext<THost>): Promise<MutationResult>;