@williamthorsen/toolbelt.filesystem 0.6.0 → 0.8.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## 0.8.0 — 2026-08-24
6
+
7
+ ### Features
8
+
9
+ - Add a recursive listFiles to createTempTree's entry API (#212)
10
+
11
+ Adds `listFiles` to the handle `createTempTree` returns in `@williamthorsen/toolbelt.filesystem/candidate`. It reports every file below a tree-relative directory, at any depth, as sorted `/`-separated paths relative to that directory, whereas `list` reaches one level and reports names alone. A symlink below that directory is neither named nor descended, so every path in the result names a file held inside the tree.
12
+
13
+ ## 0.7.0 — 2026-08-21
14
+
15
+ ### Features
16
+
17
+ - 🚨 **Breaking:** Fix createTempTree's symlink guard and disposal, and complete its entry API (#207)
18
+
19
+ Fixes an issue where `TempTree.symlink` in `@williamthorsen/toolbelt.filesystem/candidate` refused a target outside the tree and rewrote a relative target to an absolute path inside it. The containment check now applies to the link path alone and the target is stored as given, so a link reads back as the string that was passed.
20
+
21
+ Separately, fixes an issue where disposing a `TempTree` left the tree on disk when one of its directories had been made read-only.
22
+
23
+ Adds six methods to `TempTree`. `writeAll` applies the constructor's map of entries to a tree already built; `exists`, `list`, `read`, `readJson`, and `rm` read the tree back and remove from it, so a suite scaffolding through the handle reads its own fixture through it rather than reaching for `node:fs`.
24
+
25
+ Migration: A caller relying on the previous absolute storage passes `tree.resolve(target)`, which is written unchanged.
26
+
5
27
  ## 0.6.0 — 2026-08-16
6
28
 
7
29
  ### Features
package/README.md CHANGED
@@ -3,13 +3,13 @@
3
3
  Filesystem utilities for TypeScript and JavaScript.
4
4
 
5
5
  <!-- section:release-notes -->
6
- ## Release notes — v0.6.0 (2026-08-16)
6
+ ## Release notes — v0.8.0 (2026-08-24)
7
7
 
8
8
  ### Features
9
9
 
