@criogaid/pi-hashline-edit 0.3.0 → 0.4.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 (69) hide show
  1. package/README.md +59 -50
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1594 -694
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +219 -130
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -1,249 +1,393 @@
1
- import { chmod, lstat, mkdir, mkdtemp, open, readFile, realpath, rename, rm, stat, link } from "node:fs/promises";
1
+ import {
2
+ chmod,
3
+ lstat,
4
+ mkdir,
5
+ mkdtemp,
6
+ open,
7
+ readFile,
8
+ realpath,
9
+ rename,
10
+ rm,
11
+ stat,
12
+ link,
13
+ } from "node:fs/promises";
2
14
  import { dirname, join } from "node:path";
3
15
  import { createHash } from "node:crypto";
4
- import { decodeEditableText } from "../core/text.ts";
16
+ import { decodeEditableText, unwritableTextReason } from "../core/text.ts";
17
+ import { errorMessage, OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
5
18
 
6
19
  export type PublicationStatus = "NOT_PUBLISHED" | "PUBLISHED" | "UNKNOWN";
7
20
  export type CommitMode = "create" | "overwrite";
8
21
 
9
22
  export interface CommitOptions {
10
- mode?: CommitMode;
11
- expectedRevision?: string;
12
- signal?: AbortSignal;
23
+ mode?: CommitMode;
24
+ expectedRevision?: string;
25
+ signal?: AbortSignal;
26
+ /** Caller-supplied revision of the current file, skipping the readFile + SHA-256 in inspectTarget. */
27
+ knownBeforeRevision?: string;
13
28
  }
14
29
 
15
30
  export interface MutationVersions {
16
- baseRevision?: string;
17
- publishedRevision: string;
18
- observedRevision: string;
31
+ baseRevision?: string;
32
+ publishedRevision: string;
33
+ observedRevision: string;
19
34
  }
20
35
 
21
36
  export interface CommitResult extends MutationVersions {
22
- created: boolean;
23
- /** Backward-compatible alias for publishedRevision. */
24
- revision: string;
25
- publication: "NOT_PUBLISHED" | "PUBLISHED";
37
+ created: boolean;
38
+ publication: "NOT_PUBLISHED" | "PUBLISHED";
26
39
  }
27
40
 
28
41
  export class FileMutationError extends Error {
29
- readonly stage: "prepare" | "commit" | "post_process";
30
- readonly publication: PublicationStatus;
42
+ readonly stage: "prepare" | "commit" | "post_process";
43
+ readonly publication: PublicationStatus;
31
44
 
32
- constructor(stage: "prepare" | "commit" | "post_process", publication: PublicationStatus, message: string, options?: { cause?: unknown }) {
33
- super(message, options);
34
- this.name = "FileMutationError";
35
- this.stage = stage;
36
- this.publication = publication;
37
- }
45
+ constructor(
46
+ stage: "prepare" | "commit" | "post_process",
47
+ publication: PublicationStatus,
48
+ message: string,
49
+ options?: { cause?: unknown },
50
+ ) {
51
+ super(message, options);
52
+ this.name = "FileMutationError";
53
+ this.stage = stage;
54
+ this.publication = publication;
55
+ }
38
56
  }
39
57
 
40
58
  export function byteRevision(content: string | Uint8Array): string {
41
- return createHash("sha256").update(content).digest("hex");
59
+ return createHash("sha256").update(content).digest("hex");
42
60
  }
43
61
 
44
62
  export async function fileRevision(path: string): Promise<string> {
45
- return byteRevision(await readFile(path));
63
+ return byteRevision(await readFile(path));
46
64
  }
47
65
 
48
66
  /** Decode and bind a mutation snapshot to the exact bytes read. */
49
67
  export async function readEditableSnapshot(path: string, displayPath: string) {
50
- try {
51
- const bytes = await readFile(path);
52
- return { text: decodeEditableText(bytes), baseRevision: byteRevision(bytes) };
53
- } catch (error) {
54
- throw new Error(`Error reading ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
55
- }
68
+ try {
69
+ const bytes = await readFile(path);
70
+ return { text: decodeEditableText(bytes), baseRevision: byteRevision(bytes) };
71
+ } catch (error) {
72
+ throw new Error(`Error reading ${displayPath}: ${errorMessage(error)}`);
73
+ }
56
74
  }
57
75
 
58
76
  /** Publish a read-modify-write result against its source revision. Callers own the queue. */
59
- export async function commitReplacement(path: string, displayPath: string, text: string, baseRevision: string, signal?: AbortSignal) {
60
- try {
61
- return await commitFile(path, text, { mode: "overwrite", expectedRevision: baseRevision, signal });
62
- } catch (error) {
63
- if (error instanceof FileMutationError) throw error;
64
- throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
65
- }
77
+ export async function commitReplacement(
78
+ path: string,
79
+ displayPath: string,
80
+ text: string,
81
+ baseRevision: string,
82
+ signal?: AbortSignal,
83
+ ) {
84
+ try {
85
+ return await commitFile(path, text, {
86
+ mode: "overwrite",
87
+ expectedRevision: baseRevision,
88
+ knownBeforeRevision: baseRevision,
89
+ signal,
90
+ });
91
+ } catch (error) {
92
+ if (error instanceof FileMutationError) throw error;
93
+ throw new FileMutationError(
94
+ "commit",
95
+ "UNKNOWN",
96
+ `Error writing ${displayPath}: ${errorMessage(error)}`,
97
+ { cause: error },
98
+ );
99
+ }
66
100
  }
67
101
 
68
102
  function prepareError(message: string, cause?: unknown): FileMutationError {
69
- return new FileMutationError("prepare", "NOT_PUBLISHED", message, { cause });
103
+ return new FileMutationError("prepare", "NOT_PUBLISHED", message, { cause });
70
104
  }
71
105
 
72
106
  function errorCode(error: unknown): string | undefined {
73
- return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : undefined;
107
+ return typeof error === "object" &&
108
+ error !== null &&
109
+ "code" in error &&
110
+ typeof error.code === "string"
111
+ ? error.code
112
+ : undefined;
74
113
  }
75
114
 
76
115
  interface TargetInfo {
77
- existed: boolean;
78
- publishPath: string;
79
- beforeRevision?: string;
80
- modeBits?: number;
81
- }
82
-
83
- async function inspectTarget(path: string): Promise<TargetInfo> {
84
- let entry;
85
- try {
86
- entry = await lstat(path);
87
- } catch (error) {
88
- if (errorCode(error) === "ENOENT") return { existed: false, publishPath: path };
89
- throw prepareError(`unable to inspect target: ${error instanceof Error ? error.message : String(error)}`, error);
90
- }
91
-
92
- let publishPath = path;
93
- if (entry.isSymbolicLink()) {
94
- try {
95
- publishPath = await realpath(path);
96
- } catch (error) {
97
- throw prepareError(`target symlink cannot be resolved: ${error instanceof Error ? error.message : String(error)}`, error);
98
- }
99
- }
100
-
101
- let target;
102
- try {
103
- target = await stat(publishPath);
104
- } catch (error) {
105
- throw prepareError(`unable to inspect target: ${error instanceof Error ? error.message : String(error)}`, error);
106
- }
107
- if (!target.isFile()) throw prepareError("target is not a regular file");
108
- if (target.nlink > 1) throw prepareError("target has multiple hard links; refusing to split the link set");
109
-
110
- let beforeRevision: string;
111
- try {
112
- beforeRevision = await fileRevision(publishPath);
113
- } catch (error) {
114
- throw prepareError(`unable to read target revision: ${error instanceof Error ? error.message : String(error)}`, error);
115
- }
116
- return {
117
- existed: true,
118
- publishPath,
119
- beforeRevision,
120
- modeBits: target.mode,
121
- };
122
- }
123
-
124
- async function writeAndSyncTemp(tempPath: string, content: Buffer, modeBits: number | undefined, signal: AbortSignal | undefined): Promise<void> {
125
- signal?.throwIfAborted();
126
- const handle = await open(tempPath, "w", modeBits === undefined ? 0o600 : modeBits & 0o7777);
127
- try {
128
- await handle.writeFile(content);
129
- await handle.sync();
130
- } finally {
131
- await handle.close();
132
- }
133
- if (modeBits !== undefined) await chmod(tempPath, modeBits & 0o7777);
134
- }
135
-
136
- async function publishCreate(tempPath: string, targetPath: string, signal: AbortSignal | undefined): Promise<void> {
137
- // link() 在同一文件系统内创建不可覆盖的目录项,避免检查与发布之间的覆盖竞争。
138
- signal?.throwIfAborted();
139
- try {
140
- await link(tempPath, targetPath);
141
- } catch (error) {
142
- if (errorCode(error) === "EEXIST" || errorCode(error) === "ENOTEMPTY") {
143
- throw new FileMutationError("commit", "NOT_PUBLISHED", "target appeared during create; refusing to overwrite it", { cause: error });
144
- }
145
- throw new FileMutationError("commit", "UNKNOWN", `unable to publish new target: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
146
- }
147
- }
148
-
149
- async function publishReplace(tempPath: string, targetPath: string, signal: AbortSignal | undefined): Promise<void> {
150
- // rename() 替换目录项,但不会先删除旧文件;读者看到旧文件或完整新文件。
151
- signal?.throwIfAborted();
152
- try {
153
- await rename(tempPath, targetPath);
154
- } catch (error) {
155
- throw new FileMutationError("commit", "UNKNOWN", `unable to publish replacement: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
156
- }
116
+ existed: boolean;
117
+ publishPath: string;
118
+ beforeRevision?: string;
119
+ modeBits?: number;
120
+ }
121
+
122
+ async function inspectTarget(path: string, knownBeforeRevision?: string): Promise<TargetInfo> {
123
+ let entry;
124
+ try {
125
+ entry = await lstat(path);
126
+ } catch (error) {
127
+ if (errorCode(error) === "ENOENT") return { existed: false, publishPath: path };
128
+ throw prepareError(`unable to inspect target: ${errorMessage(error)}`, error);
129
+ }
130
+
131
+ let publishPath = path;
132
+ if (entry.isSymbolicLink()) {
133
+ try {
134
+ publishPath = await realpath(path);
135
+ } catch (error) {
136
+ throw prepareError(`target symlink cannot be resolved: ${errorMessage(error)}`, error);
137
+ }
138
+ }
139
+
140
+ let target;
141
+ try {
142
+ target = await stat(publishPath);
143
+ } catch (error) {
144
+ throw prepareError(`unable to inspect target: ${errorMessage(error)}`, error);
145
+ }
146
+ if (!target.isFile()) throw prepareError("target is not a regular file");
147
+ if (target.nlink > 1)
148
+ throw prepareError("target has multiple hard links; refusing to split the link set");
149
+
150
+ let beforeRevision: string;
151
+ if (knownBeforeRevision !== undefined) {
152
+ beforeRevision = knownBeforeRevision;
153
+ } else {
154
+ try {
155
+ beforeRevision = await fileRevision(publishPath);
156
+ } catch (error) {
157
+ throw prepareError(`unable to read target revision: ${errorMessage(error)}`, error);
158
+ }
159
+ }
160
+ return {
161
+ existed: true,
162
+ publishPath,
163
+ beforeRevision,
164
+ modeBits: target.mode,
165
+ };
166
+ }
167
+
168
+ async function writeAndSyncTemp(
169
+ tempPath: string,
170
+ content: Buffer,
171
+ modeBits: number | undefined,
172
+ signal: AbortSignal | undefined,
173
+ ): Promise<void> {
174
+ throwIfCancelled(signal);
175
+ const handle = await open(tempPath, "w", modeBits === undefined ? 0o600 : modeBits & 0o7777);
176
+ try {
177
+ await handle.writeFile(content);
178
+ await handle.sync();
179
+ } finally {
180
+ await handle.close();
181
+ }
182
+ if (modeBits !== undefined) await chmod(tempPath, modeBits & 0o7777);
183
+ }
184
+
185
+ async function publishCreate(
186
+ tempPath: string,
187
+ targetPath: string,
188
+ signal: AbortSignal | undefined,
189
+ ): Promise<void> {
190
+ // link() creates an unclobberable directory entry on the same filesystem, avoiding create/replace races.
191
+ throwIfCancelled(signal);
192
+ try {
193
+ await link(tempPath, targetPath);
194
+ } catch (error) {
195
+ if (errorCode(error) === "EEXIST" || errorCode(error) === "ENOTEMPTY") {
196
+ throw new FileMutationError(
197
+ "commit",
198
+ "NOT_PUBLISHED",
199
+ "target appeared during create; refusing to overwrite it",
200
+ { cause: error },
201
+ );
202
+ }
203
+ throw new FileMutationError(
204
+ "commit",
205
+ "UNKNOWN",
206
+ `unable to publish new target: ${errorMessage(error)}`,
207
+ { cause: error },
208
+ );
209
+ }
210
+ }
211
+
212
+ async function publishReplace(
213
+ tempPath: string,
214
+ targetPath: string,
215
+ signal: AbortSignal | undefined,
216
+ ): Promise<void> {
217
+ // rename() replaces the directory entry atomically without deleting the old file first; readers observe old or new.
218
+ throwIfCancelled(signal);
219
+ try {
220
+ await rename(tempPath, targetPath);
221
+ } catch (error) {
222
+ throw new FileMutationError(
223
+ "commit",
224
+ "UNKNOWN",
225
+ `unable to publish replacement: ${errorMessage(error)}`,
226
+ { cause: error },
227
+ );
228
+ }
157
229
  }
158
230
 
159
231
  async function syncDirectory(path: string): Promise<void> {
160
- if (process.platform === "win32") return;
161
- const handle = await open(path, "r");
162
- try {
163
- await handle.sync();
164
- } finally {
165
- await handle.close();
166
- }
232
+ if (process.platform === "win32") return;
233
+ const handle = await open(path, "r");
234
+ try {
235
+ await handle.sync();
236
+ } catch (error) {
237
+ // Some filesystems do not support directory fsync; preserve real I/O failures.
238
+ if (errorCode(error) !== "EINVAL" && errorCode(error) !== "ENOTSUP") throw error;
239
+ } finally {
240
+ await handle.close();
241
+ }
167
242
  }
168
243
 
169
244
  /** Validate the target, skip identical content, otherwise sync and publish. Callers own the file queue. */
170
- export async function commitFile(path: string, content: string, options: CommitOptions = {}): Promise<CommitResult> {
171
- if (content.includes("\0")) throw prepareError("UNSUPPORTED_TEXT: NUL bytes are not editable.");
172
- const bytes = Buffer.from(content, "utf8");
173
- if (bytes.toString("utf8") !== content) throw prepareError("INVALID_UNICODE: content cannot be encoded losslessly as UTF-8.");
174
- const target = await inspectTarget(path);
175
- const mode = options.mode ?? (target.existed ? "overwrite" : "create");
176
- if (mode === "create" && target.existed) throw prepareError("target already exists; use mode=overwrite");
177
- if (mode === "overwrite" && !target.existed) throw prepareError("target does not exist; use mode=create or omit mode");
178
- if (mode === "create" && options.expectedRevision !== undefined) throw prepareError("expectedRevision cannot be combined with mode=create");
179
- if (options.expectedRevision !== undefined && (!target.beforeRevision || target.beforeRevision !== options.expectedRevision)) {
180
- throw prepareError("expectedRevision does not match the current file");
181
- }
182
- try { options.signal?.throwIfAborted(); } catch (error) { throw prepareError("mutation was cancelled before publication", error); }
183
- const publishedRevision = byteRevision(bytes);
184
- // Mode, revision, target safety, and cancellation checks still apply to no-ops.
185
- if (target.beforeRevision === publishedRevision) {
186
- return {
187
- created: false,
188
- baseRevision: target.beforeRevision,
189
- publishedRevision,
190
- observedRevision: target.beforeRevision,
191
- revision: publishedRevision,
192
- publication: "NOT_PUBLISHED",
193
- };
194
- }
195
-
196
- const publishPath = target.publishPath;
197
- const publishDirectory = dirname(publishPath);
198
- let tempDir: string;
199
- try {
200
- await mkdir(publishDirectory, { recursive: true });
201
- tempDir = await mkdtemp(join(publishDirectory, ".hashline-commit-"));
202
- } catch (error) {
203
- throw new FileMutationError("commit", "NOT_PUBLISHED", `unable to prepare temporary publication area: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
204
- }
205
- const tempPath = join(tempDir, "content");
206
- let published = false;
207
- let failure: unknown;
208
- try {
209
- await writeAndSyncTemp(tempPath, bytes, target.modeBits, options.signal);
210
- if (mode === "overwrite" && options.expectedRevision !== undefined) {
211
- let currentRevision: string;
212
- try {
213
- currentRevision = await fileRevision(publishPath);
214
- } catch (error) {
215
- throw prepareError(`unable to recheck target revision: ${error instanceof Error ? error.message : String(error)}`, error);
216
- }
217
- if (currentRevision !== options.expectedRevision) throw prepareError("expectedRevision changed before publication");
218
- }
219
- if (mode === "create") await publishCreate(tempPath, publishPath, options.signal);
220
- else await publishReplace(tempPath, publishPath, options.signal);
221
- published = true;
222
- await syncDirectory(publishDirectory);
223
- try {
224
- const observedRevision = await fileRevision(publishPath);
225
- return {
226
- created: mode === "create",
227
- baseRevision: target.beforeRevision,
228
- publishedRevision,
229
- observedRevision,
230
- revision: publishedRevision,
231
- publication: "PUBLISHED",
232
- };
233
- } catch (error) {
234
- throw new FileMutationError("post_process", "PUBLISHED", `target was published but final revision could not be read: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
235
- }
236
- } catch (error) {
237
- failure = error;
238
- if (error instanceof FileMutationError) throw error;
239
- if (published) throw new FileMutationError("post_process", "PUBLISHED", `target was published but post-publication processing failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
240
- throw new FileMutationError("commit", "NOT_PUBLISHED", `unable to prepare or publish target: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
241
- } finally {
242
- try {
243
- await rm(tempDir, { recursive: true, force: true });
244
- } catch (error) {
245
- if (!published) { if (failure !== undefined) throw failure; throw error; }
246
- throw new FileMutationError("post_process", "PUBLISHED", `target was published but temporary cleanup failed: ${error instanceof Error ? error.message : String(error)}`, { cause: failure === undefined ? error : new AggregateError([failure, error], "post-publication cleanup also failed") });
247
- }
248
- }
245
+ export async function commitFile(
246
+ path: string,
247
+ content: string,
248
+ options: CommitOptions = {},
249
+ ): Promise<CommitResult> {
250
+ // Tools reject such input in prepareArguments, but a transformation can still produce it
251
+ // (a regex without `u` can split a surrogate pair), so publication keeps the final check.
252
+ const unwritable = unwritableTextReason(content);
253
+ if (unwritable) throw prepareError(unwritable);
254
+ const bytes = Buffer.from(content, "utf8");
255
+ const target = await inspectTarget(path, options.knownBeforeRevision);
256
+ const mode = options.mode ?? (target.existed ? "overwrite" : "create");
257
+ if (mode === "create" && target.existed)
258
+ throw prepareError("target already exists; use mode=overwrite");
259
+ if (mode === "overwrite" && !target.existed)
260
+ throw prepareError("target does not exist; use mode=create or omit mode");
261
+ if (mode === "create" && options.expectedRevision !== undefined)
262
+ throw prepareError("expectedRevision cannot be combined with mode=create");
263
+ if (
264
+ options.expectedRevision !== undefined &&
265
+ (!target.beforeRevision || target.beforeRevision !== options.expectedRevision)
266
+ ) {
267
+ throw prepareError("expectedRevision does not match the current file");
268
+ }
269
+ try {
270
+ throwIfCancelled(options.signal);
271
+ } catch (error) {
272
+ throw prepareError(`${OPERATION_ABORTED} before publication`, error);
273
+ }
274
+ const publishedRevision = byteRevision(bytes);
275
+ // Mode, revision, target safety, and cancellation checks still apply to no-ops.
276
+ if (target.beforeRevision === publishedRevision) {
277
+ let currentRevision = target.beforeRevision;
278
+ if (options.knownBeforeRevision !== undefined) {
279
+ try {
280
+ throwIfCancelled(options.signal);
281
+ currentRevision = await fileRevision(target.publishPath);
282
+ throwIfCancelled(options.signal);
283
+ } catch (error) {
284
+ if (options.signal?.aborted)
285
+ throw prepareError(`${OPERATION_ABORTED} before publication`, error);
286
+ throw prepareError(`unable to read target revision: ${errorMessage(error)}`, error);
287
+ }
288
+ if (options.expectedRevision !== undefined && currentRevision !== options.expectedRevision) {
289
+ throw prepareError("expectedRevision does not match the current file");
290
+ }
291
+ if (currentRevision !== publishedRevision) {
292
+ target.beforeRevision = currentRevision;
293
+ }
294
+ }
295
+ if (target.beforeRevision === publishedRevision) {
296
+ return {
297
+ created: false,
298
+ baseRevision: target.beforeRevision,
299
+ publishedRevision,
300
+ observedRevision: currentRevision,
301
+ publication: "NOT_PUBLISHED",
302
+ };
303
+ }
304
+ }
305
+
306
+ const publishPath = target.publishPath;
307
+ const publishDirectory = dirname(publishPath);
308
+ let tempDir: string;
309
+ try {
310
+ await mkdir(publishDirectory, { recursive: true });
311
+ tempDir = await mkdtemp(join(publishDirectory, ".hashline-commit-"));
312
+ } catch (error) {
313
+ throw new FileMutationError(
314
+ "commit",
315
+ "NOT_PUBLISHED",
316
+ `unable to prepare temporary publication area: ${errorMessage(error)}`,
317
+ { cause: error },
318
+ );
319
+ }
320
+ const tempPath = join(tempDir, "content");
321
+ let published = false;
322
+ let failure: unknown;
323
+ try {
324
+ await writeAndSyncTemp(tempPath, bytes, target.modeBits, options.signal);
325
+ if (mode === "overwrite" && options.expectedRevision !== undefined) {
326
+ let currentRevision: string;
327
+ try {
328
+ currentRevision = await fileRevision(publishPath);
329
+ } catch (error) {
330
+ throw prepareError(`unable to recheck target revision: ${errorMessage(error)}`, error);
331
+ }
332
+ if (currentRevision !== options.expectedRevision)
333
+ throw prepareError("expectedRevision changed before publication");
334
+ }
335
+ if (mode === "create") await publishCreate(tempPath, publishPath, options.signal);
336
+ else await publishReplace(tempPath, publishPath, options.signal);
337
+ published = true;
338
+ await syncDirectory(publishDirectory);
339
+ try {
340
+ const observedRevision = await fileRevision(publishPath);
341
+ return {
342
+ created: mode === "create",
343
+ baseRevision: target.beforeRevision,
344
+ publishedRevision,
345
+ observedRevision,
346
+ publication: "PUBLISHED",
347
+ };
348
+ } catch (error) {
349
+ throw new FileMutationError(
350
+ "post_process",
351
+ "PUBLISHED",
352
+ `target was published but final revision could not be read: ${errorMessage(error)}`,
353
+ { cause: error },
354
+ );
355
+ }
356
+ } catch (error) {
357
+ failure = error;
358
+ if (error instanceof FileMutationError) throw error;
359
+ if (published)
360
+ throw new FileMutationError(
361
+ "post_process",
362
+ "PUBLISHED",
363
+ `target was published but post-publication processing failed: ${errorMessage(error)}`,
364
+ { cause: error },
365
+ );
366
+ throw new FileMutationError(
367
+ "commit",
368
+ "NOT_PUBLISHED",
369
+ `unable to prepare or publish target: ${errorMessage(error)}`,
370
+ { cause: error },
371
+ );
372
+ } finally {
373
+ try {
374
+ await rm(tempDir, { recursive: true, force: true });
375
+ } catch (error) {
376
+ if (!published) {
377
+ if (failure !== undefined) throw failure;
378
+ throw error;
379
+ }
380
+ throw new FileMutationError(
381
+ "post_process",
382
+ "PUBLISHED",
383
+ `target was published but temporary cleanup failed: ${errorMessage(error)}`,
384
+ {
385
+ cause:
386
+ failure === undefined
387
+ ? error
388
+ : new AggregateError([failure, error], "post-publication cleanup also failed"),
389
+ },
390
+ );
391
+ }
392
+ }
249
393
  }