@nodetool-ai/runtime-core 0.8.13 → 0.8.14

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.
@@ -9,7 +9,7 @@ import { getNodeBuiltinSync } from "@nodetool-ai/config";
9
9
  import { FileStorageAdapter } from "@nodetool-ai/storage";
10
10
  import { PrefixedStorageAdapter } from "./prefixed-storage-adapter.js";
11
11
  import { withTaskSpan } from "./tracing.js";
12
- import { WorkspacePathError } from "./workspace.js";
12
+ import { NestedFolders, RESERVED_WORKSPACE_DIR, WorkspaceFolderCheckError, WorkspacePathError, WorkspaceReservedPathError, isReservedWorkspaceKey, isReservedWorkspaceName } from "./workspace.js";
13
13
  // Loaded lazily so this module still imports in browser / Edge runtimes, the
14
14
  // same way the storage adapters above it do. Only `materialize`, `absorb`,
15
15
  // `scratchDir` and the local branches of `mkdir`/`deleteAll` need them, and
@@ -51,13 +51,21 @@ function stripWorkspacePrefix(path) {
51
51
  }
52
52
  /** Normalize to a key: no `.`/`..` segments, no leading or trailing slash. */
53
53
  function normalize(path) {
54
+ return normalizeKey(stripWorkspacePrefix(path), path);
55
+ }
56
+ /**
57
+ * {@link normalize} for a string that is a key already: the prefixes a caller
58
+ * may write a path with are not stripped, so a directory named `workspace`
59
+ * stays one. `shown` is the path an error names.
60
+ */
61
+ function normalizeKey(key, shown = key) {
54
62
  const segments = [];
55
- for (const segment of stripWorkspacePrefix(path).split("/")) {
63
+ for (const segment of key.replaceAll("\\", "/").split("/")) {
56
64
  if (!segment || segment === ".")
57
65
  continue;
58
66
  if (segment === "..") {
59
67
  if (segments.length === 0)
60
- throw new WorkspacePathError(path);
68
+ throw new WorkspacePathError(shown);
61
69
  segments.pop();
62
70
  continue;
63
71
  }
@@ -93,14 +101,42 @@ function localRootOf(storage) {
93
101
  * absent to `access`, and the create would then follow it out.
94
102
  */
95
103
  async function realPathWithinRoot(root, candidate) {
104
+ return (await realKeyWithinRoot(root, candidate)) !== null;
105
+ }
106
+ /**
107
+ * Where `candidate` really is inside `root`, as a workspace key with every
108
+ * symlink resolved: "" for the root itself, null when the real location is
109
+ * outside the root or cannot be decided.
110
+ *
111
+ * The real key can differ from the key a caller wrote: `shortcut/x` is
112
+ * `games/tetris/x` when `shortcut` links to `games/tetris`. Whatever judges a
113
+ * path by its key judges this one as well.
114
+ */
115
+ async function realKeyWithinRoot(root, candidate) {
116
+ const realRoot = await requireNode().fs.realpath(root);
117
+ const found = await resolveExisting(candidate);
118
+ return found ? keyBelow(realRoot, found.real, found.rest) : null;
119
+ }
120
+ /** The key of `real` under `realRoot`, plus `rest`; null when it is not under it. */
121
+ function keyBelow(realRoot, real, rest) {
122
+ const { path } = requireNode();
123
+ const rel = path.relative(realRoot, real);
124
+ if (rel !== "" && (isClimb(rel, path) || path.isAbsolute(rel)))
125
+ return null;
126
+ return [...(rel === "" ? [] : rel.split(path.sep)), ...rest].join("/");
127
+ }
128
+ /** Whether a `path.relative` result leaves the directory it is relative to. */
129
+ function isClimb(rel, path) {
130
+ return rel === ".." || rel.startsWith(`..${path.sep}`); // key-boundary-ok: sep anchors the parent path component of a path.relative result.
131
+ }
132
+ /**
133
+ * `candidate` with every symlink resolved, as far as it exists. Null when it,
134
+ * or an ancestor, is a link with no target: such a path cannot be decided.
135
+ */
136
+ async function resolveExisting(candidate) {
96
137
  const { fs, path } = requireNode();
97
- const realRoot = await fs.realpath(root);
98
- const within = (real) => {
99
- const rel = path.relative(realRoot, real);
100
- return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
101
- };
102
138
  try {
103
- return within(await fs.realpath(candidate));
139
+ return { real: await fs.realpath(candidate), rest: [] };
104
140
  }
105
141
  catch {
106
142
  // Not resolvable — either absent, or a link with no target.
@@ -108,7 +144,7 @@ async function realPathWithinRoot(root, candidate) {
108
144
  try {
109
145
  // Exists as a link whose target does not — never follow it.
110
146
  await fs.lstat(candidate);
111
- return false;
147
+ return null;
112
148
  }
113
149
  catch {
114
150
  // Genuinely absent: the parent decides.
@@ -116,10 +152,11 @@ async function realPathWithinRoot(root, candidate) {
116
152
  // Walk up to the nearest ancestor that exists — writing `out/deep/x.txt`
117
153
  // into a workspace that has neither directory yet is ordinary, and only the
118
154
  // first real ancestor can be resolved.
155
+ const rest = [path.basename(candidate)];
119
156
  let parent = path.dirname(candidate);
120
157
  while (true) {
121
158
  try {
122
- return within(await fs.realpath(parent));
159
+ return { real: await fs.realpath(parent), rest };
123
160
  }
124
161
  catch {
125
162
  // realpath failed — either this ancestor is genuinely absent, or it is
@@ -129,27 +166,512 @@ async function realPathWithinRoot(root, candidate) {
129
166
  // straight at the root would resolve "within" by accident.
130
167
  try {
131
168
  await fs.lstat(parent);
132
- return false;
169
+ return null;
133
170
  }
134
171
  catch {
135
172
  // Genuinely absent: keep climbing.
136
173
  }
137
174
  const next = path.dirname(parent);
138
175
  if (next === parent)
139
- return false;
176
+ return null;
177
+ rest.unshift(path.basename(parent));
140
178
  parent = next;
141
179
  }
142
180
  }
143
181
  }
182
+ /** How many links a create follows before it gives up, as the kernel does. */
183
+ const MAX_LINK_HOPS = 40;
184
+ /**
185
+ * The path a create at `candidate` writes: `candidate` itself, or the end of
186
+ * the chain of links that starts there. A dangling link is not a free name,
187
+ * because `writeFile` follows it and creates its target. Null when the chain
188
+ * does not end or cannot be read.
189
+ */
190
+ async function landingOf(candidate) {
191
+ const { fs, path } = requireNode();
192
+ let current = candidate;
193
+ for (let hop = 0; hop <= MAX_LINK_HOPS; hop++) {
194
+ try {
195
+ if (!(await fs.lstat(current)).isSymbolicLink())
196
+ return current;
197
+ }
198
+ catch {
199
+ return current;
200
+ }
201
+ try {
202
+ const link = await fs.readlink(current);
203
+ // A relative target is read from the directory the link really is in.
204
+ const directory = await fs
205
+ .realpath(path.dirname(current))
206
+ .catch(() => path.dirname(current));
207
+ current = path.resolve(directory, link);
208
+ }
209
+ catch {
210
+ return null;
211
+ }
212
+ }
213
+ return null;
214
+ }
215
+ /**
216
+ * The key of `found` under `realRoot` by identity: the device and inode of
217
+ * each ancestor of its real path compared with those of the root. This is the
218
+ * answer for a spelling that `realpath` does not resolve, such as a macOS
219
+ * firmlink or a Windows share of a local drive. Null when no ancestor is the
220
+ * root.
221
+ */
222
+ async function keyByIdentity(realRoot, found) {
223
+ const { fs, path } = requireNode();
224
+ try {
225
+ const rootId = await fs.stat(realRoot, { bigint: true });
226
+ let ancestor = found.real;
227
+ while (true) {
228
+ const id = await fs.stat(ancestor, { bigint: true });
229
+ if (id.dev === rootId.dev && id.ino === rootId.ino) {
230
+ const rel = path.relative(ancestor, found.real);
231
+ return [...(rel === "" ? [] : rel.split(path.sep)), ...found.rest].join("/");
232
+ }
233
+ const next = path.dirname(ancestor);
234
+ if (next === ancestor)
235
+ return null;
236
+ ancestor = next;
237
+ }
238
+ }
239
+ catch {
240
+ return null;
241
+ }
242
+ }
243
+ /**
244
+ * Where a create or read at `target` really is inside `root`: links resolved,
245
+ * a dangling link followed to where a create would land, and a spelling that
246
+ * `realpath` leaves alone judged by the root's identity. Null when it is not
247
+ * inside, or cannot be decided. Throws when the root is not there.
248
+ */
249
+ async function realLandingKey(root, target) {
250
+ const realRoot = await requireNode().fs.realpath(root);
251
+ const landing = await landingOf(target);
252
+ if (landing === null)
253
+ return null;
254
+ const found = await resolveExisting(landing);
255
+ if (!found)
256
+ return null;
257
+ return keyBelow(realRoot, found.real, found.rest) ?? (await keyByIdentity(realRoot, found));
258
+ }
259
+ /** The administrative share of drive `X`, `X$`. */
260
+ const ADMIN_SHARE = /^([A-Za-z])\$$/;
261
+ /**
262
+ * A Windows path in the plain drive form: the long path prefix (`\\?\C:\`),
263
+ * the device prefix (`\\.\C:\`) and the administrative share of this host
264
+ * (`\\localhost\C$\`, also by loopback address or host name) all name
265
+ * `C:\`. `path.win32.relative` reads each as another root. `path` is the
266
+ * module the caller resolves with; on POSIX nothing changes.
267
+ */
268
+ function plainWindowsPath(target, path, hostname) {
269
+ if (path.sep !== "\\")
270
+ return target;
271
+ let p = target.replaceAll("/", "\\");
272
+ const device = /^\\\\[?.]\\(?=[A-Za-z]:|UNC\\)/i.exec(p);
273
+ if (device) {
274
+ p = p.slice(device[0].length);
275
+ if (/^UNC\\/i.test(p))
276
+ p = `\\\\${p.slice(4)}`;
277
+ }
278
+ const share = /^\\\\([^\\]+)\\([^\\]+)(\\.*)?$/.exec(p);
279
+ if (share) {
280
+ const host = share[1].toLowerCase();
281
+ const drive = ADMIN_SHARE.exec(share[2]);
282
+ const local = host === "localhost" ||
283
+ host === "127.0.0.1" ||
284
+ host === "::1" ||
285
+ host === "[::1]" ||
286
+ host === hostname.toLowerCase();
287
+ if (local && drive)
288
+ p = `${drive[1]}:${share[3] ?? "\\"}`;
289
+ }
290
+ return p;
291
+ }
292
+ /**
293
+ * Where `target` sits in `root` as written, before any link is resolved: a
294
+ * key, "" for the root itself, null when it is outside. Windows spellings of
295
+ * a drive path are read as the drive path. Exported for its tests, which pass
296
+ * `path.win32` on a POSIX host.
297
+ */
298
+ export function lexicalKeyWithin(root, target, path, hostname) {
299
+ const plain = (p) => path.resolve(plainWindowsPath(path.resolve(p), path, hostname));
300
+ const inside = path.relative(plain(root), plain(target));
301
+ if (isClimb(inside, path) || path.isAbsolute(inside))
302
+ return null;
303
+ return inside === "" ? "" : inside.split(path.sep).join("/");
304
+ }
305
+ /**
306
+ * How long a workspace keeps what it learned about a directory being another
307
+ * folder, in ms. Long enough that a run or a scan asks once per directory,
308
+ * short enough that a workspace held for a long time, such as the one of a
309
+ * chat thread, soon sees a project folder created inside it.
310
+ */
311
+ export const NESTED_FOLDER_MEMORY_MS = 10_000;
312
+ function isFresh(remembered) {
313
+ return (remembered != null && Date.now() - remembered.at < NESTED_FOLDER_MEMORY_MS);
314
+ }
315
+ const nodeFs = getNodeBuiltinSync("node:fs");
316
+ /**
317
+ * Refuse the real path `target` when it is the folder of another project
318
+ * inside `workspace`, or lies in one, or is in the reserved directory. `root`
319
+ * is the real directory the workspace's keys are relative to: its folder, or
320
+ * the scratch directory its files are staged in. `shown` is the path the
321
+ * refusal names.
322
+ *
323
+ * For code that opens a real path itself instead of calling the workspace: a
324
+ * host binary, libav, `node:fs`. The rule is the workspace's own, asked
325
+ * through {@link NestedFolders}, so a folder known by its `.nodetool/`
326
+ * directory and one the host names are refused alike. A path elsewhere on
327
+ * the host passes: whether it may be opened at all is the caller's check.
328
+ *
329
+ * `target` must be the exact path that will be opened. A caller that reads
330
+ * its input more than one way (`workspace/x`, `x`, `C:/x`) resolves it once
331
+ * and hands that one result both here and to whatever opens it. The path is
332
+ * judged as written and as it really is, so another spelling of a path in
333
+ * the folder is refused as well: a link inside or outside the folder,
334
+ * `/proc/self/root/...`, a dangling link a create would follow, a macOS
335
+ * firmlink, or a Windows long path or administrative share.
336
+ *
337
+ * The check runs before the path is opened, so a link swapped in afterwards
338
+ * is not seen. A writer that must close that gap opens without following a
339
+ * link and checks the file it opened, as the save nodes do.
340
+ */
341
+ export async function assertLocalPathIsOwn(workspace, root, target, shown = target, use = {}) {
342
+ const { path, os } = requireNode();
343
+ const nested = new NestedFolders(workspace);
344
+ const judge = async (key) => {
345
+ // The root is the folder itself, which is never another project's.
346
+ if (key === "")
347
+ return;
348
+ // Another spelling of `.nodetool` (a Windows short name, trailing dots
349
+ // or spaces, a link) is the reserved directory by its real path.
350
+ if (isReservedWorkspaceKey(key)) {
351
+ throw new WorkspaceReservedPathError(shown);
352
+ }
353
+ if (await nested.covers(key)) {
354
+ throw new WorkspaceReservedPathError(shown, "nested");
355
+ }
356
+ };
357
+ const key = lexicalKeyWithin(root, target, path, os.hostname());
358
+ if (key !== null)
359
+ await judge(key);
360
+ // The same question for where the path really is, links resolved.
361
+ let realKey;
362
+ try {
363
+ realKey = await realLandingKey(root, path.resolve(target));
364
+ }
365
+ catch {
366
+ // The root is not there: nothing can be opened under it.
367
+ return;
368
+ }
369
+ if (realKey === null) {
370
+ if (use.write && key !== null && key !== "") {
371
+ throw new WorkspacePathError(shown);
372
+ }
373
+ return;
374
+ }
375
+ if (realKey !== key)
376
+ await judge(realKey);
377
+ }
378
+ /**
379
+ * Whether the real path `root`/`key` is, or lies in, a directory that holds
380
+ * a reserved directory: the folder of another project inside the workspace
381
+ * rooted at `root`. The root itself never counts.
382
+ *
383
+ * A floor under {@link assertLocalPathIsOwn} for a path that is resolved
384
+ * synchronously, or by a run that has a directory and no workspace. It reads
385
+ * the mark on disk only. A folder the host names without that mark, such as
386
+ * a game's workspace, is known to the workspace alone, so whatever opens the
387
+ * resolved path calls {@link assertLocalPathIsOwn} as well.
388
+ */
389
+ export function localPathIsInNestedFolder(root, key) {
390
+ if (!nodeFs || !nodePath)
391
+ return false;
392
+ let directory = root;
393
+ for (const segment of key.split("/")) {
394
+ if (!segment)
395
+ continue;
396
+ directory = nodePath.join(directory, segment);
397
+ const mark = nodeFs.statSync(nodePath.join(directory, RESERVED_WORKSPACE_DIR), {
398
+ throwIfNoEntry: false
399
+ });
400
+ if (mark?.isDirectory())
401
+ return true;
402
+ }
403
+ return false;
404
+ }
144
405
  const textDecoder = new TextDecoder();
145
406
  const textEncoder = new TextEncoder();
407
+ /** An adapter that publishes a file on this host by a streaming copy. */
408
+ function hasStoreFile(storage) {
409
+ return typeof storage.storeFile === "function";
410
+ }
411
+ /** An adapter that publishes a file on this host only to a free key. */
412
+ function hasStoreFileIfAbsent(storage) {
413
+ return (typeof storage.storeFileIfAbsent ===
414
+ "function");
415
+ }
146
416
  export class StorageWorkspace {
147
417
  storage;
148
418
  localDir;
149
419
  scratch = null;
420
+ nestedFolderSource;
421
+ declaredNestedFolders = null;
422
+ /** Per directory key: whether it holds a reserved directory. */
423
+ reservedMarks = new Map();
424
+ /**
425
+ * The one rule for the folders of other projects in this workspace. It
426
+ * asks by key, where {@link isNestedFolder} takes a caller's path.
427
+ */
428
+ nested = new NestedFolders({
429
+ isNestedFolder: (key) => this.isNestedKey(key)
430
+ });
150
431
  constructor(storage, opts = {}) {
151
432
  this.storage = storage;
152
433
  this.localDir = opts.localDir ?? localRootOf(storage);
434
+ this.nestedFolderSource = opts.nestedFolders ?? null;
435
+ }
436
+ /** The nested folders the host named, as lower-cased workspace keys. */
437
+ declaredNested() {
438
+ const source = this.nestedFolderSource;
439
+ if (!source)
440
+ return Promise.resolve(new Set());
441
+ if (isFresh(this.declaredNestedFolders)) {
442
+ return this.declaredNestedFolders.value;
443
+ }
444
+ const value = Promise.resolve()
445
+ .then(source)
446
+ .then((paths) => {
447
+ const keys = new Set();
448
+ for (const path of paths) {
449
+ try {
450
+ // An empty key is the root, which is this folder itself.
451
+ const key = normalizeKey(path);
452
+ if (key)
453
+ keys.add(key.toLowerCase());
454
+ }
455
+ catch {
456
+ // A path outside the workspace names no directory in it.
457
+ }
458
+ }
459
+ return keys;
460
+ });
461
+ const remembered = { at: Date.now(), value };
462
+ this.declaredNestedFolders = remembered;
463
+ // An answer that failed is asked for again.
464
+ value.catch(() => {
465
+ if (this.declaredNestedFolders === remembered) {
466
+ this.declaredNestedFolders = null;
467
+ }
468
+ });
469
+ return value;
470
+ }
471
+ /**
472
+ * Whether the directory at `key` holds a reserved directory, remembered
473
+ * for {@link NESTED_FOLDER_MEMORY_MS}.
474
+ */
475
+ hasReservedDirectory(key) {
476
+ const known = this.reservedMarks.get(key);
477
+ if (isFresh(known))
478
+ return known.value;
479
+ const value = this.readReservedDirectory(key);
480
+ const remembered = { at: Date.now(), value };
481
+ this.reservedMarks.set(key, remembered);
482
+ value.catch(() => {
483
+ if (this.reservedMarks.get(key) === remembered) {
484
+ this.reservedMarks.delete(key);
485
+ }
486
+ });
487
+ return value;
488
+ }
489
+ async readReservedDirectory(key) {
490
+ if (this.localDir) {
491
+ await this.ensureRoot();
492
+ const directory = resolvePath(this.localDir, key);
493
+ // A directory reached through a link out of the root is refused by
494
+ // every operation anyway, and nothing outside the root is looked at.
495
+ if (!(await realPathWithinRoot(this.localDir, directory)))
496
+ return false;
497
+ try {
498
+ const info = await requireNode().fs.stat(resolvePath(directory, RESERVED_WORKSPACE_DIR));
499
+ return info.isDirectory();
500
+ }
501
+ catch {
502
+ return false;
503
+ }
504
+ }
505
+ const listing = await this.storage.list(`${key}/${RESERVED_WORKSPACE_DIR}/`, { delimiter: "/" });
506
+ return listing.entries.length > 0 || listing.commonPrefixes.length > 0;
507
+ }
508
+ /**
509
+ * On an object store a flat listing names every key below `under`, the
510
+ * reserved ones among them. It therefore says which directories there
511
+ * hold a reserved directory, and none of them is asked about again.
512
+ */
513
+ rememberReservedMarks(entries, under) {
514
+ const marked = new Set();
515
+ const seen = new Set();
516
+ for (const { key } of entries) {
517
+ const segments = key.split("/");
518
+ let directory = "";
519
+ for (const segment of segments.slice(0, -1)) {
520
+ if (isReservedWorkspaceName(segment)) {
521
+ if (directory && segment === RESERVED_WORKSPACE_DIR) {
522
+ marked.add(directory);
523
+ }
524
+ break;
525
+ }
526
+ directory = directory ? `${directory}/${segment}` : segment;
527
+ seen.add(directory);
528
+ }
529
+ }
530
+ const at = Date.now();
531
+ // The listing is complete only for keys at or below `under`.
532
+ const complete = (key) => !under || key === under || key.startsWith(`${under}/`);
533
+ for (const directory of seen) {
534
+ if (!complete(directory))
535
+ continue;
536
+ this.reservedMarks.set(directory, {
537
+ at,
538
+ value: Promise.resolve(marked.has(directory))
539
+ });
540
+ }
541
+ // A listed file is a directory too only when keys lie below it, and then
542
+ // it is among `seen`. Any other holds no reserved directory, so reading
543
+ // it after the listing asks the store nothing more.
544
+ for (const { key } of entries) {
545
+ if (seen.has(key) || isReservedWorkspaceKey(key) || !complete(key))
546
+ continue;
547
+ this.reservedMarks.set(key, { at, value: Promise.resolve(false) });
548
+ }
549
+ }
550
+ async isNestedFolder(path) {
551
+ let key;
552
+ try {
553
+ key = normalizeKey(path);
554
+ }
555
+ catch (error) {
556
+ if (error instanceof WorkspacePathError)
557
+ return false;
558
+ throw error;
559
+ }
560
+ return this.isNestedKey(key);
561
+ }
562
+ /**
563
+ * {@link isNestedFolder} for a normalized key. The root is never one.
564
+ *
565
+ * When the host cannot name its folders, or the storage cannot be asked,
566
+ * the answer is unknown and could be yes. That is a
567
+ * {@link WorkspaceFolderCheckError}, never "no".
568
+ */
569
+ async isNestedKey(key) {
570
+ if (!key || isReservedWorkspaceKey(key))
571
+ return false;
572
+ try {
573
+ // Compared without case, as the reserved directory is.
574
+ if ((await this.declaredNested()).has(key.toLowerCase()))
575
+ return true;
576
+ return await this.hasReservedDirectory(key);
577
+ }
578
+ catch (error) {
579
+ throw new WorkspaceFolderCheckError(key, error);
580
+ }
581
+ }
582
+ /**
583
+ * The entries of a flat listing below the key `under` that are this
584
+ * folder's own: in no reserved directory and in no nested folder.
585
+ */
586
+ async ownEntries(entries, under) {
587
+ if (!this.localDir)
588
+ this.rememberReservedMarks(entries, under);
589
+ /** Per directory: whether it is a nested folder or lies in one. */
590
+ const others = new Map();
591
+ const own = [];
592
+ for (const entry of entries) {
593
+ if (isReservedWorkspaceKey(entry.key))
594
+ continue;
595
+ const slash = entry.key.lastIndexOf("/");
596
+ const directory = slash < 0 ? "" : entry.key.slice(0, slash);
597
+ let other = others.get(directory);
598
+ if (other === undefined) {
599
+ other = directory !== "" && (await this.nested.covers(directory));
600
+ others.set(directory, other);
601
+ }
602
+ if (!other)
603
+ own.push(entry);
604
+ }
605
+ return own;
606
+ }
607
+ /**
608
+ * Whether the real directory at `key` holds a reserved directory or a
609
+ * nested folder at any depth. Symbolic links are not followed.
610
+ */
611
+ async holdsOtherFolder(key) {
612
+ if (!this.localDir)
613
+ return false;
614
+ const { fs } = requireNode();
615
+ const pending = [key];
616
+ for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
617
+ let children;
618
+ try {
619
+ children = await fs.readdir(resolvePath(this.localDir, next), {
620
+ withFileTypes: true
621
+ });
622
+ }
623
+ catch {
624
+ // Not a directory, or gone: it holds nothing.
625
+ continue;
626
+ }
627
+ for (const child of children) {
628
+ if (!child.isDirectory())
629
+ continue;
630
+ const childKey = `${next}/${child.name}`;
631
+ if (isReservedWorkspaceName(child.name) ||
632
+ (await this.nested.isFolder(childKey))) {
633
+ return true;
634
+ }
635
+ pending.push(childKey);
636
+ }
637
+ }
638
+ return false;
639
+ }
640
+ /**
641
+ * Remove the real directory at `key` with everything in it but the
642
+ * reserved directories and the nested folders. A directory on the way to
643
+ * one stays, emptied of the rest. Returns whether the directory at `key`
644
+ * itself was removed.
645
+ */
646
+ async removeOwnDirectory(key) {
647
+ if (!this.localDir)
648
+ return true;
649
+ const { fs, path } = requireNode();
650
+ const dir = resolvePath(this.localDir, key);
651
+ let children;
652
+ try {
653
+ children = await fs.readdir(dir, { withFileTypes: true });
654
+ }
655
+ catch {
656
+ // Not a directory, or already gone.
657
+ await fs.rm(dir, { recursive: true, force: true });
658
+ return true;
659
+ }
660
+ let kept = false;
661
+ for (const child of children) {
662
+ const childKey = `${key}/${child.name}`;
663
+ if (!child.isDirectory()) {
664
+ await fs.rm(path.join(dir, child.name), { force: true });
665
+ }
666
+ else if (isReservedWorkspaceName(child.name) ||
667
+ (await this.nested.isFolder(childKey)) ||
668
+ !(await this.removeOwnDirectory(childKey))) {
669
+ kept = true;
670
+ }
671
+ }
672
+ if (!kept)
673
+ await fs.rmdir(dir);
674
+ return !kept;
153
675
  }
154
676
  rootReady = null;
155
677
  /** Create the workspace directory once, on first use. */
@@ -166,26 +688,50 @@ export class StorageWorkspace {
166
688
  const key = normalize(path);
167
689
  if (!key)
168
690
  throw new WorkspacePathError(path);
691
+ if (isReservedWorkspaceKey(key))
692
+ throw new WorkspaceReservedPathError(path);
169
693
  return key;
170
694
  }
171
695
  /**
172
- * Refuse a path whose real location leaves the workspace.
696
+ * Refuse a path this workspace does not reach: one whose real location
697
+ * leaves the workspace, and one in the folder of another project inside it.
698
+ *
699
+ * Called on every operation. `key()` refuses a `..` that climbs out
700
+ * lexically and the reserved directory. A symlink defeats that, which only
701
+ * a local workspace has. A path in a nested folder is refused on every
702
+ * backend: its files belong to the other project.
173
703
  *
174
- * Called on every operation that touches a local workspace. `key()` already
175
- * refuses a `..` that climbs out lexically; this is the half a symlink
176
- * defeats.
704
+ * `asDirectory` is set by the operations that take a directory. They also
705
+ * refuse the nested folder itself, which a path to a file cannot be.
177
706
  */
178
- async assertContained(path) {
179
- if (!this.localDir)
180
- return;
181
- // The root may not exist yet (a workspace folder created on first use).
182
- // Without this the walk below climbs past it to an ancestor that does
183
- // exist, finds that outside the root, and refuses every path in a
184
- // perfectly good workspace.
185
- await this.ensureRoot();
186
- const target = resolvePath(this.localDir, this.key(path));
187
- if (!(await realPathWithinRoot(this.localDir, target))) {
188
- throw new WorkspacePathError(path);
707
+ async assertContained(path, asDirectory = false) {
708
+ // The lexical rules, the reserved directory among them, hold on every
709
+ // backend. Only the symlink half below needs a real directory.
710
+ const key = this.key(path);
711
+ let realKey = key;
712
+ if (this.localDir) {
713
+ // The root may not exist yet (a workspace folder created on first use).
714
+ // Without this the walk below climbs past it to an ancestor that does
715
+ // exist, finds that outside the root, and refuses every path in a
716
+ // perfectly good workspace.
717
+ await this.ensureRoot();
718
+ const target = resolvePath(this.localDir, key);
719
+ const real = await realKeyWithinRoot(this.localDir, target);
720
+ if (real === null)
721
+ throw new WorkspacePathError(path);
722
+ realKey = real;
723
+ }
724
+ const isOther = (candidate) => asDirectory ? this.nested.covers(candidate) : this.nested.holds(candidate);
725
+ // Judged as written, and as it really is: a link inside the folder can
726
+ // point at another project's folder, which no `.nodetool/` need mark.
727
+ // The same goes for the reserved directory: `NODETO~1` and `.nodetool.`
728
+ // are `.nodetool` only once the operating system has resolved them.
729
+ if (realKey !== key && isReservedWorkspaceKey(realKey)) {
730
+ throw new WorkspaceReservedPathError(path);
731
+ }
732
+ if ((await isOther(key)) ||
733
+ (realKey !== key && realKey !== "" && (await this.nested.covers(realKey)))) {
734
+ throw new WorkspaceReservedPathError(path, "nested");
189
735
  }
190
736
  }
191
737
  uri(path) {
@@ -217,14 +763,50 @@ export class StorageWorkspace {
217
763
  await this.storage.store(this.key(path), bytes, contentType);
218
764
  });
219
765
  }
766
+ writeNew(path, data, contentType, options = {}) {
767
+ const bytes = typeof data === "string" ? textEncoder.encode(data) : data;
768
+ return withTaskSpan("io", "workspace.write_new", { "nodetool.workspace.bytes": bytes.byteLength }, async () => {
769
+ await this.assertContained(path);
770
+ if (!this.storage.storeIfAbsent) {
771
+ // Never a check followed by `store`: that is the overwrite this
772
+ // method exists to rule out.
773
+ throw new Error("This workspace's storage cannot create a file without replacing one");
774
+ }
775
+ const key = this.key(path);
776
+ const { stagingName } = options;
777
+ if (stagingName !== undefined) {
778
+ // The staging file sits beside the target, so it is held to the
779
+ // same rules: inside the workspace and outside the reserved directory.
780
+ const slash = key.lastIndexOf("/");
781
+ const beside = `${key.slice(0, slash + 1)}${stagingName}`;
782
+ if (stagingName.includes("/") || this.key(beside) !== beside) {
783
+ throw new WorkspacePathError(stagingName);
784
+ }
785
+ }
786
+ const uri = await this.storage.storeIfAbsent(key, bytes, contentType, {
787
+ stagingName
788
+ });
789
+ return uri !== null;
790
+ });
791
+ }
220
792
  async exists(path) {
221
793
  try {
222
794
  await this.assertContained(path);
223
795
  }
224
- catch {
225
- return false;
796
+ catch (error) {
797
+ // A path the workspace refuses holds nothing a caller can use. A check
798
+ // that could not be made says nothing about the file, so it is not
799
+ // answered with "absent".
800
+ if (error instanceof WorkspacePathError ||
801
+ error instanceof WorkspaceReservedPathError) {
802
+ return false;
803
+ }
804
+ throw error;
226
805
  }
227
- return this.storage.exists(this.uri(path));
806
+ if (!(await this.storage.exists(this.uri(path))))
807
+ return false;
808
+ // A real directory answers as existing, and can be another folder.
809
+ return !(this.localDir && (await this.nested.isFolder(this.key(path))));
228
810
  }
229
811
  async stat(path) {
230
812
  await this.assertContained(path);
@@ -245,6 +827,19 @@ export class StorageWorkspace {
245
827
  // a real directory, and reporting an existing empty folder as missing is a
246
828
  // difference a caller can see.
247
829
  const listing = await this.storage.list(`${key}/`, { delimiter: "/" });
830
+ if (!this.localDir) {
831
+ // The listing shows whether `key` holds a reserved directory, so an
832
+ // object store is not asked about it a second time.
833
+ const reserved = `${key}/${RESERVED_WORKSPACE_DIR}`;
834
+ const marked = listing.commonPrefixes.some((prefix) => prefix === reserved || prefix === `${reserved}/`);
835
+ this.reservedMarks.set(key, {
836
+ at: Date.now(),
837
+ value: Promise.resolve(marked)
838
+ });
839
+ }
840
+ if (await this.nested.isFolder(key)) {
841
+ throw new WorkspaceReservedPathError(path, "nested");
842
+ }
248
843
  if (listing.entries.length > 0 || listing.commonPrefixes.length > 0) {
249
844
  return { path: key, size: 0, modifiedAt: 0, isDirectory: true };
250
845
  }
@@ -273,26 +868,37 @@ export class StorageWorkspace {
273
868
  async listEntries(path, opts) {
274
869
  const key = normalize(path);
275
870
  if (key)
276
- await this.assertContained(key);
871
+ await this.assertContained(key, true);
277
872
  const prefix = key ? `${key}/` : "";
278
873
  const listing = await this.storage.list(prefix, opts.recursive === true ? {} : { delimiter: "/" });
279
- const files = listing.entries.map((entry) => ({
874
+ // `assertContained` above refuses a listing that starts in a reserved
875
+ // directory or a nested folder. One that starts above them leaves them
876
+ // out, at every depth.
877
+ const entries = opts.recursive === true
878
+ ? await this.ownEntries(listing.entries, key)
879
+ : listing.entries.filter((entry) => !isReservedWorkspaceKey(entry.key));
880
+ const files = entries.map((entry) => ({
280
881
  path: entry.key,
281
882
  name: entry.key.slice(entry.key.lastIndexOf("/") + 1),
282
883
  size: entry.size,
283
884
  modifiedAt: entry.modifiedAt,
284
885
  isDirectory: false
285
886
  }));
286
- const dirs = listing.commonPrefixes.map((p) => {
887
+ const dirs = [];
888
+ for (const p of listing.commonPrefixes) {
287
889
  const trimmed = p.endsWith("/") ? p.slice(0, -1) : p;
288
- return {
890
+ if (isReservedWorkspaceKey(trimmed))
891
+ continue;
892
+ if (await this.nested.isFolder(trimmed))
893
+ continue;
894
+ dirs.push({
289
895
  path: trimmed,
290
896
  name: trimmed.slice(trimmed.lastIndexOf("/") + 1),
291
897
  size: 0,
292
898
  modifiedAt: 0,
293
899
  isDirectory: true
294
- };
295
- });
900
+ });
901
+ }
296
902
  return [...dirs, ...files].sort((a, b) => a.path.localeCompare(b.path));
297
903
  }
298
904
  async delete(path) {
@@ -307,22 +913,22 @@ export class StorageWorkspace {
307
913
  // hands back keys that are lexically inside the root, so the adapter's own
308
914
  // lexical check passes and `unlink` follows the link out.
309
915
  if (key)
310
- await this.assertContained(key);
916
+ await this.assertContained(key, true);
311
917
  const listing = await this.storage.list(key ? `${key}/` : "");
312
918
  let deleted = 0;
313
- for (const entry of listing.entries) {
919
+ // NodeTool's own directory is left alone, and so is the folder of another
920
+ // project inside the directory being cleared, with every file in it.
921
+ for (const entry of await this.ownEntries(listing.entries, key)) {
314
922
  if (await this.storage.delete(entry.uri))
315
923
  deleted++;
316
924
  }
317
925
  // On an object store the prefix is gone once its keys are. A real
318
926
  // directory would linger and keep showing up in `list`, so remove it —
319
- // otherwise the same call leaves two different workspaces behind.
320
- if (this.localDir && key) {
321
- await requireNode().fs.rm(resolvePath(this.localDir, key), {
322
- recursive: true,
323
- force: true
324
- });
325
- }
927
+ // otherwise the same call leaves two different workspaces behind. A
928
+ // reserved directory and a nested folder below it stay, with the
929
+ // directories that lead to them.
930
+ if (this.localDir && key)
931
+ await this.removeOwnDirectory(key);
326
932
  return deleted;
327
933
  }
328
934
  async mkdir(path) {
@@ -330,11 +936,11 @@ export class StorageWorkspace {
330
936
  // there is nothing to create and nothing to fail. A local workspace makes
331
937
  // the real directory so an empty one survives and a host binary can cd
332
938
  // into it.
939
+ const key = normalize(path);
940
+ if (!key)
941
+ return;
942
+ await this.assertContained(key, true);
333
943
  if (this.localDir) {
334
- const key = normalize(path);
335
- if (!key)
336
- return;
337
- await this.assertContained(key);
338
944
  await requireNode().fs.mkdir(resolvePath(this.localDir, key), {
339
945
  recursive: true
340
946
  });
@@ -348,15 +954,66 @@ export class StorageWorkspace {
348
954
  const st = await this.stat(from);
349
955
  await this.write(to, bytes, st?.contentType);
350
956
  }
957
+ /**
958
+ * Move a file, or a directory with everything under it. A directory is
959
+ * never moved into itself or onto anything that exists, except onto a name
960
+ * that differs from its own only in case. A local directory is renamed in
961
+ * one step, so the files keep their bytes and modification times. On an
962
+ * object store each file is copied to its new key, then removed.
963
+ *
964
+ * A directory that holds a reserved directory or a nested folder at any
965
+ * depth is refused before anything moves, and so is a target in a nested
966
+ * folder.
967
+ */
351
968
  async move(from, to) {
352
- await this.copy(from, to);
353
- await this.delete(from);
969
+ await this.assertContained(from);
970
+ const fromKey = this.key(from);
971
+ if (await this.storage.stat(this.storage.uriForKey(fromKey))) {
972
+ await this.copy(from, to);
973
+ await this.delete(from);
974
+ return;
975
+ }
976
+ const source = await this.stat(fromKey);
977
+ if (!source?.isDirectory) {
978
+ throw new Error(`Cannot move '${from}': it does not exist`);
979
+ }
980
+ await this.assertContained(to, true);
981
+ const toKey = this.key(to);
982
+ if (toKey === fromKey || toKey.startsWith(`${fromKey}/`)) {
983
+ throw new Error(`Cannot move '${from}' into itself`);
984
+ }
985
+ const caseOnly = toKey.toLowerCase() === fromKey.toLowerCase();
986
+ if (!caseOnly && (await this.stat(toKey))) {
987
+ throw new Error(`Cannot move '${from}' to '${to}': it already exists`);
988
+ }
989
+ if (this.localDir) {
990
+ const { fs, path } = requireNode();
991
+ if (await this.holdsOtherFolder(fromKey)) {
992
+ throw new WorkspaceReservedPathError(from, "holds");
993
+ }
994
+ const target = resolvePath(this.localDir, toKey);
995
+ await fs.mkdir(path.dirname(target), { recursive: true });
996
+ await fs.rename(resolvePath(this.localDir, fromKey), target);
997
+ return;
998
+ }
999
+ const listing = await this.storage.list(`${fromKey}/`);
1000
+ const own = await this.ownEntries(listing.entries, fromKey);
1001
+ if (own.length !== listing.entries.length) {
1002
+ throw new WorkspaceReservedPathError(from, "holds");
1003
+ }
1004
+ for (const entry of listing.entries) {
1005
+ const moved = `${toKey}/${entry.key.slice(fromKey.length + 1)}`;
1006
+ await this.copy(entry.key, moved);
1007
+ await this.storage.delete(entry.uri);
1008
+ }
354
1009
  }
355
1010
  materialize(path) {
356
1011
  return withTaskSpan("io", "workspace.materialize", {}, () => this.stage(path));
357
1012
  }
358
1013
  async stage(path) {
359
- await this.assertContained(path);
1014
+ // As a directory: on a local workspace the answer is a real path, and
1015
+ // the real directory of a nested folder is not handed out either.
1016
+ await this.assertContained(path, true);
360
1017
  const key = this.key(path);
361
1018
  if (this.localDir)
362
1019
  return resolvePath(this.localDir, key);
@@ -375,14 +1032,35 @@ export class StorageWorkspace {
375
1032
  }
376
1033
  async absorbFile(localPath, path) {
377
1034
  const node = requireNode();
1035
+ await this.assertContained(path);
378
1036
  if (this.localDir &&
379
1037
  node.path.resolve(localPath) ===
380
1038
  node.path.resolve(this.localDir, this.key(path))) {
381
1039
  // The binary already wrote in place — the workspace *is* that file.
382
1040
  return;
383
1041
  }
1042
+ // A folder on this host takes the file with a bounded streaming copy,
1043
+ // which also refuses a file above the upload limit, so a large file is
1044
+ // never read into memory whole.
1045
+ const { storage } = this;
1046
+ if (this.localDir && hasStoreFile(storage)) {
1047
+ await storage.storeFile(this.key(path), localPath);
1048
+ return;
1049
+ }
384
1050
  await this.write(path, new Uint8Array(await node.fs.readFile(localPath)));
385
1051
  }
1052
+ absorbNew(localPath, path, contentType) {
1053
+ return withTaskSpan("io", "workspace.absorb_new", {}, async () => {
1054
+ const { storage } = this;
1055
+ if (this.localDir && hasStoreFileIfAbsent(storage)) {
1056
+ await this.assertContained(path);
1057
+ return (await storage.storeFileIfAbsent(this.key(path), localPath)) !== null;
1058
+ }
1059
+ // An object store takes the file whole, as `absorb` gives it.
1060
+ const bytes = new Uint8Array(await requireNode().fs.readFile(localPath));
1061
+ return this.writeNew(path, bytes, contentType);
1062
+ });
1063
+ }
386
1064
  async scratchDir() {
387
1065
  if (this.localDir)
388
1066
  return this.localDir;
@@ -405,19 +1083,21 @@ export class StorageWorkspace {
405
1083
  * gives each user their own workspace inside the one bucket it has.
406
1084
  */
407
1085
  export function createWorkspace(storage, opts = {}) {
1086
+ const { nestedFolders } = opts;
408
1087
  if (!opts.prefix)
409
- return new StorageWorkspace(storage);
1088
+ return new StorageWorkspace(storage, { nestedFolders });
410
1089
  return new StorageWorkspace(new PrefixedStorageAdapter(storage, opts.prefix), {
411
1090
  // A prefixed view of a local folder still has a real directory: the
412
1091
  // subfolder the prefix names.
413
1092
  localDir: (() => {
414
1093
  const root = localRootOf(storage);
415
1094
  return root ? resolvePath(root, opts.prefix) : null;
416
- })()
1095
+ })(),
1096
+ nestedFolders
417
1097
  });
418
1098
  }
419
1099
  /** A workspace over a real directory. */
420
- export function createLocalWorkspace(dir) {
421
- return new StorageWorkspace(new FileStorageAdapter(dir));
1100
+ export function createLocalWorkspace(dir, opts = {}) {
1101
+ return new StorageWorkspace(new FileStorageAdapter(dir), opts);
422
1102
  }
423
1103
  //# sourceMappingURL=storage-workspace.js.map