@fnndsc/fond 0.6.2 → 0.7.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 (44) hide show
  1. package/README.md +1 -3
  2. package/dist/errorStack.d.ts +0 -6
  3. package/dist/errorStack.js +0 -9
  4. package/dist/errorStack.js.map +1 -1
  5. package/dist/heldWriter.d.ts +130 -0
  6. package/dist/heldWriter.js +539 -0
  7. package/dist/heldWriter.js.map +1 -0
  8. package/dist/homePath.d.ts +60 -0
  9. package/dist/homePath.js +117 -0
  10. package/dist/homePath.js.map +1 -0
  11. package/dist/hostPlace.d.ts +275 -0
  12. package/dist/hostPlace.js +777 -0
  13. package/dist/hostPlace.js.map +1 -0
  14. package/dist/index.d.ts +6 -0
  15. package/dist/index.js +24 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/placedPath.d.ts +250 -0
  18. package/dist/placedPath.js +757 -0
  19. package/dist/placedPath.js.map +1 -0
  20. package/dist/publication.d.ts +43 -0
  21. package/dist/publication.js +55 -0
  22. package/dist/publication.js.map +1 -0
  23. package/dist/recordFile.d.ts +61 -0
  24. package/dist/recordFile.js +258 -0
  25. package/dist/recordFile.js.map +1 -0
  26. package/dist/vfs/contract.js +19 -5
  27. package/dist/vfs/contract.js.map +1 -1
  28. package/dist/vfs/dispatcher.d.ts +222 -13
  29. package/dist/vfs/dispatcher.js +483 -73
  30. package/dist/vfs/dispatcher.js.map +1 -1
  31. package/dist/vfs/memory.d.ts +107 -3
  32. package/dist/vfs/memory.js +198 -24
  33. package/dist/vfs/memory.js.map +1 -1
  34. package/dist/vfs/naming.d.ts +97 -0
  35. package/dist/vfs/naming.js +122 -0
  36. package/dist/vfs/naming.js.map +1 -0
  37. package/dist/vfs/outcome.d.ts +72 -2
  38. package/dist/vfs/outcome.js +84 -3
  39. package/dist/vfs/outcome.js.map +1 -1
  40. package/dist/vfs/provider.d.ts +191 -6
  41. package/dist/vfs/render.d.ts +7 -0
  42. package/dist/vfs/render.js +16 -13
  43. package/dist/vfs/render.js.map +1 -1
  44. package/package.json +1 -1
