@deepseek-ai/dsh-util-file-operations 0.0.0-stage → 0.2.3-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,794 @@
1
+ import { FS_ERROR_CODES, FsError, FsTargetKey, FsVersion } from "@deepseek-ai/dsh-fs";
2
+ import { applyHunks } from "@deepseek-ai/dsh-fs-patch";
3
+ //#region lib/types/index.js
4
+ /**
5
+ * The `FileSystem` file-operation rules as one function over a machine's `node:fs/promises` and `node:path`, which
6
+ * references only its parameters and JavaScript globals. An execution environment runs it from its source text on the
7
+ * machine where the file lives, because `ctx.environments.define()` sends only that text; `FileOperationEnv.limits` and
8
+ * `FileOperationEnv.sandbox` carry such a run's message bound and write sandbox. `fileOperations` builds the
9
+ * `FileSystem` methods on a runner of that function.
10
+ * @module @deepseek-ai/dsh-util-file-operations
11
+ */
12
+ async function fileOperation(request, env) {
13
+ const { fs, path: P } = env;
14
+ const hooks = env.hooks ?? {};
15
+ const result = (_op, value) => value;
16
+ const fail = (code, message, cause) => Object.assign(new Error(message), cause === void 0 ? { code } : {
17
+ code,
18
+ cause
19
+ });
20
+ const codeOf = (error) => error?.code;
21
+ const messageOf = (error) => {
22
+ const message = error?.message;
23
+ return typeof message === "string" ? message : String(error);
24
+ };
25
+ const coded = (error) => typeof codeOf(error) === "string" && String(codeOf(error)).startsWith("FS_");
26
+ const absent = (error) => codeOf(error) === "ENOENT" || codeOf(error) === "ENOTDIR";
27
+ const permission = (error) => codeOf(error) === "EACCES" || codeOf(error) === "EPERM";
28
+ const abortError = (error) => error?.name === "AbortError";
29
+ const sandboxDenied = (error) => codeOf(error) === "SANDBOX_DENIED" ? fail("FS_SANDBOX_DENIED", messageOf(error), error) : void 0;
30
+ const classify = (verb, display, error) => {
31
+ if (coded(error) || typeof codeOf(error) !== "string") return error;
32
+ const failure = `cannot ${verb} "${display}"`;
33
+ if (absent(error)) return fail("FS_NOT_FOUND", `${failure}: not found`, error);
34
+ if (permission(error)) return fail("FS_PERMISSION_DENIED", `${failure}: permission denied`, error);
35
+ if (codeOf(error) === "EISDIR") return fail("FS_NOT_REGULAR_FILE", `${failure}: not a regular file`, error);
36
+ return fail("FS_IO_ERROR", `${failure}: ${messageOf(error)}`, error);
37
+ };
38
+ const checkAborted = (verb) => {
39
+ if (env.signal?.aborted === true) throw fail("FS_ABORTED", `${verb} aborted`);
40
+ };
41
+ const fits = (units) => env.limits === void 0 || units * 2 + 4096 <= env.limits.maxMessageBytes;
42
+ const tooLarge = (verb, display) => fail("FS_TOO_LARGE", `cannot ${verb} "${display}": larger than the environment connection carries`);
43
+ const changed = (verb, display) => fail("FS_STALE_VERSION", `cannot ${verb} "${display}": file changed since it was read`);
44
+ const versionOf = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
45
+ /** The entry type one metadata read reports, most specific classification first. */
46
+ const typeOfEntry = (info) => {
47
+ if (info.isSymbolicLink()) return "symlink";
48
+ if (info.isFile()) return "file";
49
+ if (info.isDirectory()) return "directory";
50
+ return "other";
51
+ };
52
+ const describe = (info) => ({
53
+ version: versionOf(info),
54
+ type: typeOfEntry(info),
55
+ size: Number(info.size),
56
+ mode: Number(info.mode & 511n)
57
+ });
58
+ const probe = async (path, follow = true) => {
59
+ try {
60
+ return await (follow ? fs.stat(path, { bigint: true }) : fs.lstat(path, { bigint: true }));
61
+ } catch (error) {
62
+ if (absent(error)) return null;
63
+ throw classify("stat", path, error);
64
+ }
65
+ };
66
+ const requireFile = async (path, display, verb, expected) => {
67
+ const existing = await probe(path);
68
+ if (existing === null) throw changed(verb, display);
69
+ if (!existing.isFile()) throw fail("FS_NOT_REGULAR_FILE", `cannot ${verb} "${display}": not a regular file`);
70
+ if (expected !== void 0 && versionOf(existing) !== expected) throw changed(verb, display);
71
+ return existing;
72
+ };
73
+ const writeTarget = async (path, display, expected) => {
74
+ const existing = await probe(path);
75
+ if (existing !== null && !existing.isFile()) throw fail("FS_NOT_REGULAR_FILE", `cannot write "${display}": not a regular file`);
76
+ if (expected?.kind === "replaceIfVersion") {
77
+ if (existing === null) throw fail("FS_STALE_VERSION", `cannot write "${display}": file no longer exists`);
78
+ if (versionOf(existing) !== expected.version) throw changed("write", display);
79
+ } else if (expected?.kind === "createIfAbsent" && existing !== null) throw fail("FS_NOT_OBSERVED", `cannot overwrite existing "${display}" without reading it first`);
80
+ return existing;
81
+ };
82
+ const versionAfter = async (path) => {
83
+ const after = await probe(path);
84
+ /* v8 ignore next -- needs a concurrent unlink between publication and this stat. */
85
+ return after === null ? `missing:${path}` : versionOf(after);
86
+ };
87
+ const normalize = (text) => text.replaceAll("\r\n", "\n");
88
+ const crlfOf = (raw) => {
89
+ const sample = raw.slice(0, 4096);
90
+ const crlf = sample.split("\r\n").length - 1;
91
+ return crlf > sample.split("\n").length - 1 - crlf;
92
+ };
93
+ const restore = (content, crlf) => crlf ? normalize(content).split("\n").join("\r\n") : content;
94
+ /** A NUL byte makes content binary rather than text. */
95
+ const assertBytes = (bytes, verb, display) => {
96
+ if (bytes.includes(0)) throw fail("FS_NOT_TEXT", `cannot ${verb} "${display}": binary file`);
97
+ };
98
+ const decodeUtf8 = (bytes, verb, display) => {
99
+ try {
100
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
101
+ } catch (invalid) {
102
+ throw fail("FS_NOT_TEXT", `cannot ${verb} "${display}": invalid UTF-8 text`, invalid);
103
+ }
104
+ };
105
+ /** Leading bytes a text read inspects for NUL, applied by a whole-file read and by each streamed step. */
106
+ const SAMPLE_BYTES = 8192;
107
+ /**
108
+ * Length of the UTF-8 sequence a lead byte starts: 0xC2–0xDF starts two bytes, 0xE0–0xEF three, 0xF0–0xF4 four,
109
+ * and every other byte starts none.
110
+ * @param lead - the first byte of a sequence.
111
+ * @returns its length in bytes, or 0 when it starts no multi-byte sequence.
112
+ */
113
+ const sequenceLength = (lead) => {
114
+ if (lead >= 194 && lead <= 223) return 2;
115
+ if (lead >= 224 && lead <= 239) return 3;
116
+ if (lead >= 240 && lead <= 244) return 4;
117
+ return 0;
118
+ };
119
+ /** Whether `bytes` are the start of a well-formed UTF-8 sequence a later step completes, so they can be carried. */
120
+ const unfinishedSequence = (bytes) => {
121
+ const lead = bytes[0];
122
+ const expected = sequenceLength(lead);
123
+ if (expected === 0 || bytes.length >= expected) return false;
124
+ for (let index = 1; index < bytes.length; index += 1) if ((bytes[index] & 192) !== 128) return false;
125
+ return true;
126
+ };
127
+ const decode = (bytes, verb, display) => {
128
+ assertBytes(verb === "read" ? bytes.subarray(0, SAMPLE_BYTES) : bytes, verb, display);
129
+ return decodeUtf8(bytes, verb, display);
130
+ };
131
+ const readFile = async (path, display, verb) => {
132
+ checkAborted(verb);
133
+ try {
134
+ return await fs.readFile(path, env.signal === void 0 ? {} : { signal: env.signal });
135
+ } catch (error) {
136
+ /* v8 ignore next -- a mid-read abort needs cancellation racing an active read; earlier checkpoints catch a prior abort. */
137
+ if (abortError(error)) throw fail("FS_ABORTED", `${verb} aborted`);
138
+ throw classify(verb, display, error);
139
+ } finally {
140
+ checkAborted(verb);
141
+ }
142
+ };
143
+ const readForEdit = async (path, display) => {
144
+ const raw = decode(await readFile(path, display, "edit"), "edit", display);
145
+ return {
146
+ content: normalize(raw),
147
+ crlf: crlfOf(raw)
148
+ };
149
+ };
150
+ const statRegular = async (path, display) => {
151
+ checkAborted("read");
152
+ let info;
153
+ try {
154
+ info = await fs.stat(path, { bigint: true });
155
+ } catch (error) {
156
+ throw classify("read", display, error);
157
+ }
158
+ if (!info.isFile()) throw fail("FS_NOT_REGULAR_FILE", `cannot read "${display}": not a regular file`);
159
+ return info;
160
+ };
161
+ /**
162
+ * Best-effort LF-normalized diff basis of `path`: null for a non-regular, at/above-bound, binary, non-UTF-8, resized
163
+ * or unreadable file. The bound applies to the opened descriptor, and reads go in 64 KiB chunks so cancellation is
164
+ * observed between them; cancellation propagates.
165
+ */
166
+ const basis = async (path, maxBytes) => {
167
+ checkAborted("read");
168
+ try {
169
+ const handle = await fs.open(path, "r");
170
+ let buffer;
171
+ let total = 0;
172
+ let openedSize = 0;
173
+ try {
174
+ checkAborted("read");
175
+ const info = await handle.stat();
176
+ checkAborted("read");
177
+ if (!info.isFile() || info.size >= maxBytes) return null;
178
+ openedSize = info.size;
179
+ buffer = Buffer.allocUnsafe(openedSize + 1);
180
+ while (total < buffer.length) {
181
+ checkAborted("read");
182
+ const { bytesRead } = await handle.read(buffer, total, Math.min(buffer.length - total, 64 * 1024), null);
183
+ if (bytesRead === 0) break;
184
+ total += bytesRead;
185
+ }
186
+ } finally {
187
+ await handle.close();
188
+ }
189
+ checkAborted("read");
190
+ if (total !== openedSize) return null;
191
+ try {
192
+ return normalize(decode(buffer.subarray(0, total), "edit", path));
193
+ } catch (_notText) {
194
+ return null;
195
+ }
196
+ } catch (error) {
197
+ if (coded(error)) throw error;
198
+ if (typeof codeOf(error) === "string") return null;
199
+ throw error;
200
+ }
201
+ };
202
+ const literalEdit = (content, edit, display) => {
203
+ const oldString = normalize(edit.oldString);
204
+ if (oldString.length === 0) throw fail("FS_EDIT_NOT_FOUND", "old_string must be a non-empty string");
205
+ let matches = 0;
206
+ for (let index = content.indexOf(oldString); index !== -1; index = content.indexOf(oldString, index + oldString.length)) matches++;
207
+ if (matches === 0) throw fail("FS_EDIT_NOT_FOUND", `old_string was not found in "${display}"`);
208
+ if (!edit.replaceAll && matches > 1) throw fail("FS_AMBIGUOUS_EDIT", `old_string matched ${matches} times in "${display}"; provide a more specific old_string or set replace_all to true`);
209
+ return content.split(oldString).join(normalize(edit.newString));
210
+ };
211
+ const writeFailure = (display, error) => {
212
+ if (coded(error)) return error;
213
+ const denied = sandboxDenied(error);
214
+ if (denied !== void 0) return denied;
215
+ /* v8 ignore next -- an abort during the staged write needs a writeFile/signal race; the checkpoints around it are tested. */
216
+ if (abortError(error)) return fail("FS_ABORTED", "write aborted");
217
+ if (permission(error)) return fail("FS_PERMISSION_DENIED", `cannot write "${display}": permission denied`, error);
218
+ if (typeof codeOf(error) === "string") return fail("FS_IO_ERROR", `cannot write "${display}": ${messageOf(error)}`, error);
219
+ return error;
220
+ };
221
+ const guardedCreateFailure = async (error, path, display) => {
222
+ let existing;
223
+ try {
224
+ existing = await (hooks.inspectPublicationTarget ?? ((target) => fs.lstat(target, { bigint: true })))(path);
225
+ } catch (metadataError) {
226
+ if (!absent(metadataError)) throw fail("FS_IO_ERROR", `cannot write "${display}": ${messageOf(metadataError)}`, metadataError);
227
+ }
228
+ if (existing !== void 0 && !existing.isFile()) throw fail("FS_NOT_REGULAR_FILE", `cannot write "${display}": not a regular file`, error);
229
+ if (existing !== void 0 || codeOf(error) === "EEXIST") throw fail("FS_NOT_OBSERVED", `cannot overwrite existing "${display}" without reading it first`, error);
230
+ throw fail("FS_IO_ERROR", `cannot write "${display}": ${messageOf(error)}`, error);
231
+ };
232
+ /**
233
+ * Atomically publish `content` at `path`. On Windows an existing destination keeps its security descriptor through
234
+ * the DACL and replacement hooks; a replaced destination that vanished during staging is recreated by rename.
235
+ */
236
+ const publish = async (path, display, content, mode, options = {}) => {
237
+ const cancellable = options.cancellable ?? true;
238
+ const check = () => {
239
+ if (cancellable) checkAborted("write");
240
+ };
241
+ const existingDestination = options.existingDestination ?? mode !== void 0;
242
+ const platform = hooks.platform ?? env.platform;
243
+ check();
244
+ const directory = P.dirname(path);
245
+ try {
246
+ await fs.mkdir(directory, { recursive: true });
247
+ } catch (error) {
248
+ throw writeFailure(display, error);
249
+ }
250
+ check();
251
+ const stagingDir = P.join(directory, hooks.tempDirName?.(path) ?? `.${P.basename(path)}.${Date.now().toString(36)}${Math.random().toString(36).slice(2)}.tmpdir`);
252
+ const tempPath = P.join(stagingDir, hooks.tempName?.(path) ?? `${P.basename(path)}.tmp`);
253
+ const removeStagingDir = hooks.removeStagingDir ?? ((dir) => fs.rm(dir, {
254
+ recursive: true,
255
+ force: true
256
+ }));
257
+ let handle;
258
+ let stagingCreated = false;
259
+ try {
260
+ await fs.mkdir(stagingDir, { mode: 448 });
261
+ stagingCreated = true;
262
+ await fs.chmod(stagingDir, 448);
263
+ handle = await fs.open(tempPath, "wx", 384);
264
+ await handle.chmod(384);
265
+ if (platform === "win32" && existingDestination) await hooks.copyFileDacl?.(path, tempPath);
266
+ await handle.writeFile(content, {
267
+ ...typeof content === "string" ? { encoding: "utf8" } : {},
268
+ ...cancellable && env.signal !== void 0 ? { signal: env.signal } : {}
269
+ });
270
+ await handle.sync();
271
+ await hooks.inspectTemp?.({
272
+ stagingDir,
273
+ tempPath
274
+ });
275
+ if (mode !== void 0) await handle.chmod(mode);
276
+ await handle.close();
277
+ handle = void 0;
278
+ check();
279
+ if (options.createIfAbsent === true) try {
280
+ await (hooks.linkFile ?? fs.link)(tempPath, path);
281
+ } catch (error) {
282
+ await guardedCreateFailure(error, path, display);
283
+ }
284
+ else if (platform === "win32" && existingDestination && hooks.replaceFile !== void 0) try {
285
+ await hooks.replaceFile(path, tempPath);
286
+ } catch (error) {
287
+ if (codeOf(error) !== "ENOENT") throw error;
288
+ await fs.rename(tempPath, path);
289
+ }
290
+ else await fs.rename(tempPath, path);
291
+ try {
292
+ await removeStagingDir(stagingDir);
293
+ } catch (_committedStagingCleanupFailure) {}
294
+ } catch (error) {
295
+ let failure = writeFailure(display, error);
296
+ /* v8 ignore next 8 -- reached only if writeFile/sync throws with the handle open; a close failure is a double fault. */
297
+ if (handle !== void 0) try {
298
+ await handle.close();
299
+ } catch (closeError) {
300
+ failure = fail("FS_NOT_FOUND", `write failed (${messageOf(failure)}) and temp close failed (${messageOf(closeError)})`, failure);
301
+ }
302
+ if (!stagingCreated) throw failure;
303
+ try {
304
+ await removeStagingDir(stagingDir);
305
+ } catch (cleanupError) {
306
+ /* v8 ignore next -- needs a second filesystem fault after the primary write failure. */
307
+ throw fail("FS_NOT_FOUND", `write failed (${messageOf(failure)}) and temp cleanup failed (${messageOf(cleanupError)})`, failure);
308
+ }
309
+ throw failure;
310
+ }
311
+ };
312
+ /** Remove one file, returning the failure a delete throws and a move reports, or null once the file is gone. */
313
+ const remove = async (path, display) => {
314
+ try {
315
+ await (hooks.removeFile ?? fs.rm)(path);
316
+ return null;
317
+ } catch (error) {
318
+ if (codeOf(error) === "SANDBOX_DENIED") return {
319
+ code: "FS_SANDBOX_DENIED",
320
+ message: messageOf(error),
321
+ cause: error
322
+ };
323
+ return {
324
+ code: permission(error) ? "FS_PERMISSION_DENIED" : "FS_IO_ERROR",
325
+ message: `cannot delete "${display}": ${messageOf(error)}`,
326
+ cause: error
327
+ };
328
+ }
329
+ };
330
+ const displayPath = (cwd, path) => {
331
+ const driveRelative = env.platform === "win32" && /^[A-Za-z]:(?![\\/])/u.test(cwd);
332
+ const absoluteCwd = P.isAbsolute(cwd) || driveRelative ? cwd : `${env.cwd}${P.sep}${cwd}`;
333
+ const raw = P.isAbsolute(path) ? path : `${absoluteCwd}${P.sep}${path}`;
334
+ const physical = /(?:^|[\\/])\.\.(?:[\\/]|$)/u.test(raw) ? raw : P.resolve(absoluteCwd, path);
335
+ /* v8 ignore next -- Native Windows tests cover DOS drive-relative resolution; POSIX preserves physical traversal. */
336
+ return env.platform === "win32" ? P.resolve(absoluteCwd, path) : physical;
337
+ };
338
+ const resolveTarget = async (cwd, path) => {
339
+ if (path.trim().length === 0) throw fail("FS_NOT_FOUND", "file_path must be a non-empty string");
340
+ const display = displayPath(cwd, path);
341
+ try {
342
+ return {
343
+ display,
344
+ real: await fs.realpath(display)
345
+ };
346
+ } catch (error) {
347
+ /* v8 ignore next -- Windows reports this case as ENOENT and repairs it in the ancestor walk below. */
348
+ if (codeOf(error) === "ENOTDIR") throw fail("FS_NOT_FOUND", `cannot resolve "${display}": a parent path segment is not a directory`);
349
+ if (codeOf(error) !== "ENOENT") throw classify("resolve", display, error);
350
+ }
351
+ const missing = [P.basename(display)];
352
+ for (let ancestor = P.dirname(display);; ancestor = P.dirname(ancestor)) try {
353
+ const real = await fs.realpath(ancestor);
354
+ /* v8 ignore next -- POSIX rejects this traversal; Windows normalizes parent segments before filesystem lookup. */
355
+ if (missing.includes("..")) throw fail("FS_NOT_FOUND", `cannot resolve "${display}": parent traversal crosses a missing directory`);
356
+ /* v8 ignore next 3 -- native Windows coverage exercises this repair. */
357
+ if (env.platform === "win32" && !(await fs.stat(real)).isDirectory()) throw fail("FS_NOT_FOUND", `cannot resolve "${display}": a parent path segment is not a directory`);
358
+ return {
359
+ display,
360
+ real: P.join(real, ...missing)
361
+ };
362
+ } catch (error) {
363
+ /* v8 ignore next -- native Windows coverage exercises the failures raised above. */
364
+ if (coded(error)) throw error;
365
+ /* v8 ignore next -- needs an ancestor realpath fault after the full path reported ENOENT. */
366
+ if (codeOf(error) !== "ENOENT") throw classify("resolve", display, error);
367
+ /* v8 ignore next -- the filesystem root always realpaths, so the walk ends before reaching it. */
368
+ if (P.dirname(ancestor) === ancestor) return {
369
+ display,
370
+ real: display
371
+ };
372
+ missing.unshift(P.basename(ancestor));
373
+ }
374
+ };
375
+ switch (request.op) {
376
+ case "resolve": return result("resolve", await resolveTarget(request.cwd ?? env.cwd, request.path));
377
+ case "stat": {
378
+ const info = await probe(request.path);
379
+ return result("stat", info === null ? null : describe(info));
380
+ }
381
+ case "list": {
382
+ const { path, display } = request;
383
+ checkAborted("list");
384
+ let info;
385
+ try {
386
+ info = await fs.stat(path, { bigint: true });
387
+ } catch (error) {
388
+ if (!absent(error)) throw classify("list", display, error);
389
+ info = null;
390
+ }
391
+ if (info === null) throw fail("FS_NOT_FOUND", `cannot list "${display}": not found`);
392
+ if (!info.isDirectory()) throw fail("FS_NOT_DIRECTORY", `cannot list "${display}": not a directory`);
393
+ let names;
394
+ try {
395
+ names = await fs.readdir(path, { encoding: "utf8" });
396
+ } catch (error) {
397
+ /* v8 ignore next -- needs a permission or kernel failure from readdir after a successful directory stat. */
398
+ throw classify("list", display, error);
399
+ }
400
+ const entries = [];
401
+ let units = 0;
402
+ for (const name of names.sort((left, right) => left.localeCompare(right))) {
403
+ checkAborted("list");
404
+ const { real } = await resolveTarget(path, name);
405
+ const child = await probe(real);
406
+ const entry = {
407
+ name,
408
+ display: displayPath(display, name),
409
+ real,
410
+ info: child === null ? null : describe(child)
411
+ };
412
+ units += entry.name.length + entry.display.length + entry.real.length + 96;
413
+ if (!fits(units)) throw tooLarge("list", display);
414
+ entries.push(entry);
415
+ }
416
+ checkAborted("list");
417
+ return result("list", entries);
418
+ }
419
+ case "lstat": {
420
+ if (request.path.trim().length === 0) throw fail("FS_NOT_FOUND", "file_path must be a non-empty string");
421
+ const info = await probe(displayPath(request.cwd ?? env.cwd, request.path), false);
422
+ return result("lstat", info === null ? null : describe(info));
423
+ }
424
+ case "read": {
425
+ const { path, display } = request;
426
+ const info = await statRegular(path, display);
427
+ if (!fits(Number(info.size))) throw tooLarge("read", display);
428
+ return result("read", decode(await readFile(path, display, "read"), "read", display));
429
+ }
430
+ case "text": {
431
+ const { bytes, tail, offset, final, display } = request;
432
+ const sampled = Math.max(0, Math.min(bytes.length, SAMPLE_BYTES - offset));
433
+ assertBytes(bytes.subarray(0, sampled), "read", display);
434
+ const joined = new Uint8Array(tail.length + bytes.length);
435
+ joined.set(tail);
436
+ joined.set(bytes, tail.length);
437
+ for (let cut = 0; cut <= (final ? 0 : Math.min(3, joined.length)); cut += 1) {
438
+ const rest = joined.slice(joined.length - cut);
439
+ if (cut > 0 && !unfinishedSequence(rest)) continue;
440
+ try {
441
+ return result("text", {
442
+ text: new TextDecoder("utf-8", {
443
+ fatal: true,
444
+ ignoreBOM: offset - tail.length > 0
445
+ }).decode(joined.subarray(0, joined.length - cut)),
446
+ tail: rest
447
+ });
448
+ } catch (_invalidCut) {}
449
+ }
450
+ throw fail("FS_NOT_TEXT", `cannot read "${display}": invalid UTF-8 text`);
451
+ }
452
+ case "bytes": {
453
+ const { path, display, maxBytes } = request;
454
+ const info = await statRegular(path, display);
455
+ if (info.size > maxBytes) throw fail("FS_TOO_LARGE", `cannot read "${display}": ${info.size} bytes exceeds the ${maxBytes}-byte limit`);
456
+ await hooks.inspectReadBytesAfterStat?.(path);
457
+ const chunks = [];
458
+ let total = 0;
459
+ try {
460
+ const handle = await fs.open(path, "r");
461
+ try {
462
+ while (total <= maxBytes) {
463
+ checkAborted("read");
464
+ const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1 - total));
465
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
466
+ if (bytesRead === 0) break;
467
+ chunks.push(chunk.subarray(0, bytesRead));
468
+ total += bytesRead;
469
+ }
470
+ } finally {
471
+ await handle.close();
472
+ }
473
+ } catch (error) {
474
+ throw classify("read", display, error);
475
+ }
476
+ checkAborted("read");
477
+ if (total > maxBytes) throw fail("FS_TOO_LARGE", `cannot read "${display}": content exceeds the ${maxBytes}-byte limit`);
478
+ const content = new Uint8Array(total);
479
+ let at = 0;
480
+ for (const chunk of chunks) {
481
+ content.set(chunk, at);
482
+ at += chunk.length;
483
+ }
484
+ return result("bytes", content);
485
+ }
486
+ case "write": {
487
+ const { path, display, content, expected, basisMaxBytes } = request;
488
+ const existing = await writeTarget(path, display, expected);
489
+ const before = existing !== null && typeof content === "string" && Buffer.byteLength(content, "utf8") < basisMaxBytes ? await basis(path, basisMaxBytes) : null;
490
+ await publish(path, display, content, existing === null ? void 0 : Number(existing.mode & 511n), { createIfAbsent: expected?.kind === "createIfAbsent" });
491
+ return result("write", {
492
+ operation: existing === null ? "create" : "update",
493
+ version: await versionAfter(path),
494
+ before
495
+ });
496
+ }
497
+ case "edit": {
498
+ const { path, display, edit, expected } = request;
499
+ const existing = await requireFile(path, display, "edit", expected);
500
+ if (!fits(Number(existing.size))) throw tooLarge("edit", display);
501
+ const { content: before, crlf } = await readForEdit(path, display);
502
+ const after = literalEdit(before, edit, display);
503
+ if (!fits(before.length + after.length)) throw tooLarge("edit", display);
504
+ await publish(path, display, restore(after, crlf), Number(existing.mode & 511n));
505
+ return result("edit", {
506
+ version: await versionAfter(path),
507
+ before,
508
+ after
509
+ });
510
+ }
511
+ case "load": {
512
+ const { path, display, verb, expected, destination } = request;
513
+ const existing = await requireFile(path, display, verb, expected);
514
+ if (destination !== void 0) await writeTarget(destination.path, destination.display, destination.expected);
515
+ if (!fits(Number(existing.size))) throw tooLarge(verb, display);
516
+ return result("load", {
517
+ ...await readForEdit(path, display),
518
+ version: versionOf(existing)
519
+ });
520
+ }
521
+ case "store": {
522
+ const { path, display, verb, content, crlf, version } = request;
523
+ const existing = await requireFile(path, display, verb, version);
524
+ await publish(path, display, restore(content, crlf), Number(existing.mode & 511n));
525
+ return result("store", { version: await versionAfter(path) });
526
+ }
527
+ case "delete": {
528
+ const { path, display, expected, basisMaxBytes } = request;
529
+ await requireFile(path, display, "delete", expected);
530
+ const before = await basis(path, basisMaxBytes);
531
+ await hooks.inspectBeforeMutation?.(path);
532
+ checkAborted("delete");
533
+ const failure = await remove(path, display);
534
+ if (failure !== null) throw fail(failure.code, failure.message, failure.cause);
535
+ return result("delete", { before });
536
+ }
537
+ case "move": {
538
+ const { source, sourceDisplay, sourceVersion, destination, destinationDisplay, content, crlf, expected, basisMaxBytes } = request;
539
+ if (source === destination) throw fail("FS_SAME_TARGET", `cannot move "${sourceDisplay}" to itself`);
540
+ const sourceInfo = await requireFile(source, sourceDisplay, "move", sourceVersion);
541
+ if (env.sandbox !== void 0 && !await env.sandbox.canWrite(source)) throw fail("FS_SANDBOX_DENIED", `cannot move "${sourceDisplay}": file access denied under ${env.sandbox.mode} mode`);
542
+ const existing = await writeTarget(destination, destinationDisplay, expected);
543
+ const stored = restore(content, crlf);
544
+ const before = existing !== null && Buffer.byteLength(stored, "utf8") < basisMaxBytes ? await basis(destination, basisMaxBytes) : null;
545
+ await hooks.inspectBeforeMutation?.(source);
546
+ checkAborted("move");
547
+ await publish(destination, destinationDisplay, stored, Number(sourceInfo.mode & 511n), {
548
+ createIfAbsent: expected?.kind === "createIfAbsent",
549
+ existingDestination: existing !== null,
550
+ cancellable: false
551
+ });
552
+ const operation = existing === null ? "create" : "update";
553
+ const version = await versionAfter(destination);
554
+ const failure = await remove(source, sourceDisplay);
555
+ return result("move", {
556
+ operation,
557
+ version,
558
+ before,
559
+ sourceFailure: failure === null ? null : {
560
+ code: failure.code,
561
+ message: failure.message
562
+ }
563
+ });
564
+ }
565
+ }
566
+ }
567
+ /**
568
+ * The `FsError` for a failure of {@link fileOperation}; a failure without an `FS_*` code is a defect and is returned
569
+ * unchanged.
570
+ * @param error - the caught value.
571
+ * @returns the typed failure, keeping the original `cause`.
572
+ */
573
+ function fileOperationError(error) {
574
+ if (error instanceof FsError || !(error instanceof Error)) return error;
575
+ const code = FS_ERROR_CODES.find((known) => known === error.code);
576
+ if (code === void 0) return error;
577
+ return new FsError(error.message, code, error.cause === void 0 ? void 0 : { cause: error.cause });
578
+ }
579
+ /**
580
+ * The `FileSystem` operations of one machine. Patch hunks apply in the calling process between a `load` and a
581
+ * `store` (or `move`) guarded by the loaded version, so a file that changes in between fails `FS_STALE_VERSION`.
582
+ * @param run - runs one operation on the machine.
583
+ * @param options - `keyOf` and `pathOf` convert between a realpath and a target key; `cwd` is the default directory of
584
+ * relative paths (undefined: the machine's); `expandPath` rewrites a requested path first; `basisMaxBytes` bounds
585
+ * each diff basis; `maxTextUnits` bounds, in UTF-16 units, the loaded text plus its patched text for a patch or a
586
+ * move with hunks (`FS_TOO_LARGE`), as an execution environment's connection requires.
587
+ * @returns the operations; mutations hold no locks of their own.
588
+ */
589
+ function fileOperations(run, options) {
590
+ const { keyOf, pathOf, basisMaxBytes } = options;
591
+ const expand = options.expandPath ?? ((path) => path);
592
+ const checked = async (verb, signal, operation) => {
593
+ const abort = () => {
594
+ if (signal?.aborted === true) throw new FsError(`${verb} aborted`, "FS_ABORTED");
595
+ };
596
+ abort();
597
+ const result = await operation();
598
+ abort();
599
+ return result;
600
+ };
601
+ const metadata = (info) => ({
602
+ version: FsVersion(info.version),
603
+ type: info.type,
604
+ size: info.size
605
+ });
606
+ const patched = (target, content, hunks) => {
607
+ if (hunks === void 0) return content;
608
+ const result = applyHunks(content, hunks);
609
+ if (!result.ok) throw new FsError(`cannot patch "${target.displayPath}": hunk at patch line ${result.failure.hunkLineNumber} (${result.failure.stage}) does not match`, "FS_PATCH_MISMATCH");
610
+ if (options.maxTextUnits !== void 0 && content.length + result.after.length > options.maxTextUnits) throw new FsError(`cannot patch "${target.displayPath}": larger than the environment connection carries`, "FS_TOO_LARGE");
611
+ return result.after;
612
+ };
613
+ const bounded = (text) => Buffer.byteLength(text, "utf8") < basisMaxBytes ? text : null;
614
+ const cwdOf = (cwd) => cwd ?? options.cwd;
615
+ return {
616
+ async resolve(path, opts) {
617
+ const { display, real } = await checked("resolve", opts?.signal, () => run({
618
+ op: "resolve",
619
+ path: expand(path),
620
+ cwd: cwdOf(opts?.cwd)
621
+ }, opts?.signal));
622
+ return {
623
+ targetKey: FsTargetKey(keyOf(real)),
624
+ displayPath: display
625
+ };
626
+ },
627
+ processPath: pathOf,
628
+ async stat(target, signal) {
629
+ const info = await checked("stat", signal, () => run({
630
+ op: "stat",
631
+ path: pathOf(target)
632
+ }, signal));
633
+ return info === null ? void 0 : {
634
+ ...metadata(info),
635
+ type: info.type
636
+ };
637
+ },
638
+ async lstat(path, opts, signal) {
639
+ const info = await checked("lstat", signal, () => run({
640
+ op: "lstat",
641
+ path: expand(path),
642
+ cwd: cwdOf(opts?.cwd)
643
+ }, signal));
644
+ return info === null ? void 0 : metadata(info);
645
+ },
646
+ readText: (target, signal) => run({
647
+ op: "read",
648
+ path: pathOf(target),
649
+ display: target.displayPath
650
+ }, signal),
651
+ readBytes: (target, signal, maxBytes) => run({
652
+ op: "bytes",
653
+ path: pathOf(target),
654
+ display: target.displayPath,
655
+ maxBytes
656
+ }, signal),
657
+ async listDir(target, signal) {
658
+ return (await run({
659
+ op: "list",
660
+ path: pathOf(target),
661
+ display: target.displayPath
662
+ }, signal)).map(({ name, display, real, info }) => ({
663
+ name,
664
+ type: info?.type ?? "other",
665
+ target: {
666
+ targetKey: FsTargetKey(keyOf(real)),
667
+ displayPath: display
668
+ },
669
+ ...info === null ? {} : { version: FsVersion(info.version) },
670
+ ...info?.type === "file" ? { size: info.size } : {}
671
+ }));
672
+ },
673
+ async writeText(target, content, expected, signal) {
674
+ const outcome = await run({
675
+ op: "write",
676
+ path: pathOf(target),
677
+ display: target.displayPath,
678
+ content,
679
+ expected,
680
+ basisMaxBytes
681
+ }, signal);
682
+ return {
683
+ ...outcome,
684
+ version: FsVersion(outcome.version),
685
+ after: content.replaceAll("\r\n", "\n")
686
+ };
687
+ },
688
+ async writeBytes(target, data, expected, signal) {
689
+ const outcome = await run({
690
+ op: "write",
691
+ path: pathOf(target),
692
+ display: target.displayPath,
693
+ content: data,
694
+ expected,
695
+ basisMaxBytes: 0
696
+ }, signal);
697
+ return {
698
+ operation: outcome.operation,
699
+ version: FsVersion(outcome.version)
700
+ };
701
+ },
702
+ async editText(target, edit, expected, signal) {
703
+ const outcome = await run({
704
+ op: "edit",
705
+ path: pathOf(target),
706
+ display: target.displayPath,
707
+ edit,
708
+ expected: expected?.version
709
+ }, signal);
710
+ return {
711
+ ...outcome,
712
+ version: FsVersion(outcome.version)
713
+ };
714
+ },
715
+ async patchText(target, hunks, expected, signal) {
716
+ const loaded = await run({
717
+ op: "load",
718
+ path: pathOf(target),
719
+ display: target.displayPath,
720
+ verb: "patch",
721
+ expected: expected?.version
722
+ }, signal);
723
+ const after = patched(target, loaded.content, hunks);
724
+ return {
725
+ version: FsVersion((await run({
726
+ op: "store",
727
+ path: pathOf(target),
728
+ display: target.displayPath,
729
+ verb: "patch",
730
+ content: after,
731
+ crlf: loaded.crlf,
732
+ version: loaded.version
733
+ }, signal)).version),
734
+ before: loaded.content,
735
+ after
736
+ };
737
+ },
738
+ deleteFile: (target, expected, signal) => run({
739
+ op: "delete",
740
+ path: pathOf(target),
741
+ display: target.displayPath,
742
+ expected: expected?.version,
743
+ basisMaxBytes
744
+ }, signal),
745
+ async moveFile(source, destination, moveOptions, signal) {
746
+ if (source.targetKey === destination.targetKey) throw new FsError(`cannot move "${source.displayPath}" to itself`, "FS_SAME_TARGET");
747
+ const loaded = await run({
748
+ op: "load",
749
+ path: pathOf(source),
750
+ display: source.displayPath,
751
+ verb: "move",
752
+ expected: moveOptions.expectedSource?.version,
753
+ destination: {
754
+ path: pathOf(destination),
755
+ display: destination.displayPath,
756
+ expected: moveOptions.expectedDestination
757
+ }
758
+ }, signal);
759
+ const after = patched(source, loaded.content, moveOptions.hunks);
760
+ const moved = await run({
761
+ op: "move",
762
+ source: pathOf(source),
763
+ sourceDisplay: source.displayPath,
764
+ sourceVersion: loaded.version,
765
+ destination: pathOf(destination),
766
+ destinationDisplay: destination.displayPath,
767
+ content: after,
768
+ crlf: loaded.crlf,
769
+ expected: moveOptions.expectedDestination,
770
+ basisMaxBytes
771
+ }, signal);
772
+ const outcome = {
773
+ operation: moved.operation,
774
+ version: FsVersion(moved.version),
775
+ before: moved.before,
776
+ after
777
+ };
778
+ const sourceBefore = bounded(loaded.content);
779
+ if (moved.sourceFailure === null) return {
780
+ sourceBefore,
781
+ destination: outcome,
782
+ sourceDeleted: true
783
+ };
784
+ return {
785
+ sourceBefore,
786
+ destination: outcome,
787
+ sourceDeleted: false,
788
+ sourceFailure: moved.sourceFailure
789
+ };
790
+ }
791
+ };
792
+ }
793
+ //#endregion
794
+ export { fileOperation, fileOperationError, fileOperations };