10
- - Add mkdir, symlink, write, and writeJson methods to `TempTree` (#176)
10
+ - Add a recursive listFiles to createTempTree's entry API (#212)
11
11
 
12
- Adds four write methods to `TempTree` in `@williamthorsen/toolbelt.filesystem`: `mkdir`, `symlink`, `write`, and `writeJson`. Each takes a tree-relative path, creates the parent directories it needs, resolves through the same containment check `resolve` applies, and returns the absolute path, so a suite writing into a built temporary tree reaches it through the handle rather than through `node:fs`. `symlink` accepts a link path and a target, and picks the link type from the target.
12
+ Adds `listFiles` to the handle `createTempTree` returns in `@williamthorsen/toolbelt.filesystem/candidate`. It reports every file below a tree-relative directory, at any depth, as sorted `/`-separated paths relative to that directory, whereas `list` reaches one level and reports names alone. A symlink below that directory is neither named nor descended, so every path in the result names a file held inside the tree.
13
13
  <!-- /section:release-notes -->
14
14
 
15
15
  ## Installation
@@ -292,10 +292,17 @@ A prefix that would place the tree anywhere but directly inside the system tempo
292
292
  ```ts
293
293
  interface TempTree extends Disposable {
294
294
  readonly dir: string;
295
+ exists(entryPath: string): boolean;
296
+ list(entryPath?: string): string[];
297
+ listFiles(entryPath?: string): string[];
295
298
  mkdir(entryPath: string): string;
299
+ read(entryPath: string): string;
300
+ readJson(entryPath: string): unknown;
296
301
  resolve(...segments: string[]): string;
302
+ rm(entryPath: string): void;
297
303
  symlink(linkPath: string, targetPath: string): string;
298
304
  write(entryPath: string, contents: string | Uint8Array): string;
305
+ writeAll(entries: Record<string, string | Uint8Array>): void;
299
306
  writeJson(entryPath: string, value: unknown): string;
300
307
  }
301
308
  ```
@@ -304,7 +311,7 @@ interface TempTree extends Disposable {
304
311
 
305
312
  `resolve` joins `segments` against the root and throws when the result would fall outside it, so a stray `..` fails loudly rather than reaching into the enclosing directory. An absolute segment landing inside the root is returned unchanged. The containment test is lexical, so it does not follow a symlink inside the tree that points out of it.
306
313
 
307
- `mkdir`, `symlink`, `write`, and `writeJson` write into the tree after it is built, for a fixture that varies per test or a file created to trigger a re-read:
314
+ `mkdir`, `symlink`, `write`, `writeAll`, and `writeJson` write into the tree after it is built, for a fixture that varies per test or a file created to trigger a re-read:
308
315
 
309
316
  ```ts
310
317
  using tree = createTempTree({ 'packages/app/package.json': '{ "name": "app" }' });
@@ -314,23 +321,50 @@ tree.writeJson('tsconfig.json', { include: ['src'] });
314
321
  tree.mkdir('packages/empty');
315
322
  ```
316
323
 
317
- Each creates the parent directories it needs, resolves through the same containment check as `resolve`, and returns the absolute path of what it wrote. Both of `symlink`'s paths are checked, so an escaping target is refused as well as an escaping link.
324
+ Each creates the parent directories it needs, resolves through the same containment check as `resolve`, and returns the absolute path of what it wrote. `symlink`'s link path is checked; its target is not, being a string the link holds rather than a location the tree writes to.
325
+
326
+ `writeAll` takes the same map the constructor takes, `/`-suffix convention included, so a fixture built in one call can be added to in one call:
327
+
328
+ ```ts
329
+ tree.writeAll({ 'packages/empty/': '', 'packages/app/src/main.ts': 'export {};\n' });
330
+ ```
331
+
332
+ It returns nothing, there being no single path to return, and unlike the constructor it is not atomic: a failure part-way leaves the entries already written in place, there being no whole tree to discard.
318
333
 
319
334
  They part company on an entry that already exists: `write` replaces it, `mkdir` leaves it and its contents alone, and `symlink` raises `EEXIST`.
320
335
 
321
- `symlink` takes the link first and the target second, inverting `fs.symlinkSync`, so that it reads like the other methods: the path being created leads. The link type is chosen from the target, which is where the one portability difference lives. A directory is linked as a junction, which Windows creates without the elevation a directory symlink needs; every other target, one that does not exist included, is linked as a file. That last case matches what Node falls back to when no type is given, and it leaves the link dangling until the target appears.
336
+ `symlink` takes the link first and the target second, inverting `fs.symlinkSync`, so that it reads like the other methods: the path being created leads. The target is stored verbatim, so it may be absolute or relative, name something outside the tree, or dangle until the target appears; a relative one resolves against the link's own directory, as POSIX resolves it. Code under test that reads a link rather than following it therefore sees the string that was passed, which is what a consumer hashing a link's target depends on.
322
337
 
323
338
  ```ts
324
339
  using tree = createTempTree({ 'store/kit/package.json': '{ "name": "kit" }' });
325
340
 
326
- tree.symlink('node_modules/kit', 'store/kit'); // a junction, so Windows needs no elevation
341
+ tree.symlink('node_modules/kit', '../store/kit'); // reads back as '../store/kit'
342
+ tree.symlink('node_modules/.bin', tree.resolve('store/kit/bin')); // reads back absolute
327
343
  ```
328
344
 
329
- The link stores an absolute path, which a junction requires. Code under test that reads a link rather than following it therefore sees a path under the tree root, where a package manager would have written a relative one; a fixture reproducing that shape reaches for `fs.symlinkSync` directly.
345
+ The link type is chosen from the target, which is where the one portability difference lives. An absolute directory target is linked as a junction, which Windows creates without the elevation a directory symlink needs; a relative directory target is linked as a directory, which needs that elevation, because Node normalizes a junction's target to an absolute path and would discard the relative string. Every other target, one that does not exist included, is linked as a file, matching what Node falls back to when no type is given.
346
+
347
+ `exists`, `list`, `listFiles`, `read`, `readJson`, and `rm` read the tree back and remove from it, each through the same containment check:
348
+
349
+ ```ts
350
+ using tree = createTempTree({ 'packages/app/package.json': '{ "name": "app" }', 'packages/app/src/main.ts': 'export {};\n' });
351
+
352
+ tree.list(); // ['packages'], defaulting to the tree root
353
+ tree.list('packages/app'); // ['package.json', 'src'], sorted
354
+ tree.listFiles('packages'); // ['app/package.json', 'app/src/main.ts'], at any depth
355
+ tree.read('packages/app/src/main.ts'); // 'export {};\n'
356
+ tree.readJson('packages/app/package.json'); // unknown, for the caller to narrow
357
+ tree.exists('packages/app/tsconfig.json'); // false
358
+ tree.rm('packages/app');
359
+ ```
360
+
361
+ `listFiles` reaches every depth and reports paths relative to the directory it was given, sorted, with `/` as the separator on every platform: a path a test asserts on is a value rather than a location, so `'app/src/main.ts'` should not vary by platform. It parts from `list` twice. A directory that is not there answers `[]` where `list` raises `ENOENT`, which is what lets a suite assert that a build emitted nothing without guarding the call; a path that exists as a file still raises `ENOTDIR`, as `list` does. And a symlink below the directory it was given is neither named nor descended, so every path in the result names a file held inside the tree, where `list` reports a link by name at its own level. The directory given as the argument is the exception, followed as `list`, `read`, and `exists` follow theirs: one naming a link out of the tree lists the target's files.
362
+
363
+ `read` returns UTF-8 text, and a missing entry raises `ENOENT` rather than answering emptily -- `exists` is the check. `readJson` returns `unknown`, so a caller narrows it rather than trusting an asserted type; contents that do not parse raise an error naming the entry, which the parse error alone does not. `exists` follows a symlink, so a dangling one answers `false`. `rm` is recursive and silent on an entry that is not there.
330
364
 
331
365
  `writeJson` writes two-space-indented JSON ending in a newline, so a tree outliving a crashed run reads as a real config file would. A fixture needing exact bytes goes through `write` instead. A value `JSON.stringify` cannot represent -- `undefined`, a function, a symbol -- is refused rather than written, so an optional binding that arrived empty fails at the call that passed it instead of surfacing later as a parse error.
332
366
 
333
- Disposal is idempotent.
367
+ Disposal is idempotent, and it removes a tree that has been made unwritable: unlinking an entry needs write permission on the directory containing it, so disposal restores permission across the tree and retries once before giving up. A suite that chmods a directory to exercise a write-failure path therefore needs no wrapper to chmod it back.
334
368
 
335
369
  `Disposable` is declared in `lib.esnext.disposable.d.ts` alone, so consuming this export requires `ESNext.Disposable` in your `lib`.
336
370
 
@@ -4,9 +4,16 @@ export interface CreateTempTreeOptions {
4
4
  }
5
5
  export interface TempTree extends Disposable {
6
6
  readonly dir: string;
7
+ exists(entryPath: string): boolean;
8
+ list(entryPath?: string): string[];
9
+ listFiles(entryPath?: string): string[];
7
10
  mkdir(entryPath: string): string;
11
+ read(entryPath: string): string;
12
+ readJson(entryPath: string): unknown;
8
13
  resolve(...segments: string[]): string;
14
+ rm(entryPath: string): void;
9
15
  symlink(linkPath: string, targetPath: string): string;
10
16
  write(entryPath: string, contents: string | Uint8Array): string;
17
+ writeAll(entries: Record<string, string | Uint8Array>): void;
11
18
  writeJson(entryPath: string, value: unknown): string;
12
19
  }
@@ -6,32 +6,51 @@ export function createTempTree(entries, options = {}) {
6
6
  assertNamesDirectChild(prefix);
7
7
  const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));
8
8
  try {
9
- for (const [entry, contents] of Object.entries(entries)) {
10
- if (entry.endsWith('/')) {
11
- mkdir(entry);
12
- }
13
- else {
14
- write(entry, contents);
15
- }
16
- }
9
+ writeAll(entries);
17
10
  }
18
11
  catch (error) {
19
12
  fs.rmSync(dir, { force: true, recursive: true });
20
13
  throw error;
21
14
  }
15
+ function exists(entryPath) {
16
+ return fs.existsSync(resolveWithinTree(dir, [entryPath]));
17
+ }
18
+ function list(entryPath = '') {
19
+ return fs.readdirSync(resolveWithinTree(dir, [entryPath])).toSorted();
20
+ }
21
+ function listFiles(entryPath = '') {
22
+ const rootPath = resolveWithinTree(dir, [entryPath]);
23
+ if (!fs.existsSync(rootPath))
24
+ return [];
25
+ return listFilesBelow(rootPath, '').toSorted();
26
+ }
22
27
  function mkdir(entryPath) {
23
28
  const absolutePath = resolveWithinTree(dir, [entryPath]);
24
29
  fs.mkdirSync(absolutePath, { recursive: true });
25
30
  return absolutePath;
26
31
  }
32
+ function read(entryPath) {
33
+ return fs.readFileSync(resolveWithinTree(dir, [entryPath]), 'utf8');
34
+ }
35
+ function readJson(entryPath) {
36
+ const contents = read(entryPath);
37
+ try {
38
+ return JSON.parse(contents);
39
+ }
40
+ catch (error) {
41
+ throw new Error(`Entry "${entryPath}" is not readable as JSON`, { cause: error });
42
+ }
43
+ }
27
44
  function resolve(...segments) {
28
45
  return resolveWithinTree(dir, segments);
29
46
  }
47
+ function rm(entryPath) {
48
+ fs.rmSync(resolveWithinTree(dir, [entryPath]), { force: true, recursive: true });
49
+ }
30
50
  function symlink(linkPath, targetPath) {
31
51
  const absoluteLink = resolveWithinTree(dir, [linkPath]);
32
- const absoluteTarget = resolveWithinTree(dir, [targetPath]);
33
52
  fs.mkdirSync(path.dirname(absoluteLink), { recursive: true });
34
- fs.symlinkSync(absoluteTarget, absoluteLink, chooseLinkType(absoluteTarget));
53
+ fs.symlinkSync(targetPath, absoluteLink, chooseLinkType(absoluteLink, targetPath));
35
54
  return absoluteLink;
36
55
  }
37
56
  function write(entryPath, contents) {
@@ -40,6 +59,16 @@ export function createTempTree(entries, options = {}) {
40
59
  fs.writeFileSync(absolutePath, contents);
41
60
  return absolutePath;
42
61
  }
62
+ function writeAll(newEntries) {
63
+ for (const [entry, contents] of Object.entries(newEntries)) {
64
+ if (entry.endsWith('/')) {
65
+ mkdir(entry);
66
+ }
67
+ else {
68
+ write(entry, contents);
69
+ }
70
+ }
71
+ }
43
72
  function writeJson(entryPath, value) {
44
73
  const json = JSON.stringify(value, null, 2);
45
74
  if (json === undefined) {
@@ -49,13 +78,26 @@ export function createTempTree(entries, options = {}) {
49
78
  }
50
79
  return {
51
80
  dir,
81
+ exists,
82
+ list,
83
+ listFiles,
52
84
  mkdir,
85
+ read,
86
+ readJson,
53
87
  resolve,
88
+ rm,
54
89
  symlink,
55
90
  write,
91
+ writeAll,
56
92
  writeJson,
57
93
  [Symbol.dispose]() {
58
- fs.rmSync(dir, { force: true, recursive: true });
94
+ try {
95
+ fs.rmSync(dir, { force: true, recursive: true });
96
+ }
97
+ catch {
98
+ restoreDirectoryPermissions(dir);
99
+ fs.rmSync(dir, { force: true, recursive: true });
100
+ }
59
101
  },
60
102
  };
61
103
  }
@@ -67,8 +109,35 @@ function assertNamesDirectChild(prefix) {
67
109
  throw new Error(`Temporary-directory prefix "${prefix}" names no new directory`);
68
110
  }
69
111
  }
70
- function chooseLinkType(targetPath) {
71
- return fs.statSync(targetPath, { throwIfNoEntry: false })?.isDirectory() === true ? 'junction' : 'file';
112
+ function chooseLinkType(absoluteLinkPath, targetPath) {
113
+ const resolvedTarget = path.resolve(path.dirname(absoluteLinkPath), targetPath);
114
+ if (fs.statSync(resolvedTarget, { throwIfNoEntry: false })?.isDirectory() !== true) {
115
+ return 'file';
116
+ }
117
+ return path.isAbsolute(targetPath) ? 'junction' : 'dir';
118
+ }
119
+ function listFilesBelow(dir, prefix) {
120
+ const paths = [];
121
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
122
+ for (const entry of entries) {
123
+ const relativePath = `${prefix}${entry.name}`;
124
+ if (entry.isFile()) {
125
+ paths.push(relativePath);
126
+ }
127
+ else if (entry.isDirectory()) {
128
+ paths.push(...listFilesBelow(path.join(dir, entry.name), `${relativePath}/`));
129
+ }
130
+ }
131
+ return paths;
132
+ }
133
+ function restoreDirectoryPermissions(dir) {
134
+ fs.chmodSync(dir, 0o700);
135
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
136
+ for (const entry of entries) {
137
+ if (entry.isDirectory()) {
138
+ restoreDirectoryPermissions(path.join(dir, entry.name));
139
+ }
140
+ }
72
141
  }
73
142
  function resolveWithinTree(dir, segments) {
74
143
  const target = path.resolve(dir, ...segments);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@williamthorsen/toolbelt.filesystem",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Filesystem utilities",
5
5
  "keywords": [
6
6
  "config-cascade",
@@ -44,7 +44,7 @@
44
44
  "CHANGELOG.md"
45
45
  ],
46
46
  "dependencies": {
47
- "@williamthorsen/toolbelt.errors": "0.5.0"
47
+ "@williamthorsen/toolbelt.errors": "0.6.1"
48
48
  },
49
49
  "engines": {
50
50
  "node": ">=24.0.0"