@@ -0,0 +1,757 @@
1
+ "use strict";
2
+ /**
3
+ * @file Places on this machine for what arrives from elsewhere, and the one writer that puts bytes there.
4
+ *
5
+ * A download names its files by what CUBE (or a session) says. Every such name is placed under a folder the
6
+ * operator chose, and only fond can say a path was placed: a `PlacedPath` is a frozen token whose facts live in a
7
+ * map only this module holds, so a cast, an `any`, a copied or changed object is refused by every writer here.
8
+ *
9
+ * Two origins, and only two:
10
+ * - `operatorFolder_place` / `operatorFile_place`: the destination the operator typed (or authorized), kept as
11
+ * they said it. Its root is recorded by identity (device and inode) and by its real spelling.
12
+ * - `placed_child`: a name that arrived, placed under a token already made, so every place chains to the
13
+ * operator's root.
14
+ *
15
+ * The writer never opens the final name for writing. It writes a fresh owner-only temporary file beside it,
16
+ * proves after opening that the temporary file is where it should be (inside the operator's root, the same file
17
+ * the handle holds), streams, syncs, sets the final mode through the handle, and renames over the name. The
18
+ * rename is the commit point: before it the prior file is untouched; after it a failed check is reported, never
19
+ * repaired by path.
20
+ *
21
+ * Guarantee: an existing file outside the operator's root is never opened for writing. On Linux with a real
22
+ * procfs (heldWriter.ts) every create, rename and cleanup is made relative to folders held as descriptors, so a
23
+ * folder swapped for a link never takes a byte outside, and a held folder moved out of the root is refused
24
+ * before the commit and reported as unconfirmed after it; the temporary file's inode is pinned until its
25
+ * publication is proved. Elsewhere (macOS, a hardened /proc) the pathname writer here is used: every create,
26
+ * rename and cleanup stays inside the root while no other local process changes folders inside it during the
27
+ * write, and a process that does can leave a temporary file or an empty folder outside, which is said.
28
+ *
29
+ * Key components:
30
+ * - PlacedPath, operatorFolder_place, operatorFile_place, placed_child: the places.
31
+ * - placedFolder_make, placedFile_write: the only makers.
32
+ * - placedCapabilities_set: what the platform offers (a test's seam).
33
+ *
34
+ * Typical usage:
35
+ * ```ts
36
+ * const root: Placing = operatorFolder_place('./out', true);
37
+ * const file: Placing = root.ok ? placed_child(root.placed, 'anat/t1.nii') : root;
38
+ * if (file.ok) await placedFile_write(file.placed, stream, { mode: 0o600 });
39
+ * ```
40
+ *
41
+ * Dependencies: Node's fs, path, crypto, child_process (macOS ACL reading).
42
+ *
43
+ * @module
44
+ */
45
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
46
+ if (k2 === undefined) k2 = k;
47
+ var desc = Object.getOwnPropertyDescriptor(m, k);
48
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
49
+ desc = { enumerable: true, get: function() { return m[k]; } };
50
+ }
51
+ Object.defineProperty(o, k2, desc);
52
+ }) : (function(o, m, k, k2) {
53
+ if (k2 === undefined) k2 = k;
54
+ o[k2] = m[k];
55
+ }));
56
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
57
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
58
+ }) : function(o, v) {
59
+ o["default"] = v;
60
+ });
61
+ var __importStar = (this && this.__importStar) || (function () {
62
+ var ownKeys = function(o) {
63
+ ownKeys = Object.getOwnPropertyNames || function (o) {
64
+ var ar = [];
65
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
66
+ return ar;
67
+ };
68
+ return ownKeys(o);
69
+ };
70
+ return function (mod) {
71
+ if (mod && mod.__esModule) return mod;
72
+ var result = {};
73
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
74
+ __setModuleDefault(result, mod);
75
+ return result;
76
+ };
77
+ })();
78
+ Object.defineProperty(exports, "__esModule", { value: true });
79
+ exports.PART_PREFIX = void 0;
80
+ exports.placedCapabilities_set = placedCapabilities_set;
81
+ exports.aclListing_inheritableAllow = aclListing_inheritableAllow;
82
+ exports.operatorFolder_place = operatorFolder_place;
83
+ exports.operatorFile_place = operatorFile_place;
84
+ exports.placed_child = placed_child;
85
+ exports.placed_parent = placed_parent;
86
+ exports.placedFolder_make = placedFolder_make;
87
+ exports.placedFile_write = placedFile_write;
88
+ exports.localPath_kind = localPath_kind;
89
+ const node_child_process_1 = require("node:child_process");
90
+ const node_crypto_1 = require("node:crypto");
91
+ const node_fs_1 = require("node:fs");
92
+ const promises_1 = require("node:fs/promises");
93
+ const path = __importStar(require("node:path"));
94
+ const node_stream_1 = require("node:stream");
95
+ const heldWriter_js_1 = require("./heldWriter.js");
96
+ const hostPlace_js_1 = require("./hostPlace.js");
97
+ const publication_js_1 = require("./publication.js");
98
+ /** The records of every token fond has made. */
99
+ const RECORDS = new WeakMap();
100
+ /** Names a temporary file of the writer starts with; refused when they arrive from elsewhere. */
101
+ exports.PART_PREFIX = '.mise-part-';
102
+ /** The capabilities in use. */
103
+ let capabilities = {
104
+ noFollow: typeof node_fs_1.constants.O_NOFOLLOW === 'number',
105
+ platform: process.platform,
106
+ inheritableAllow_read: (folder) => process.platform === 'darwin' && macAcl_inheritableAllow(folder),
107
+ held: (0, heldWriter_js_1.heldFolders_available)(),
108
+ };
109
+ /**
110
+ * Replaces what the platform is taken to offer (a test's seam), returning the restore.
111
+ *
112
+ * @param given - The capabilities to use.
113
+ * @returns The call that restores the previous ones.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const restore = placedCapabilities_set({ noFollow: false });
118
+ * ```
119
+ */
120
+ function placedCapabilities_set(given) {
121
+ const previous = capabilities;
122
+ capabilities = { ...capabilities, ...given };
123
+ return () => { capabilities = previous; };
124
+ }
125
+ /**
126
+ * Whether a macOS folder holds an inheritable allow entry (one a new file there would get), read from `ls -lde`.
127
+ *
128
+ * @param folder - The folder.
129
+ * @returns True when it does (or when it could not be read: then owner-only cannot be established).
130
+ */
131
+ function macAcl_inheritableAllow(folder) {
132
+ const listing = (0, node_child_process_1.spawnSync)('/bin/ls', ['-lde', folder], { encoding: 'utf8' });
133
+ if (listing.status !== 0)
134
+ return true;
135
+ return aclListing_inheritableAllow(listing.stdout);
136
+ }
137
+ /**
138
+ * Whether macOS's `ls -lde` listing of a folder shows an inheritable allow entry: an ACE line (`N: who allow
139
+ * rights`) whose rights include file_inherit or directory_inherit.
140
+ *
141
+ * @param listing - What `ls -lde` printed.
142
+ * @returns True when one is there.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * aclListing_inheritableAllow(' 0: user:bob allow read,file_inherit'); // true
147
+ * ```
148
+ */
149
+ function aclListing_inheritableAllow(listing) {
150
+ return listing.split('\n').some((line) => /^\s*\d+:/.test(line) && /\ballow\b/.test(line) && /\b(file_inherit|directory_inherit)\b/.test(line));
151
+ }
152
+ /**
153
+ * Mints a token for a record.
154
+ *
155
+ * @param record - What it means.
156
+ * @returns The token.
157
+ */
158
+ function token_mint(record) {
159
+ const token = Object.freeze({ place: path.join(record.root.real, ...record.parts) });
160
+ RECORDS.set(token, record);
161
+ return token;
162
+ }
163
+ /**
164
+ * The record of a token fond made, or the refusal of anything else.
165
+ *
166
+ * @param token - What was given.
167
+ * @returns Its record.
168
+ * @throws {Error} When fond did not make it.
169
+ */
170
+ function record_read(token) {
171
+ // (A primitive or a lookalike is simply not in the map.)
172
+ const record = RECORDS.get(token);
173
+ if (record === undefined)
174
+ throw new Error('refused: not a place fond made; nothing was written');
175
+ return record;
176
+ }
177
+ /**
178
+ * The code of a filesystem error.
179
+ *
180
+ * @param error - The error.
181
+ * @returns Its code, or EIO.
182
+ */
183
+ function code_read(error) {
184
+ return error?.code ?? 'EIO';
185
+ }
186
+ /**
187
+ * A folder that stands, by real path and identity, or why not.
188
+ *
189
+ * @param folder - The folder.
190
+ * @returns Its root record, or the reason.
191
+ */
192
+ function folder_hold(folder) {
193
+ try {
194
+ const real = node_fs_1.realpathSync.native(folder);
195
+ const stood = (0, node_fs_1.statSync)(real, { bigint: true });
196
+ if (!stood.isDirectory())
197
+ return `${JSON.stringify(folder)} is not a folder`;
198
+ return { real, dev: stood.dev, ino: stood.ino };
199
+ }
200
+ catch (error) {
201
+ return `${JSON.stringify(folder)} could not be looked at (${code_read(error)})`;
202
+ }
203
+ }
204
+ /**
205
+ * Proves the operator's root is still the folder it was: the same identity at the same real spelling.
206
+ *
207
+ * @param root - The root.
208
+ * @throws {Error} When it is not.
209
+ */
210
+ function root_prove(root) {
211
+ let real;
212
+ let stood;
213
+ try {
214
+ real = node_fs_1.realpathSync.native(root.real);
215
+ stood = (0, node_fs_1.statSync)(root.real, { bigint: true });
216
+ }
217
+ catch (error) {
218
+ throw new Error(`refused: the destination ${JSON.stringify(root.real)} could not be looked at (${code_read(error)}); nothing was written`);
219
+ }
220
+ if (real !== root.real || stood.dev !== root.dev || stood.ino !== root.ino)
221
+ throw new Error(`refused: the destination ${JSON.stringify(root.real)} is no longer the folder it was; nothing was written`);
222
+ }
223
+ /**
224
+ * Proves a folder under the root is a real folder at exactly its place (no link on the way).
225
+ *
226
+ * @param root - The root.
227
+ * @param folder - The folder's expected real path.
228
+ * @throws {Error} When it is not.
229
+ */
230
+ function folder_prove(root, folder) {
231
+ root_prove(root);
232
+ let real;
233
+ let stood;
234
+ try {
235
+ stood = (0, node_fs_1.lstatSync)(folder);
236
+ real = node_fs_1.realpathSync.native(folder);
237
+ }
238
+ catch (error) {
239
+ throw new Error(`refused: ${JSON.stringify(folder)} could not be looked at (${code_read(error)}); nothing was written`);
240
+ }
241
+ if (!stood.isDirectory() || stood.isSymbolicLink() || real !== folder)
242
+ throw new Error(`refused: ${JSON.stringify(folder)} is not a folder of its own inside the destination; nothing was written`);
243
+ }
244
+ /**
245
+ * The nearest folder that stands on the way to a path, and the operator's own parts below it that do not yet
246
+ * (made later, each proved, by the writer's folder maker): nothing is created here.
247
+ *
248
+ * @param target - The path the operator named, absolute.
249
+ * @returns The held folder and the missing parts, or the reason.
250
+ */
251
+ function operatorAnchor_hold(target) {
252
+ const missing = [];
253
+ let existing = target;
254
+ for (;;) {
255
+ try {
256
+ (0, node_fs_1.lstatSync)(existing);
257
+ break;
258
+ }
259
+ catch (error) {
260
+ if (code_read(error) !== 'ENOENT')
261
+ return `${JSON.stringify(existing)} could not be looked at (${code_read(error)})`;
262
+ const parent = path.dirname(existing);
263
+ if (parent === existing)
264
+ return `nothing of ${JSON.stringify(target)} exists`;
265
+ missing.unshift(path.basename(existing));
266
+ existing = parent;
267
+ }
268
+ }
269
+ for (const part of missing) {
270
+ const judged = (0, hostPlace_js_1.namePart_judge)(part, capabilities.platform);
271
+ if (judged !== null)
272
+ return `${JSON.stringify(part)} ${judged}`;
273
+ }
274
+ const root = folder_hold(existing);
275
+ return typeof root === 'string' ? root : { root, missing };
276
+ }
277
+ /**
278
+ * Places the folder the operator named as a download's destination. Its nearest standing folder is held by
279
+ * identity and real spelling as the root every name under it chains to; when `create` allows, the operator's
280
+ * missing folders are part of the place, made later (each proved) by `placedFolder_make` or the writer. Nothing is
281
+ * created here.
282
+ *
283
+ * @param operand - The destination as the operator typed it.
284
+ * @param create - Whether a missing folder (and missing parents) may be part of the place.
285
+ * @returns The folder's token, or why not.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * const placing: Placing = operatorFolder_place('./out', true);
290
+ * ```
291
+ */
292
+ function operatorFolder_place(operand, create) {
293
+ const target = path.resolve(operand);
294
+ if (!create) {
295
+ const held = folder_hold(target);
296
+ if (typeof held === 'string')
297
+ return { ok: false, reason: `refused: ${held}; nothing was written` };
298
+ return { ok: true, placed: token_mint({ root: held, parts: [] }) };
299
+ }
300
+ const anchored = operatorAnchor_hold(target);
301
+ if (typeof anchored === 'string')
302
+ return { ok: false, reason: `refused: ${anchored}; nothing was written` };
303
+ if (anchored.missing.length === 0 && !(0, node_fs_1.statSync)(anchored.root.real).isDirectory())
304
+ return { ok: false, reason: `refused: ${JSON.stringify(target)} is not a folder; nothing was written` };
305
+ return { ok: true, placed: token_mint({ root: anchored.root, parts: anchored.missing }) };
306
+ }
307
+ /**
308
+ * Places the file the operator named exactly (`download x ./notes.txt`): its folder (made when missing) is the
309
+ * root, and the file keeps the operator's own name.
310
+ *
311
+ * @param operand - The file as the operator typed it.
312
+ * @returns The file's token, or why not.
313
+ *
314
+ * @example
315
+ * ```ts
316
+ * const placing: Placing = operatorFile_place('./notes.txt');
317
+ * ```
318
+ */
319
+ function operatorFile_place(operand) {
320
+ const target = path.resolve(operand);
321
+ const name = path.basename(target);
322
+ const judged = (0, hostPlace_js_1.namePart_judge)(name, capabilities.platform);
323
+ if (judged !== null)
324
+ return { ok: false, reason: `refused: the destination ${JSON.stringify(name)} ${judged}; nothing was written` };
325
+ const folder = operatorFolder_place(path.dirname(target), true);
326
+ if (!folder.ok)
327
+ return folder;
328
+ const record = record_read(folder.placed);
329
+ return { ok: true, placed: token_mint({ root: record.root, parts: [...record.parts, name] }) };
330
+ }
331
+ /**
332
+ * Places a name that arrived (a CUBE row's name inside the folder downloaded, a delivery's filename) under a place
333
+ * fond made: each part a plain name for this platform, never a writer's temporary name, never leaving the root
334
+ * by a link that stands on its way.
335
+ *
336
+ * @param parent - Where it goes.
337
+ * @param name - The name as it arrived, `/`-separated.
338
+ * @returns Its token, or why not.
339
+ *
340
+ * @example
341
+ * ```ts
342
+ * const child: Placing = placed_child(folder, 'anat/t1.nii');
343
+ * ```
344
+ */
345
+ function placed_child(parent, name) {
346
+ const record = record_read(parent);
347
+ const shown = JSON.stringify(name);
348
+ if (name.length === 0)
349
+ return { ok: false, reason: 'refused: an empty name' };
350
+ if (path.posix.isAbsolute(name))
351
+ return { ok: false, reason: `refused: ${shown} is an absolute path, not a name` };
352
+ // Parts are split at `/` only: a `\\` inside a ChRIS name is part of that name on POSIX, never a folder, and refused
353
+ // on Windows, where it would be one.
354
+ const parts = name.split('/');
355
+ const judged = arrivedParts_judge(shown, parts);
356
+ if (judged !== null)
357
+ return { ok: false, reason: judged };
358
+ const all = [...record.parts, ...parts];
359
+ const stood = arrivedWay_judge(shown, record.root.real, all);
360
+ if (stood !== null)
361
+ return { ok: false, reason: stood };
362
+ return { ok: true, placed: token_mint({ root: record.root, parts: all }) };
363
+ }
364
+ /**
365
+ * Why the parts of a name that arrived are not each a plain name for this platform (on Windows a `\\` is a folder
366
+ * there, so refused), or one fond keeps for a writer's temporary file; the first part refused says it.
367
+ *
368
+ * @param shown - The name as it is quoted to the operator.
369
+ * @param parts - Its `/`-separated parts, in order.
370
+ * @returns Null when every part is plain, else the refusal.
371
+ */
372
+ function arrivedParts_judge(shown, parts) {
373
+ for (const part of parts) {
374
+ if (capabilities.platform === 'win32' && part.includes('\\'))
375
+ return `refused: ${shown} has a \\, which this machine reads as a folder`;
376
+ const judged = (0, hostPlace_js_1.namePart_judge)(part, capabilities.platform);
377
+ if (judged !== null)
378
+ return `refused: ${shown} ${judged}`;
379
+ if (part.startsWith(exports.PART_PREFIX))
380
+ return `refused: ${shown}: a name this machine keeps for its own unfinished files`;
381
+ }
382
+ return null;
383
+ }
384
+ /**
385
+ * Why what stands of a placed name's way is not folders of their own: each part before the last that is there must
386
+ * be a folder and not a link (the last may be anything); the first part not there ends the look, and a part that
387
+ * could not be looked at refuses.
388
+ *
389
+ * @param shown - The name as it is quoted to the operator.
390
+ * @param real - The real path of the root the parts are under.
391
+ * @param all - Every part from the root, in order.
392
+ * @returns Null when the way may be taken, else the refusal.
393
+ */
394
+ function arrivedWay_judge(shown, real, all) {
395
+ let current = real;
396
+ for (const [at, part] of all.entries()) {
397
+ current = path.join(current, part);
398
+ let stood;
399
+ try {
400
+ stood = (0, node_fs_1.lstatSync)(current);
401
+ }
402
+ catch (error) {
403
+ if (code_read(error) === 'ENOENT')
404
+ break;
405
+ return `refused: ${shown} passes through a place that could not be looked at (${code_read(error)})`;
406
+ }
407
+ const last = at === all.length - 1;
408
+ if (!last && (stood.isSymbolicLink() || !stood.isDirectory()))
409
+ return `refused: ${shown} passes through ${JSON.stringify(current)}, which is not a folder of its own`;
410
+ }
411
+ return null;
412
+ }
413
+ /**
414
+ * The folder a placed file or folder is in, as a place (null for the operator's root itself).
415
+ *
416
+ * @param placed - The place.
417
+ * @returns Its folder's token, or null.
418
+ *
419
+ * @example
420
+ * ```ts
421
+ * const folder: PlacedPath | null = placed_parent(file);
422
+ * ```
423
+ */
424
+ function placed_parent(placed) {
425
+ const record = record_read(placed);
426
+ if (record.parts.length === 0)
427
+ return null;
428
+ return token_mint({ root: record.root, parts: record.parts.slice(0, -1) });
429
+ }
430
+ /**
431
+ * Makes a placed folder: each missing part from the root down, owner-only, each proved after it is made (a folder
432
+ * of its own at exactly its place, the root unchanged); a part made and then not proved is removed again.
433
+ *
434
+ * @param placed - The folder's token.
435
+ * @throws {Error} When a part cannot be made or proved.
436
+ *
437
+ * @example
438
+ * ```ts
439
+ * placedFolder_make(child.placed);
440
+ * ```
441
+ */
442
+ function placedFolder_make(placed) {
443
+ const record = record_read(placed);
444
+ if (capabilities.held) {
445
+ (0, heldWriter_js_1.heldFolder_make)(record.root, record.parts, { root_prove: () => { root_prove(record.root); } });
446
+ return;
447
+ }
448
+ root_prove(record.root);
449
+ let current = record.root.real;
450
+ for (const part of record.parts) {
451
+ current = path.join(current, part);
452
+ let made = null;
453
+ try {
454
+ (0, node_fs_1.mkdirSync)(current, { mode: 0o700 });
455
+ made = (0, node_fs_1.lstatSync)(current);
456
+ }
457
+ catch (error) {
458
+ if (code_read(error) !== 'EEXIST')
459
+ throw new Error(`refused: ${JSON.stringify(current)} could not be made (${code_read(error)}); nothing was written`);
460
+ }
461
+ try {
462
+ folder_prove(record.root, current);
463
+ }
464
+ catch (error) {
465
+ if (made !== null)
466
+ madeFolder_remove(current, made);
467
+ throw error;
468
+ }
469
+ }
470
+ }
471
+ /**
472
+ * Removes a folder this writer made, only when the name still holds that folder.
473
+ *
474
+ * @param folder - Its place.
475
+ * @param made - What was made there.
476
+ */
477
+ function madeFolder_remove(folder, made) {
478
+ try {
479
+ const now = (0, node_fs_1.lstatSync)(folder);
480
+ if (now.dev === made.dev && now.ino === made.ino)
481
+ (0, node_fs_1.rmdirSync)(folder);
482
+ }
483
+ catch {
484
+ // Gone, or not ours: left as it is.
485
+ }
486
+ }
487
+ /**
488
+ * Writes a placed file from a stream: a fresh owner-only temporary file beside it, proved, filled, synced, given
489
+ * its final mode through the handle, then renamed over the name (the commit point). Refused before any byte where
490
+ * the platform cannot refuse a link at the name, where a macOS folder would give the file inherited access, or
491
+ * where an existing file at the name may not be written by this account; a folder or a special file at the name is
492
+ * refused. Before the rename a failure or cancel leaves the prior file and no temporary file of this attempt;
493
+ * after it a failed check is reported as publication unconfirmed.
494
+ *
495
+ * @param placed - The file's token.
496
+ * @param given - The bytes: a stream, or the bytes whole.
497
+ * @param how - The final mode, the signal, the byte counter.
498
+ * @returns The bytes written.
499
+ * @throws {Error} When refused, or when the write failed.
500
+ *
501
+ * @example
502
+ * ```ts
503
+ * await placedFile_write(child.placed, stream, { mode: 0o600, signal });
504
+ * ```
505
+ */
506
+ async function placedFile_write(placed, given, how) {
507
+ // Bytes whole (a projection, a pipeline) are written as one chunk.
508
+ const source = given instanceof Uint8Array ? node_stream_1.Readable.from([given]) : given;
509
+ const record = record_read(placed);
510
+ const mode = write_admit(record, how);
511
+ const folder = path.join(record.root.real, ...record.parts.slice(0, -1));
512
+ const target = path.join(folder, record.parts[record.parts.length - 1] ?? '');
513
+ folder_prove(record.root, folder);
514
+ if (capabilities.inheritableAllow_read(folder))
515
+ throw new Error(`refused: ${JSON.stringify(folder)} gives files made in it access for others (an inherited ACL entry), so this file could not be kept to its owner; nothing was written`);
516
+ if (capabilities.held)
517
+ return heldBackend_write(record, source, how, mode);
518
+ standing_judge(target);
519
+ const temporary = path.join(folder, `${exports.PART_PREFIX}${(0, node_crypto_1.randomBytes)(8).toString('hex')}`);
520
+ const handle = await (0, promises_1.open)(temporary, node_fs_1.constants.O_WRONLY | node_fs_1.constants.O_CREAT | node_fs_1.constants.O_EXCL | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK, 0o600);
521
+ let held = null;
522
+ let published = false;
523
+ let open = true;
524
+ const handle_close = async () => {
525
+ if (!open)
526
+ return;
527
+ open = false;
528
+ await handle.close();
529
+ };
530
+ try {
531
+ held = await handle.stat();
532
+ temporary_prove(record.root, folder, temporary, held);
533
+ const written = await stream_writeThrough(source, handle, how);
534
+ await handle.sync();
535
+ await handle.chmod(mode);
536
+ // Closed before the commit: nothing of the write itself can fail once it is published.
537
+ await handle_close();
538
+ // The last moment before the commit: a cancel since, or a changed place, publishes nothing.
539
+ if (how.signal?.aborted === true)
540
+ throw new Error('cancelled: the write was stopped before it was published');
541
+ temporary_prove(record.root, folder, temporary, held);
542
+ standing_judge(target);
543
+ (0, node_fs_1.renameSync)(temporary, target);
544
+ published = true;
545
+ publication_prove(record.root, folder, target, held);
546
+ return written;
547
+ }
548
+ catch (error) {
549
+ if (published)
550
+ throw error;
551
+ await handle_close().catch(() => {
552
+ // The write failed already; a failed close of its temporary adds nothing to say.
553
+ });
554
+ const cleanup = held === null ? 'the file being written could not be looked at' : madeFile_remove(record.root, folder, temporary, held);
555
+ if (cleanup === null)
556
+ throw error;
557
+ throw new Error(`${error instanceof Error ? error.message : String(error)}; and ${cleanup}`);
558
+ }
559
+ }
560
+ /**
561
+ * What every write must be before anything is opened: one of the two owner-only modes (whatever a caller
562
+ * passes), a platform that can refuse a link at the name, a file (not the root folder), and a name that is not
563
+ * one the writer keeps for its unfinished files.
564
+ *
565
+ * @param record - The place.
566
+ * @param how - The write.
567
+ * @returns The mode, checked once and used from here on.
568
+ * @throws {Error} When any is not so (nothing written).
569
+ */
570
+ function write_admit(record, how) {
571
+ const mode = how.mode;
572
+ if (mode !== 0o600 && mode !== 0o400)
573
+ throw new Error('refused: a downloaded file is written 0600 or 0400 only; nothing was written');
574
+ if (!capabilities.noFollow)
575
+ throw new Error('refused: this platform cannot refuse a link where a file is written; nothing was written');
576
+ if (record.parts.length === 0)
577
+ throw new Error('refused: a folder is not a file to write; nothing was written');
578
+ // Whatever the origin (an operator's own filename too): such a name could be the writer's own temporary file.
579
+ if ((record.parts[record.parts.length - 1] ?? '').startsWith(exports.PART_PREFIX))
580
+ throw new Error(`refused: ${JSON.stringify(record.parts[record.parts.length - 1])} is a name this machine keeps for its own unfinished files; nothing was written`);
581
+ return mode;
582
+ }
583
+ /**
584
+ * Writes through held folders (heldWriter.ts), with this module's checks handed in.
585
+ *
586
+ * @param record - The place.
587
+ * @param source - The bytes.
588
+ * @param how - The signal and the byte counter.
589
+ * @param mode - The final mode, already checked.
590
+ * @returns The bytes written.
591
+ */
592
+ function heldBackend_write(record, source, how, mode) {
593
+ return (0, heldWriter_js_1.heldFile_write)(record.root, record.parts, mode, {
594
+ root_prove: () => { root_prove(record.root); },
595
+ standing_judge: (target, shown) => { standing_judge(target, shown); },
596
+ stream_write: (handle) => stream_writeThrough(source, handle, how),
597
+ unconfirmed_make: (message) => new publication_js_1.UnconfirmedPublication(message),
598
+ temporary: `${exports.PART_PREFIX}${(0, node_crypto_1.randomBytes)(8).toString('hex')}`,
599
+ cancel_read: () => how.signal?.aborted === true,
600
+ });
601
+ }
602
+ /**
603
+ * Proves a publication after the rename: the root unchanged, the folder its own, and the name holding the file just
604
+ * written. Anything else is reported as unconfirmed; the name is left as it is (nothing removed by path).
605
+ *
606
+ * @param root - The root.
607
+ * @param folder - The file's folder.
608
+ * @param target - Its name.
609
+ * @param held - What was written.
610
+ * @throws {Error} When the publication cannot be confirmed.
611
+ */
612
+ function publication_prove(root, folder, target, held) {
613
+ try {
614
+ folder_prove(root, folder);
615
+ const now = (0, node_fs_1.lstatSync)(target);
616
+ if (now.dev !== held.dev || now.ino !== held.ino)
617
+ throw new Error('the name holds another file');
618
+ }
619
+ catch (error) {
620
+ // A distinct outcome: the write was published, so a caller must not write it again.
621
+ throw new publication_js_1.UnconfirmedPublication(`publication unconfirmed: ${JSON.stringify(target)}: ${error instanceof Error ? error.message : String(error)}; it was left as it is`);
622
+ }
623
+ }
624
+ /**
625
+ * Writes a stream's bytes through a held handle, all of each chunk; a cancel ends the source, and with it the write.
626
+ *
627
+ * @param source - The bytes.
628
+ * @param handle - The open temporary file.
629
+ * @param how - The signal and the byte counter.
630
+ * @returns The bytes written.
631
+ * @throws {Error} When cancelled, or when the source or the write fails.
632
+ */
633
+ async function stream_writeThrough(source, handle, how) {
634
+ const stream_cancel = () => {
635
+ const destroyer = Reflect.get(source, 'destroy');
636
+ if (typeof destroyer === 'function')
637
+ Reflect.apply(destroyer, source, [new Error('cancelled: the write was stopped before it was published')]);
638
+ };
639
+ if (how.signal?.aborted === true)
640
+ stream_cancel();
641
+ how.signal?.addEventListener('abort', stream_cancel, { once: true });
642
+ let written = 0;
643
+ try {
644
+ for await (const chunk of source) {
645
+ const bytes = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
646
+ for (let offset = 0; offset < bytes.length;) {
647
+ const { bytesWritten } = await handle.write(bytes, offset, bytes.length - offset);
648
+ offset += bytesWritten;
649
+ }
650
+ written += bytes.length;
651
+ how.bytes_add?.(bytes.length);
652
+ }
653
+ }
654
+ finally {
655
+ how.signal?.removeEventListener('abort', stream_cancel);
656
+ }
657
+ if (how.signal?.aborted === true)
658
+ throw new Error('cancelled: the write was stopped before it was published');
659
+ return written;
660
+ }
661
+ /**
662
+ * Proves the temporary file is the one the handle holds, at its place inside the root.
663
+ *
664
+ * @param root - The root.
665
+ * @param folder - Its folder's expected real path.
666
+ * @param temporary - Its place.
667
+ * @param held - What the handle holds.
668
+ * @throws {Error} When it is not.
669
+ */
670
+ function temporary_prove(root, folder, temporary, held) {
671
+ folder_prove(root, folder);
672
+ let stood;
673
+ try {
674
+ stood = (0, node_fs_1.lstatSync)(temporary);
675
+ }
676
+ catch (error) {
677
+ throw new Error(`refused: the file being written could not be looked at (${code_read(error)}); nothing was published`);
678
+ }
679
+ if (stood.dev !== held.dev || stood.ino !== held.ino || !stood.isFile())
680
+ throw new Error('refused: the file being written is not where it was made; nothing was published');
681
+ }
682
+ /**
683
+ * What may be replaced at a name: nothing, a link (replaced, never followed), or a regular file this account may
684
+ * write. A folder or a special file is refused.
685
+ *
686
+ * @param target - The name's place (a path that reaches it).
687
+ * @param shown - The place as the operator would know it, for the words.
688
+ * @throws {Error} When what stands there may not be replaced.
689
+ */
690
+ function standing_judge(target, shown = target) {
691
+ let stood;
692
+ try {
693
+ stood = (0, node_fs_1.lstatSync)(target);
694
+ }
695
+ catch (error) {
696
+ if (code_read(error) === 'ENOENT')
697
+ return;
698
+ throw new Error(`refused: ${JSON.stringify(shown)} could not be looked at (${code_read(error)}); nothing was written`);
699
+ }
700
+ if (stood.isSymbolicLink())
701
+ return;
702
+ if (!stood.isFile())
703
+ throw new Error(`refused: ${JSON.stringify(shown)} is not a plain file; nothing was written`);
704
+ try {
705
+ (0, node_fs_1.accessSync)(target, node_fs_1.constants.W_OK);
706
+ }
707
+ catch {
708
+ throw new Error(`refused: ${JSON.stringify(shown)} may not be written by this account; nothing was written`);
709
+ }
710
+ }
711
+ /**
712
+ * Removes a temporary file this writer made, only while its folder is still inside the root and its name still
713
+ * holds that file; otherwise it is left, and the caller says so.
714
+ *
715
+ * @param root - The root.
716
+ * @param folder - Its folder.
717
+ * @param temporary - Its place.
718
+ * @param held - What was made.
719
+ * @returns Null when removed (or already gone); else why it could not be.
720
+ */
721
+ function madeFile_remove(root, folder, temporary, held) {
722
+ try {
723
+ folder_prove(root, folder);
724
+ const now = (0, node_fs_1.lstatSync)(temporary);
725
+ if (now.dev !== held.dev || now.ino !== held.ino)
726
+ return `its unfinished file ${JSON.stringify(temporary)} could not be confirmed as this write's, so it was left`;
727
+ (0, node_fs_1.unlinkSync)(temporary);
728
+ return null;
729
+ }
730
+ catch (error) {
731
+ if (code_read(error) === 'ENOENT')
732
+ return null;
733
+ return `its unfinished file ${JSON.stringify(temporary)} could not be removed with certainty (${error instanceof Error ? error.message : String(error)})`;
734
+ }
735
+ }
736
+ /**
737
+ * What stands at a local path (following a link, as a destination the operator named is followed), for a
738
+ * download's planning: nothing is opened or changed.
739
+ *
740
+ * @param local - The path.
741
+ * @returns Its kind, or null when nothing stands there.
742
+ *
743
+ * @example
744
+ * ```ts
745
+ * if (localPath_kind('./out') === 'file') refuse();
746
+ * ```
747
+ */
748
+ function localPath_kind(local) {
749
+ try {
750
+ const stood = (0, node_fs_1.statSync)(local);
751
+ return stood.isFile() ? 'file' : stood.isDirectory() ? 'folder' : 'other';
752
+ }
753
+ catch {
754
+ return null;
755
+ }
756
+ }
757
+ //# sourceMappingURL=placedPath.js.map