@statewalker/webrun-files-composite 0.7.1 → 0.8.1

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.
@@ -22,11 +22,63 @@ function normalizePath(filePath) {
22
22
  function joinPath(...segments) {
23
23
  return normalizePath(segments.join("/"));
24
24
  }
25
+ /**
26
+ * Returns the directory portion of a path.
27
+ */
28
+ function dirname(path) {
29
+ const normalized = normalizePath(path);
30
+ const lastSlash = normalized.lastIndexOf("/");
31
+ if (lastSlash <= 0) return "/";
32
+ return normalized.substring(0, lastSlash);
33
+ }
34
+ /**
35
+ * Returns the filename portion of a path.
36
+ */
37
+ function basename(path, ext) {
38
+ const normalized = normalizePath(path);
39
+ const lastSlash = normalized.lastIndexOf("/");
40
+ const name = lastSlash === -1 ? normalized : normalized.substring(lastSlash + 1);
41
+ if (ext && name.endsWith(ext)) return name.substring(0, name.length - ext.length);
42
+ return name;
43
+ }
25
44
  //#endregion
26
45
  //#region src/composite-files-api.ts
46
+ /**
47
+ * Composite `FilesApi` that routes calls to one of several backends based
48
+ * on a path prefix. Mounts are matched by **longest prefix wins**, so a
49
+ * mount at `/a/b` takes precedence over a mount at `/a` for paths under
50
+ * `/a/b/...`. The mount point itself appears in listings as a synthetic
51
+ * directory and cannot be removed.
52
+ *
53
+ * Each backend can use a sub-directory of its own filesystem as the mount
54
+ * root via `fsPath` (constructor `rootPath` for the implicit root mount,
55
+ * `fsPath` argument for additional mounts). Cross-mount `move` is
56
+ * implemented as copy-then-delete; there is no atomicity guarantee.
57
+ *
58
+ * Access control and visibility filtering are intentionally **not** part of
59
+ * this class — wrap with {@link GuardedFilesApi} or {@link FilteredFilesApi}
60
+ * (or both) instead.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const fs = new CompositeFilesApi(localFs, "/projects")
65
+ * .mount("/docs", s3Fs, "/documentation")
66
+ * .mount("/cache", memFs);
67
+ * await fs.write("/readme.md", data); // → localFs:/projects/readme.md
68
+ * await fs.write("/docs/api.md", data); // → s3Fs:/documentation/api.md
69
+ * ```
70
+ */
27
71
  var CompositeFilesApi = class {
28
72
  mounts;
29
- guards = [];
73
+ /**
74
+ * @param root Default backend used for any path that does not match a
75
+ * more specific mount. All paths are routed here unless `mount()`
76
+ * intercepts them.
77
+ * @param rootPath Optional sub-directory of the root backend to use as
78
+ * the composite filesystem's `/`. For example, `rootPath = "/projects"`
79
+ * makes the composite path `/readme.md` resolve to `/projects/readme.md`
80
+ * in the root backend. Defaults to `"/"` (no remapping).
81
+ */
30
82
  constructor(root, rootPath) {
31
83
  this.mounts = [{
32
84
  prefix: "/",
@@ -34,6 +86,22 @@ var CompositeFilesApi = class {
34
86
  basePath: normalizePath(rootPath ?? "/")
35
87
  }];
36
88
  }
89
+ /**
90
+ * Attaches a backend to handle every composite path under `path`. The
91
+ * mount prefix is normalized; paths under it are resolved against the
92
+ * mount's `fsPath` sub-directory (defaulting to `"/"`).
93
+ *
94
+ * @param path Composite-namespace prefix (e.g. `"/docs"`). Mounting at
95
+ * `"/"` is forbidden — use the constructor `root` argument instead.
96
+ * @param api The backend `FilesApi` to delegate to for paths under
97
+ * `path`. Wrap it in {@link FilteredFilesApi} / {@link GuardedFilesApi}
98
+ * first if you want mount-local filtering or guards.
99
+ * @param fsPath Sub-directory of the mounted backend used as its mount
100
+ * root, e.g. `mount("/docs", s3, "/documentation")` makes
101
+ * `/docs/api.md` resolve to `/documentation/api.md` on `s3`.
102
+ * @returns `this`, for chaining.
103
+ * @throws If `path` normalizes to `"/"`.
104
+ */
37
105
  mount(path, api, fsPath) {
38
106
  const prefix = normalizePath(path);
39
107
  if (prefix === "/") throw new Error("Cannot mount at root — root is set via constructor");
@@ -45,14 +113,6 @@ var CompositeFilesApi = class {
45
113
  this.mounts.sort((a, b) => b.prefix.length - a.prefix.length);
46
114
  return this;
47
115
  }
48
- guard(operations, check, message) {
49
- this.guards.push({
50
- operations,
51
- check,
52
- message
53
- });
54
- return this;
55
- }
56
116
  resolve(path) {
57
117
  const normalized = normalizePath(path);
58
118
  for (const mount of this.mounts) {
@@ -90,33 +150,19 @@ var CompositeFilesApi = class {
90
150
  }
91
151
  return result;
92
152
  }
93
- checkGuard(operation, path) {
94
- const normalized = normalizePath(path);
95
- for (const guard of this.guards) {
96
- if (!guard.operations.includes(operation)) continue;
97
- if (!guard.check(normalized)) {
98
- const msg = guard.message ?? "Access denied";
99
- throw new Error(`${msg}: ${normalized}`);
100
- }
101
- }
102
- }
103
153
  read(path, options) {
104
- this.checkGuard("read", path);
105
154
  const { api, resolvedPath } = this.resolve(path);
106
155
  return api.read(resolvedPath, options);
107
156
  }
108
157
  async write(path, content) {
109
- this.checkGuard("write", path);
110
158
  const { api, resolvedPath } = this.resolve(path);
111
159
  return api.write(resolvedPath, content);
112
160
  }
113
161
  async mkdir(path) {
114
- this.checkGuard("mkdir", path);
115
162
  const { api, resolvedPath } = this.resolve(path);
116
163
  return api.mkdir(resolvedPath);
117
164
  }
118
165
  async *list(path, options) {
119
- this.checkGuard("list", path);
120
166
  const normalized = normalizePath(path);
121
167
  const { api, resolvedPath } = this.resolve(path);
122
168
  const childMounts = this.childMountPrefixes(normalized);
@@ -181,13 +227,10 @@ var CompositeFilesApi = class {
181
227
  async remove(path) {
182
228
  const normalized = normalizePath(path);
183
229
  if (this.isMountPoint(normalized)) throw new Error(`Cannot remove mount point: ${normalized}`);
184
- this.checkGuard("remove", path);
185
230
  const { api, resolvedPath } = this.resolve(path);
186
231
  return api.remove(resolvedPath);
187
232
  }
188
233
  async move(source, target) {
189
- this.checkGuard("move", source);
190
- this.checkGuard("move", target);
191
234
  const src = this.resolve(source);
192
235
  const tgt = this.resolve(target);
193
236
  if (src.api === tgt.api) return src.api.move(src.resolvedPath, tgt.resolvedPath);
@@ -196,8 +239,6 @@ var CompositeFilesApi = class {
196
239
  return copied;
197
240
  }
198
241
  async copy(source, target) {
199
- this.checkGuard("copy", source);
200
- this.checkGuard("copy", target);
201
242
  const src = this.resolve(source);
202
243
  const tgt = this.resolve(target);
203
244
  if (src.api === tgt.api) return src.api.copy(src.resolvedPath, tgt.resolvedPath);
@@ -236,4 +277,705 @@ var CompositeFilesApi = class {
236
277
  }
237
278
  };
238
279
  //#endregion
280
+ //#region src/cow-files-api.ts
281
+ /**
282
+ * Copy-on-write view: a writable layer over a read-only `base`. The `base`
283
+ * is **never** mutated — every change (write, delete, move) is recorded in
284
+ * the `writable` layer, using marker files to record deletions.
285
+ *
286
+ * Resolution precedence for any path:
287
+ * 1. a covering whiteout / opaque marker ⇒ the path is absent;
288
+ * 2. otherwise the `writable` layer, if it has the path;
289
+ * 3. otherwise fall through to `base`.
290
+ *
291
+ * Deletions are persisted as marker files inside the writable layer, so they
292
+ * survive across process restarts and work over any `FilesApi` backend.
293
+ * Markers are hidden from `read` / `list` / `stats` / `exists`.
294
+ *
295
+ * Use {@link cow} to construct one.
296
+ */
297
+ var CowFilesApi = class {
298
+ base;
299
+ writable;
300
+ whiteoutPrefix;
301
+ opaqueName;
302
+ constructor(base, writable, opts) {
303
+ this.base = base;
304
+ this.writable = writable;
305
+ this.whiteoutPrefix = opts?.whiteoutPrefix ?? ".wh.";
306
+ this.opaqueName = opts?.opaqueName ?? ".wh..opq";
307
+ }
308
+ whiteoutPath(path) {
309
+ const p = normalizePath(path);
310
+ return joinPath(dirname(p), `${this.whiteoutPrefix}${basename(p)}`);
311
+ }
312
+ opaquePath(dir) {
313
+ return joinPath(normalizePath(dir), this.opaqueName);
314
+ }
315
+ isMarker(name) {
316
+ return name.startsWith(this.whiteoutPrefix) || name === this.opaqueName;
317
+ }
318
+ *ancestorsInclusive(dir) {
319
+ let cur = normalizePath(dir);
320
+ yield cur;
321
+ while (cur !== "/") {
322
+ cur = dirname(cur);
323
+ yield cur;
324
+ }
325
+ }
326
+ async hasDirectWhiteout(path) {
327
+ return this.writable.exists(this.whiteoutPath(path));
328
+ }
329
+ /** True when an opaque marker on `dir` or any ancestor hides base content. */
330
+ async isBaseContentHidden(dir) {
331
+ for (const ancestor of this.ancestorsInclusive(dir)) if (await this.writable.exists(this.opaquePath(ancestor))) return true;
332
+ return false;
333
+ }
334
+ /** True when the base version of `path` is hidden by a marker. */
335
+ async isBaseHidden(path) {
336
+ if (await this.hasDirectWhiteout(path)) return true;
337
+ return this.isBaseContentHidden(dirname(normalizePath(path)));
338
+ }
339
+ async resolveLayer(path) {
340
+ if (await this.writable.exists(path)) return "writable";
341
+ if (await this.isBaseHidden(path)) return "absent";
342
+ if (await this.base.exists(path)) return "base";
343
+ return "absent";
344
+ }
345
+ /** Removes a covering whiteout marker so a write/mkdir resurrects the path. */
346
+ async clearWhiteout(path) {
347
+ const marker = this.whiteoutPath(path);
348
+ if (await this.writable.exists(marker)) await this.writable.remove(marker);
349
+ }
350
+ async *read(path, options) {
351
+ const layer = await this.resolveLayer(path);
352
+ if (layer === "writable") yield* this.writable.read(path, options);
353
+ else if (layer === "base") yield* this.base.read(path, options);
354
+ }
355
+ async write(path, content) {
356
+ await this.clearWhiteout(path);
357
+ await this.writable.write(path, content);
358
+ }
359
+ async mkdir(path) {
360
+ await this.clearWhiteout(path);
361
+ await this.writable.mkdir(path);
362
+ }
363
+ async stats(path) {
364
+ const layer = await this.resolveLayer(path);
365
+ if (layer === "writable") return this.writable.stats(path);
366
+ if (layer === "base") return this.base.stats(path);
367
+ }
368
+ async exists(path) {
369
+ return await this.resolveLayer(path) !== "absent";
370
+ }
371
+ async *list(path, options) {
372
+ yield* this.listDir(normalizePath(path), options?.recursive ?? false);
373
+ }
374
+ async *listDir(dir, recursive) {
375
+ if ((await this.stats(dir))?.kind !== "directory") return;
376
+ for (const entry of await this.mergeChildren(dir)) {
377
+ yield entry;
378
+ if (recursive && entry.kind === "directory") yield* this.listDir(entry.path, true);
379
+ }
380
+ }
381
+ /** Direct children of `dir`: writable entries win, base entries fill in. */
382
+ async mergeChildren(dir) {
383
+ const merged = /* @__PURE__ */ new Map();
384
+ if ((await this.writable.stats(dir))?.kind === "directory") for await (const entry of this.writable.list(dir)) {
385
+ if (this.isMarker(entry.name)) continue;
386
+ merged.set(entry.name, entry);
387
+ }
388
+ if (!await this.isBaseContentHidden(dir) && (await this.base.stats(dir))?.kind === "directory") for await (const entry of this.base.list(dir)) {
389
+ if (merged.has(entry.name)) continue;
390
+ if (await this.hasDirectWhiteout(entry.path)) continue;
391
+ merged.set(entry.name, entry);
392
+ }
393
+ return [...merged.values()];
394
+ }
395
+ async remove(path) {
396
+ if (await this.resolveLayer(path) === "absent") return false;
397
+ if (await this.writable.exists(path)) await this.writable.remove(path);
398
+ const baseStats = await this.base.stats(path);
399
+ if (baseStats) {
400
+ const marker = baseStats.kind === "directory" ? this.opaquePath(path) : this.whiteoutPath(path);
401
+ await this.writable.write(marker, []);
402
+ }
403
+ return true;
404
+ }
405
+ async move(source, target) {
406
+ const stats = await this.stats(source);
407
+ if (!stats) return false;
408
+ await this.copyInto(source, target, stats);
409
+ await this.remove(source);
410
+ return true;
411
+ }
412
+ async copy(source, target) {
413
+ const stats = await this.stats(source);
414
+ if (!stats) return false;
415
+ await this.copyInto(source, target, stats);
416
+ return true;
417
+ }
418
+ /** Copies the composite view of `src` into the writable layer at `tgt`. */
419
+ async copyInto(src, tgt, stats) {
420
+ if (stats.kind === "file") {
421
+ await this.write(tgt, this.read(src));
422
+ return;
423
+ }
424
+ await this.mkdir(tgt);
425
+ for await (const entry of this.list(src)) await this.copyInto(entry.path, joinPath(tgt, entry.name), entry);
426
+ }
427
+ };
428
+ /**
429
+ * Builds a copy-on-write `FilesApi`: a `writable` layer over a read-only
430
+ * `base`. Reads fall through to `base`; every write goes to `writable`;
431
+ * `base` is never mutated. Deletions are persisted as marker files in
432
+ * `writable` (a per-path whiteout for files, one opaque marker for a deleted
433
+ * base directory), so they survive over any backend and across restarts.
434
+ *
435
+ * @param base The read-only lower layer. Never mutated.
436
+ * @param writable The upper layer that captures all changes and markers.
437
+ * @param opts Marker naming overrides (see {@link CowOptions}).
438
+ * @returns A read/write `FilesApi` composing the two layers.
439
+ *
440
+ * @example
441
+ * ```ts
442
+ * const fs = cow(releaseFiles, new MemFilesApi());
443
+ * await fs.write("/a.txt", data); // captured in the writable layer
444
+ * await fs.remove("/base-only"); // whiteout marker; base untouched
445
+ * ```
446
+ */
447
+ function cow(base, writable, opts) {
448
+ return new CowFilesApi(base, writable, opts);
449
+ }
450
+ //#endregion
451
+ //#region src/glob-to-regexp.ts
452
+ /**
453
+ * Compiles a glob pattern into a `RegExp`.
454
+ *
455
+ * @example
456
+ * ```ts
457
+ * globToRegExp("*.js"); // /^.*\.js$/
458
+ * globToRegExp("*.js", { globstar: true }); // /^([^/]*)\.js$/
459
+ * globToRegExp("/foo/**", { globstar: true }) // /^\/foo\/((?:[^/]*(?:\/|$))*)$/
460
+ * globToRegExp("foo{bar,baz}", { extended: true }); // /^foo(bar|baz)$/
461
+ * ```
462
+ */
463
+ function globToRegExp(glob, opts = {}) {
464
+ if (typeof glob !== "string") throw new TypeError("Expected a string");
465
+ const str = String(glob);
466
+ let reStr = "";
467
+ const extended = !!opts.extended;
468
+ const globstar = !!opts.globstar;
469
+ let inGroup = false;
470
+ const flags = typeof opts.flags === "string" ? opts.flags : "";
471
+ for (let i = 0; i < str.length; i++) {
472
+ const c = str[i];
473
+ switch (c) {
474
+ case "/":
475
+ case "$":
476
+ case "^":
477
+ case "+":
478
+ case ".":
479
+ case "(":
480
+ case ")":
481
+ case "=":
482
+ case "!":
483
+ case "|":
484
+ reStr += `\\${c}`;
485
+ break;
486
+ case "?":
487
+ reStr += extended ? "." : `\\${c}`;
488
+ break;
489
+ case "[":
490
+ case "]":
491
+ reStr += extended ? c : `\\${c}`;
492
+ break;
493
+ case "{":
494
+ if (extended) {
495
+ inGroup = true;
496
+ reStr += "(";
497
+ } else reStr += `\\${c}`;
498
+ break;
499
+ case "}":
500
+ if (extended) {
501
+ inGroup = false;
502
+ reStr += ")";
503
+ } else reStr += `\\${c}`;
504
+ break;
505
+ case ",":
506
+ if (inGroup) reStr += "|";
507
+ else reStr += `\\${c}`;
508
+ break;
509
+ case "*": {
510
+ const prevChar = str[i - 1];
511
+ let starCount = 1;
512
+ while (str[i + 1] === "*") {
513
+ starCount++;
514
+ i++;
515
+ }
516
+ const nextChar = str[i + 1];
517
+ if (!globstar) reStr += ".*";
518
+ else if (starCount > 1 && (prevChar === "/" || prevChar === void 0) && (nextChar === "/" || nextChar === void 0)) {
519
+ reStr += "((?:[^/]*(?:\\/|$))*)";
520
+ i++;
521
+ } else reStr += "([^/]*)";
522
+ break;
523
+ }
524
+ default: reStr += c;
525
+ }
526
+ }
527
+ if (!flags?.includes("g")) reStr = `^${reStr}$`;
528
+ return new RegExp(reStr, flags);
529
+ }
530
+ //#endregion
531
+ //#region src/filtered-files-api.ts
532
+ /**
533
+ * Builds a {@link PathFilter} that hides any path whose normalized form
534
+ * equals one of the provided prefixes or lives under `${prefix}/`.
535
+ *
536
+ * Prefixes are normalized through `normalizePath` (so `"foo"`, `"/foo"`, and
537
+ * `"/foo/"` are equivalent). Empty / root entries are dropped — they would
538
+ * otherwise hide every path.
539
+ *
540
+ * Matching is **boundary-aware**: the prefix `"/priv"` does not match the
541
+ * path `"/private"` because there is no `/` boundary between them.
542
+ *
543
+ * @param pathPrefixes Path prefixes whose contents (and the prefix itself)
544
+ * should be hidden. Pass none to hide nothing.
545
+ *
546
+ * @example
547
+ * ```ts
548
+ * const filter = newPathFilter("/.git", "/node_modules");
549
+ * filter("/src/index.ts"); // true
550
+ * filter("/.git"); // false
551
+ * filter("/.git/HEAD"); // false
552
+ * filter("/notgit"); // true (boundary-aware, no false match)
553
+ * ```
554
+ */
555
+ function newPathFilter(...pathPrefixes) {
556
+ const normalized = pathPrefixes.map((p) => normalizePath(p)).filter((p) => p !== "/");
557
+ return (path) => {
558
+ const target = normalizePath(path);
559
+ for (const prefix of normalized) {
560
+ if (target === prefix) return false;
561
+ if (target.startsWith(`${prefix}/`)) return false;
562
+ }
563
+ return true;
564
+ };
565
+ }
566
+ /**
567
+ * Builds a {@link PathFilter} that hides any path whose normalized form
568
+ * matches at least one of the provided regular expressions.
569
+ *
570
+ * The path is normalized through `normalizePath` before matching, so a
571
+ * regexp anchored on `^/` always sees a leading slash and never a trailing
572
+ * one. The regexp's `lastIndex` is irrelevant — the filter calls `test`
573
+ * via a fresh evaluation each time, but stateful (`/g`, `/y`) regexps
574
+ * still mutate `lastIndex` across calls; pass non-stateful regexps unless
575
+ * you know what you are doing.
576
+ *
577
+ * @param pathRegexps Regular expressions whose match means "hide this
578
+ * path". Pass none to hide nothing.
579
+ *
580
+ * @example
581
+ * ```ts
582
+ * // Hide every dotfile and every *.log file
583
+ * const filter = newRegexpPathFilter(/\/\.[^/]+$/, /\.log$/);
584
+ * filter("/src/index.ts"); // true
585
+ * filter("/.env"); // false (matches /\/\.[^/]+$/)
586
+ * filter("/build.log"); // false (matches /\.log$/)
587
+ * ```
588
+ */
589
+ function newRegexpPathFilter(...pathRegexps) {
590
+ return (path) => {
591
+ const target = normalizePath(path);
592
+ for (const regexp of pathRegexps) if (regexp.test(target)) return false;
593
+ return true;
594
+ };
595
+ }
596
+ /**
597
+ * Builds a {@link PathFilter} that hides any path whose normalized form
598
+ * matches at least one of the provided glob patterns.
599
+ *
600
+ * Each glob is compiled with `extended: true` and `globstar: true`, the
601
+ * standard "filesystem-style" mode:
602
+ *
603
+ * - `*` matches any number of characters within a single path segment
604
+ * (does **not** cross `/`).
605
+ * - `**` between slashes matches zero or more whole path segments.
606
+ * - `?` matches exactly one character.
607
+ * - `[abc]` / `[a-z]` matches a single character in the set / range.
608
+ * - `{a,b,c}` matches one of the alternatives.
609
+ *
610
+ * Because matching is done on the **normalized** path (which always starts
611
+ * with `/`), patterns that should match anywhere in the tree need a
612
+ * leading `**​/`, e.g. `**​/*.log` to hide every `.log` file at any depth.
613
+ *
614
+ * Gotcha: `/foo/**` matches descendants of `/foo` but **not** `/foo`
615
+ * itself, because the glob requires a `/` after `foo` before `**` can
616
+ * match. To hide both the directory and its contents, list both prefixes:
617
+ * `newGlobPathFilter("/foo", "/foo/**")`. {@link newPathFilter} doesn't
618
+ * have this problem and may be a better fit for prefix-only hiding.
619
+ *
620
+ * @param pathGlobs Glob patterns whose match means "hide this path". Pass
621
+ * none to hide nothing.
622
+ *
623
+ * @example
624
+ * ```ts
625
+ * const filter = newGlobPathFilter("**​/*.log", "/.git", "/.git/**");
626
+ * filter("/src/index.ts"); // true
627
+ * filter("/build.log"); // false (matches **​/*.log)
628
+ * filter("/.git"); // false (matches /.git)
629
+ * filter("/.git/HEAD"); // false (matches /.git/**)
630
+ * ```
631
+ */
632
+ function newGlobPathFilter(...pathGlobs) {
633
+ return newRegexpPathFilter(...pathGlobs.map((glob) => globToRegExp(glob, {
634
+ extended: true,
635
+ globstar: true
636
+ })));
637
+ }
638
+ /**
639
+ * `FilesApi` decorator that hides every path the supplied {@link PathFilter}
640
+ * rejects. Hidden paths are treated as if they do not exist:
641
+ *
642
+ * - `read` / `list` yield empty iterables.
643
+ * - `stats` returns `undefined`; `exists` returns `false`.
644
+ * - `remove` returns `false` (no error, nothing changed).
645
+ * - `move` / `copy` return `false` if either endpoint is hidden.
646
+ * - `write` / `mkdir` reject with an `Error` (since silently dropping a
647
+ * write would lose data).
648
+ * - `list` recursively skips entries whose paths are hidden, so iterating a
649
+ * visible parent never reveals a hidden child.
650
+ *
651
+ * Wrap any `FilesApi` to scope its visibility without changing the
652
+ * underlying storage; the wrapped instance still holds the data, it is just
653
+ * not reachable through this decorator.
654
+ *
655
+ * Pair with one of the built-in {@link PathFilter} factories
656
+ * ({@link newPathFilter}, {@link newRegexpPathFilter},
657
+ * {@link newGlobPathFilter}) or pass any predicate of shape
658
+ * `(path) => boolean | Promise<boolean>`.
659
+ *
660
+ * @example
661
+ * ```ts
662
+ * import {
663
+ * FilteredFilesApi,
664
+ * newGlobPathFilter,
665
+ * newPathFilter,
666
+ * newRegexpPathFilter,
667
+ * } from "@statewalker/webrun-files-composite";
668
+ *
669
+ * // Hide by path prefix
670
+ * const noVcs = new FilteredFilesApi(sourceFiles, newPathFilter("/.git", "/.cache"));
671
+ * await noVcs.exists("/.git"); // false
672
+ * await noVcs.write("/.git/x", data); // throws "Path is hidden"
673
+ *
674
+ * // Hide by regexp
675
+ * const noLogs = new FilteredFilesApi(sourceFiles, newRegexpPathFilter(/\.log$/));
676
+ *
677
+ * // Hide by glob (extended + globstar mode)
678
+ * const noJunk = new FilteredFilesApi(
679
+ * sourceFiles,
680
+ * newGlobPathFilter("**​/*.log", "/.git", "/.git/**"),
681
+ * );
682
+ * ```
683
+ */
684
+ var FilteredFilesApi = class {
685
+ source;
686
+ pathFilter;
687
+ /**
688
+ * @param source The underlying `FilesApi` whose paths will be selectively
689
+ * hidden. Operations always delegate to this instance; the decorator
690
+ * only adds the visibility check.
691
+ * @param pathFilter Predicate that decides per-call whether a normalized
692
+ * path is visible. See {@link PathFilter}.
693
+ */
694
+ constructor(source, pathFilter) {
695
+ this.source = source;
696
+ this.pathFilter = pathFilter;
697
+ }
698
+ async isHidden(path) {
699
+ return await this.pathFilter(normalizePath(path)) === false;
700
+ }
701
+ async *read(path, options) {
702
+ if (await this.isHidden(path)) return;
703
+ yield* this.source.read(path, options);
704
+ }
705
+ async write(path, content) {
706
+ if (await this.isHidden(path)) throw new Error(`Path is hidden: ${path}`);
707
+ await this.source.write(path, content);
708
+ }
709
+ async mkdir(path) {
710
+ if (await this.isHidden(path)) throw new Error(`Path is hidden: ${path}`);
711
+ await this.source.mkdir(path);
712
+ }
713
+ async *list(path, options) {
714
+ if (await this.isHidden(path)) return;
715
+ for await (const entry of this.source.list(path, options)) {
716
+ if (await this.isHidden(entry.path)) continue;
717
+ yield entry;
718
+ }
719
+ }
720
+ async stats(path) {
721
+ if (await this.isHidden(path)) return void 0;
722
+ return this.source.stats(path);
723
+ }
724
+ async exists(path) {
725
+ if (await this.isHidden(path)) return false;
726
+ return this.source.exists(path);
727
+ }
728
+ async remove(path) {
729
+ if (await this.isHidden(path)) return false;
730
+ return this.source.remove(path);
731
+ }
732
+ async move(source, target) {
733
+ if (await this.isHidden(source) || await this.isHidden(target)) return false;
734
+ return this.source.move(source, target);
735
+ }
736
+ async copy(source, target) {
737
+ if (await this.isHidden(source) || await this.isHidden(target)) return false;
738
+ return this.source.copy(source, target);
739
+ }
740
+ };
741
+ //#endregion
742
+ //#region src/guarded-files-api.ts
743
+ /**
744
+ * `FilesApi` decorator that runs every call through an ordered list of
745
+ * {@link FileGuard}s. A guard fires when its `operations` set intersects the
746
+ * effective operation(s) for the current call. The first guard whose
747
+ * `check` returns `false` aborts the call by throwing an `Error` with that
748
+ * guard's `message` (defaulting to `"Access denied"`) followed by the
749
+ * normalized path.
750
+ *
751
+ * Effective operations per call:
752
+ *
753
+ * | Method | Operations checked |
754
+ * | ------------- | --------------------------------------------------- |
755
+ * | `read` | `read` |
756
+ * | `write` | `write` |
757
+ * | `mkdir` | `mkdir` |
758
+ * | `remove` | `remove` |
759
+ * | `list` | `list` on the path AND on each directory entry |
760
+ * | `stats` | `list` (a stat reveals existence like a tiny list) |
761
+ * | `exists` | `read` (existence is a read of metadata) |
762
+ * | `move(s, t)` | `move`+`read` on source; `move`+`write` on target |
763
+ * | `copy(s, t)` | `copy`+`read` on source; `copy`+`write` on target |
764
+ *
765
+ * The expanded checks for `move`/`copy` mean a guard that blocks `read` on
766
+ * a path also prevents move/copy *from* that path, and a `write`-blocking
767
+ * guard prevents move/copy *to* it. Likewise, an `exists` call respects any
768
+ * read guard, and `stats` respects any list guard.
769
+ *
770
+ * @example
771
+ * ```ts
772
+ * const api = new GuardedFilesApi(source, [
773
+ * {
774
+ * operations: ["write", "remove", "move", "mkdir"],
775
+ * check: (p) => !p.startsWith("/.system/"),
776
+ * message: "system folder is read-only",
777
+ * },
778
+ * ]);
779
+ * await api.write("/.system/cfg", data); // throws "system folder is read-only: /.system/cfg"
780
+ * ```
781
+ */
782
+ var GuardedFilesApi = class {
783
+ source;
784
+ guards;
785
+ /**
786
+ * @param source The underlying `FilesApi` whose calls will be policed.
787
+ * Allowed operations delegate straight through.
788
+ * @param guards Ordered list of access policies. The wrapper takes a
789
+ * defensive copy, so mutating the array afterwards has no effect.
790
+ * An empty list disables every check (the wrapper becomes a passthrough).
791
+ */
792
+ constructor(source, guards) {
793
+ this.source = source;
794
+ this.guards = [...guards];
795
+ }
796
+ checkGuard(path, ...operations) {
797
+ const normalized = normalizePath(path);
798
+ for (const guard of this.guards) {
799
+ if (!operations.some((op) => guard.operations.includes(op))) continue;
800
+ if (!guard.check(normalized)) {
801
+ const msg = guard.message ?? "Access denied";
802
+ throw new Error(`${msg}: ${normalized}`);
803
+ }
804
+ }
805
+ }
806
+ read(path, options) {
807
+ this.checkGuard(path, "read");
808
+ return this.source.read(path, options);
809
+ }
810
+ async write(path, content) {
811
+ this.checkGuard(path, "write");
812
+ return this.source.write(path, content);
813
+ }
814
+ async mkdir(path) {
815
+ this.checkGuard(path, "mkdir");
816
+ return this.source.mkdir(path);
817
+ }
818
+ async *list(path, options) {
819
+ this.checkGuard(path, "list");
820
+ for await (const info of this.source.list(path, options)) {
821
+ if (info.kind === "directory") this.checkGuard(info.path, "list");
822
+ yield info;
823
+ }
824
+ }
825
+ stats(path) {
826
+ this.checkGuard(path, "list");
827
+ return this.source.stats(path);
828
+ }
829
+ exists(path) {
830
+ this.checkGuard(path, "read");
831
+ return this.source.exists(path);
832
+ }
833
+ async remove(path) {
834
+ this.checkGuard(path, "remove");
835
+ return this.source.remove(path);
836
+ }
837
+ async move(source, target) {
838
+ this.checkGuard(source, "move", "read");
839
+ this.checkGuard(target, "move", "write");
840
+ return this.source.move(source, target);
841
+ }
842
+ async copy(source, target) {
843
+ this.checkGuard(source, "copy", "read");
844
+ this.checkGuard(target, "copy", "write");
845
+ return this.source.copy(source, target);
846
+ }
847
+ };
848
+ //#endregion
849
+ //#region src/overlay-files-api.ts
850
+ /**
851
+ * Read-only union of several `FilesApi` layers. A path is resolved
852
+ * **top → bottom**: the first layer that has it wins for
853
+ * `read` / `stats` / `exists`, and its entry (including `kind`) wins any
854
+ * name clash in `list`. Listings merge and dedupe across every layer.
855
+ *
856
+ * The union never writes — every mutating call throws. Use
857
+ * {@link overlay} to construct one.
858
+ */
859
+ var OverlayFilesApi = class {
860
+ layers;
861
+ constructor(layers) {
862
+ this.layers = layers;
863
+ }
864
+ deny(op, path) {
865
+ throw new Error(`overlay is read-only (${op}): ${normalizePath(path)}`);
866
+ }
867
+ async *read(path, options) {
868
+ for (const layer of this.layers) if (await layer.exists(path)) {
869
+ yield* layer.read(path, options);
870
+ return;
871
+ }
872
+ }
873
+ async stats(path) {
874
+ for (const layer of this.layers) {
875
+ const stats = await layer.stats(path);
876
+ if (stats) return stats;
877
+ }
878
+ }
879
+ async exists(path) {
880
+ for (const layer of this.layers) if (await layer.exists(path)) return true;
881
+ return false;
882
+ }
883
+ async *list(path, options) {
884
+ yield* this.listDir(normalizePath(path), options?.recursive ?? false);
885
+ }
886
+ async *listDir(dir, recursive) {
887
+ if ((await this.stats(dir))?.kind !== "directory") return;
888
+ for (const entry of await this.mergeChildren(dir)) {
889
+ yield entry;
890
+ if (recursive && entry.kind === "directory") yield* this.listDir(entry.path, true);
891
+ }
892
+ }
893
+ /** Direct children of `dir`, deduped by name with the topmost layer winning. */
894
+ async mergeChildren(dir) {
895
+ const merged = /* @__PURE__ */ new Map();
896
+ for (const layer of this.layers) {
897
+ if ((await layer.stats(dir))?.kind !== "directory") continue;
898
+ for await (const entry of layer.list(dir)) if (!merged.has(entry.name)) merged.set(entry.name, entry);
899
+ }
900
+ return [...merged.values()];
901
+ }
902
+ async write(path) {
903
+ this.deny("write", path);
904
+ }
905
+ async mkdir(path) {
906
+ this.deny("mkdir", path);
907
+ }
908
+ async remove(path) {
909
+ return this.deny("remove", path);
910
+ }
911
+ async move(source) {
912
+ return this.deny("move", source);
913
+ }
914
+ async copy(source) {
915
+ return this.deny("copy", source);
916
+ }
917
+ };
918
+ /**
919
+ * Builds a **read-only** union view over `top` and any number of `lower`
920
+ * layers. Reads resolve top → bottom (first layer that has the path wins);
921
+ * `list` merges and dedupes across all layers with `top` winning a clash
922
+ * (including a file-vs-directory `kind` clash). Every write is denied.
923
+ *
924
+ * @param top The highest-priority layer; its entries shadow the rest.
925
+ * @param lower Additional layers, consulted in order after `top`.
926
+ * @returns A read-only `FilesApi` union.
927
+ *
928
+ * @example
929
+ * ```ts
930
+ * const view = overlay(userFiles, defaultFiles);
931
+ * await view.read("/config.json"); // userFiles if present, else defaultFiles
932
+ * await view.write("/x", data); // throws (read-only)
933
+ * ```
934
+ */
935
+ function overlay(top, ...lower) {
936
+ return new OverlayFilesApi([top, ...lower]);
937
+ }
938
+ //#endregion
939
+ //#region src/read-only-files-api.ts
940
+ /**
941
+ * Wraps a `FilesApi` in a read-only view: every mutating operation
942
+ * (`write`, `mkdir`, `remove`, `move`, `copy`) throws, while reads
943
+ * (`read`, `list`, `stats`, `exists`) pass straight through to `api`.
944
+ *
945
+ * Implemented as a {@link GuardedFilesApi} with a single deny-all guard on
946
+ * the mutating operations, so `move`/`copy` are blocked on either endpoint.
947
+ *
948
+ * @param api The underlying `FilesApi` to expose read-only.
949
+ * @returns A `FilesApi` that never mutates `api`.
950
+ *
951
+ * @example
952
+ * ```ts
953
+ * const ro = readOnly(sourceFiles);
954
+ * await ro.read("/a.txt"); // ok
955
+ * await ro.write("/a.txt", data); // throws "read-only: /a.txt"
956
+ * ```
957
+ */
958
+ function readOnly(api) {
959
+ return new GuardedFilesApi(api, [{
960
+ operations: [
961
+ "write",
962
+ "mkdir",
963
+ "remove",
964
+ "move",
965
+ "copy"
966
+ ],
967
+ check: () => false,
968
+ message: "read-only"
969
+ }]);
970
+ }
971
+ //#endregion
239
972
  exports.CompositeFilesApi = CompositeFilesApi;
973
+ exports.FilteredFilesApi = FilteredFilesApi;
974
+ exports.GuardedFilesApi = GuardedFilesApi;
975
+ exports.cow = cow;
976
+ exports.globToRegExp = globToRegExp;
977
+ exports.newGlobPathFilter = newGlobPathFilter;
978
+ exports.newPathFilter = newPathFilter;
979
+ exports.newRegexpPathFilter = newRegexpPathFilter;
980
+ exports.overlay = overlay;
981
+ exports.readOnly = readOnly;