farna-bootstrapper 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +30 -0
  3. package/NOTICE +42 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +65 -0
  6. package/dist/cli/commands/check.d.ts +58 -0
  7. package/dist/cli/commands/check.js +198 -0
  8. package/dist/cli/commands/generate.d.ts +75 -0
  9. package/dist/cli/commands/generate.js +218 -0
  10. package/dist/cli/commands/init.d.ts +52 -0
  11. package/dist/cli/commands/init.js +271 -0
  12. package/dist/cli/main.d.ts +2 -0
  13. package/dist/cli/main.js +51 -0
  14. package/dist/cli/program.d.ts +23 -0
  15. package/dist/cli/program.js +183 -0
  16. package/dist/compose/resolve.d.ts +154 -0
  17. package/dist/compose/resolve.js +545 -0
  18. package/dist/config/load.d.ts +4 -0
  19. package/dist/config/load.js +45 -0
  20. package/dist/config/schema.d.ts +22 -0
  21. package/dist/config/schema.js +46 -0
  22. package/dist/core/constants.d.ts +268 -0
  23. package/dist/core/constants.js +336 -0
  24. package/dist/core/errors.d.ts +44 -0
  25. package/dist/core/errors.js +75 -0
  26. package/dist/core/fs.d.ts +31 -0
  27. package/dist/core/fs.js +169 -0
  28. package/dist/core/json.d.ts +22 -0
  29. package/dist/core/json.js +174 -0
  30. package/dist/core/paths.d.ts +45 -0
  31. package/dist/core/paths.js +110 -0
  32. package/dist/core/text.d.ts +10 -0
  33. package/dist/core/text.js +27 -0
  34. package/dist/index.d.ts +10 -0
  35. package/dist/index.js +1 -0
  36. package/dist/lock/lockfile.d.ts +229 -0
  37. package/dist/lock/lockfile.js +333 -0
  38. package/dist/materialise/source-tree.d.ts +77 -0
  39. package/dist/materialise/source-tree.js +264 -0
  40. package/dist/permissions/permissions.d.ts +128 -0
  41. package/dist/permissions/permissions.js +452 -0
  42. package/dist/render/commit.d.ts +59 -0
  43. package/dist/render/commit.js +279 -0
  44. package/dist/render/generate-lock.d.ts +9 -0
  45. package/dist/render/generate-lock.js +203 -0
  46. package/dist/render/identity.d.ts +23 -0
  47. package/dist/render/identity.js +396 -0
  48. package/dist/render/orphans.d.ts +59 -0
  49. package/dist/render/orphans.js +234 -0
  50. package/dist/render/port.d.ts +96 -0
  51. package/dist/render/port.js +1 -0
  52. package/dist/render/prepare.d.ts +33 -0
  53. package/dist/render/prepare.js +139 -0
  54. package/dist/render/root-cleanliness.d.ts +28 -0
  55. package/dist/render/root-cleanliness.js +76 -0
  56. package/dist/render/stage.d.ts +36 -0
  57. package/dist/render/stage.js +92 -0
  58. package/dist/render/staging.d.ts +16 -0
  59. package/dist/render/staging.js +94 -0
  60. package/dist/render/structured.d.ts +35 -0
  61. package/dist/render/structured.js +258 -0
  62. package/dist/render/upstream.d.ts +41 -0
  63. package/dist/render/upstream.js +179 -0
  64. package/dist/report/format.d.ts +7 -0
  65. package/dist/report/format.js +97 -0
  66. package/dist/report/warnings.d.ts +21 -0
  67. package/dist/report/warnings.js +24 -0
  68. package/dist/source/digest.d.ts +18 -0
  69. package/dist/source/digest.js +77 -0
  70. package/dist/source/frontmatter.d.ts +12 -0
  71. package/dist/source/frontmatter.js +29 -0
  72. package/dist/source/load.d.ts +103 -0
  73. package/dist/source/load.js +676 -0
  74. package/dist/source/schema.d.ts +149 -0
  75. package/dist/source/schema.js +283 -0
  76. package/dist/source/yaml.d.ts +10 -0
  77. package/dist/source/yaml.js +49 -0
  78. package/dist/verify/containment.d.ts +22 -0
  79. package/dist/verify/containment.js +753 -0
  80. package/package.json +79 -4
@@ -0,0 +1,396 @@
1
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { LOCKFILE_MAX_BYTES, NPM_LOCKFILE_MAX_BYTES, PRODUCT_NAME } from '../core/constants.js';
5
+ import { FarnaError, rendererMismatch } from '../core/errors.js';
6
+ /**
7
+ * The renderer that actually ran. The values are read from the installed
8
+ * package, never copied from a compiled-in literal: the lockfile's renderer
9
+ * record must describe the bytes that produced the committed artefacts.
10
+ */
11
+ const requireFromHere = createRequire(import.meta.url);
12
+ /**
13
+ * Read a JSON file best-effort. An absent, unreadable, oversized or malformed
14
+ * file yields `undefined`, because this is used for `package.json` metadata the
15
+ * caller reports as a typed refusal itself. Lock records are read through
16
+ * `readLockRecord`, which never treats a present record as absent.
17
+ */
18
+ function readJson(path) {
19
+ let fd;
20
+ try {
21
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
22
+ const stats = fstatSync(fd);
23
+ if (!stats.isFile() || stats.size > LOCKFILE_MAX_BYTES) {
24
+ return undefined;
25
+ }
26
+ const value = JSON.parse(readFileSync(fd, 'utf8'));
27
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
28
+ ? value
29
+ : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ finally {
35
+ if (fd !== undefined) {
36
+ closeSync(fd);
37
+ }
38
+ }
39
+ }
40
+ function isMissing(cause) {
41
+ return cause?.code === 'ENOENT';
42
+ }
43
+ /** A lock record that exists but cannot be verified. Never a fallback. */
44
+ function unreadableLockRecord(path, cause) {
45
+ const detail = cause instanceof Error ? `: ${cause.message}` : '';
46
+ return rendererMismatch(`${path} exists but could not be read${detail}, so the installed renderer's integrity cannot be verified`, {
47
+ subject: path,
48
+ action: 're-install dependencies so npm writes a readable lock record, or restore it from version control',
49
+ ...(cause === undefined ? {} : { cause }),
50
+ });
51
+ }
52
+ /**
53
+ * Read an npm lock record. The three outcomes are deliberately distinct:
54
+ *
55
+ * - no record at all (`ENOENT`) yields `undefined`, which `readRecordedIntegrity`
56
+ * reports as `no-record` so the renderer identity policy can name it with
57
+ * W114 rather than substituting the pin for the missing digest;
58
+ * - a record over `NPM_LOCKFILE_MAX_BYTES` is refused (F010), naming the record
59
+ * and the bound, because a present-but-unverifiable integrity must fail
60
+ * exactly like a differing one rather than become a pass;
61
+ * - a record that exists but cannot be read (a symlink, a FIFO, an I/O or parse
62
+ * failure, a non-object) is refused the same way.
63
+ *
64
+ * The bound is applied before any allocation: this is the one synchronous read
65
+ * of a repository-controlled path, so it cannot use `readBoundedBytes`. It is
66
+ * `NPM_LOCKFILE_MAX_BYTES`, not the small derived-lockfile bound, because npm's
67
+ * record scales with the dependency tree and a legitimate monorepo lockfile can
68
+ * be several megabytes.
69
+ */
70
+ function readLockRecord(path) {
71
+ let fd;
72
+ try {
73
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
74
+ }
75
+ catch (cause) {
76
+ if (isMissing(cause)) {
77
+ return undefined;
78
+ }
79
+ throw unreadableLockRecord(path, cause);
80
+ }
81
+ try {
82
+ const stats = fstatSync(fd);
83
+ if (!stats.isFile()) {
84
+ throw unreadableLockRecord(path, new Error('it is not a regular file'));
85
+ }
86
+ if (stats.size > NPM_LOCKFILE_MAX_BYTES) {
87
+ throw rendererMismatch(`${path} is ${stats.size} bytes, over the ${NPM_LOCKFILE_MAX_BYTES}-byte bound for an npm lock record; it is refused rather than read, so the installed renderer's integrity cannot be verified`, {
88
+ subject: path,
89
+ action: 'inspect the lock record for runaway content and restore it from version control; the bound is far above any real lockfile, so this is not a normal install',
90
+ });
91
+ }
92
+ const value = JSON.parse(readFileSync(fd, 'utf8'));
93
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
94
+ throw unreadableLockRecord(path, new Error('it is not a JSON object'));
95
+ }
96
+ return value;
97
+ }
98
+ catch (cause) {
99
+ if (cause instanceof FarnaError) {
100
+ throw cause;
101
+ }
102
+ throw unreadableLockRecord(path, cause);
103
+ }
104
+ finally {
105
+ closeSync(fd);
106
+ }
107
+ }
108
+ function findPackageDir(name) {
109
+ let entry;
110
+ try {
111
+ entry = requireFromHere.resolve(name);
112
+ }
113
+ catch (cause) {
114
+ // A global install, or a missing dependency, must not surface a raw
115
+ // module-resolution stack from a command that renders.
116
+ throw rendererMismatch(`the pinned renderer ${name} is not installed`, {
117
+ subject: name,
118
+ action: 'install the pinned dependencies, or reinstall farna-bootstrapper',
119
+ cause,
120
+ });
121
+ }
122
+ let current = dirname(entry);
123
+ for (let depth = 0; depth < 16; depth += 1) {
124
+ const manifest = readJson(join(current, 'package.json'));
125
+ if (manifest?.['name'] === name && typeof manifest['version'] === 'string') {
126
+ return current;
127
+ }
128
+ const parent = dirname(current);
129
+ if (parent === current) {
130
+ break;
131
+ }
132
+ current = parent;
133
+ }
134
+ throw rendererMismatch(`cannot locate the installed ${name} package`, {
135
+ subject: name,
136
+ action: 're-install dependencies so the pinned renderer is present',
137
+ });
138
+ }
139
+ /**
140
+ * True when an npm `packages` key names the renderer: the key is
141
+ * `node_modules/<name>` for a hoisted entry, or ends with
142
+ * `/node_modules/<name>` for one nested under another package. npm writes the
143
+ * key in exactly this shape, so the nested layout
144
+ * (`npm install --install-strategy=nested`, which records
145
+ * `node_modules/farna-bootstrapper/node_modules/rulesync`) is the same package
146
+ * record one path deeper rather than a missing one.
147
+ */
148
+ function isRendererKey(key, name) {
149
+ const hoisted = `node_modules/${name}`;
150
+ return key === hoisted || key.endsWith(`/${hoisted}`);
151
+ }
152
+ /** True when a `packages` key nests the renderer directly under our own package. */
153
+ function isUnderProduct(key, name) {
154
+ const underProduct = `node_modules/${PRODUCT_NAME}/node_modules/${name}`;
155
+ return key === underProduct || key.endsWith(`/${underProduct}`);
156
+ }
157
+ /** How many `node_modules` segments a `packages` key contains. Shallowest wins ties. */
158
+ function nestingLevel(key) {
159
+ return key.split('/').filter((segment) => segment === 'node_modules').length;
160
+ }
161
+ /**
162
+ * Rank two renderer entries. The entry nested under our own package wins (that
163
+ * is the copy the product actually imports), then the shallowest, then the
164
+ * earlier record, then the key, so the same records always yield the same
165
+ * answer.
166
+ */
167
+ function isBetterCandidate(candidate, best) {
168
+ if (candidate.underProduct !== best.underProduct) {
169
+ return candidate.underProduct;
170
+ }
171
+ if (candidate.level !== best.level) {
172
+ return candidate.level < best.level;
173
+ }
174
+ if (candidate.recordIndex !== best.recordIndex) {
175
+ return candidate.recordIndex < best.recordIndex;
176
+ }
177
+ return candidate.key < best.key;
178
+ }
179
+ /**
180
+ * The renderer's entry across the supported lock records.
181
+ *
182
+ * The `packages` map is searched for a key ending in `node_modules/<name>`, not
183
+ * indexed by one literal key: a nested install records the renderer under the
184
+ * package that depends on it
185
+ * (`node_modules/<product>/node_modules/<renderer>`), and reading only the
186
+ * hoisted key made a present record look absent. When several entries match,
187
+ * the one nested under our own package wins, then the shallowest (see
188
+ * `isBetterCandidate`).
189
+ *
190
+ * `found` distinguishes the two ways the records can leave the integrity
191
+ * unknown: no matching key at all, and a matching key whose value is not a JSON
192
+ * object with a string `integrity`. The renderer identity policy reports both
193
+ * as `W114`, but the warning names which one happened.
194
+ */
195
+ function bestRendererEntry(records, name) {
196
+ let found = false;
197
+ let best;
198
+ records.forEach((record, recordIndex) => {
199
+ const packages = record?.['packages'];
200
+ if (packages === null || typeof packages !== 'object' || Array.isArray(packages)) {
201
+ return;
202
+ }
203
+ for (const [key, value] of Object.entries(packages)) {
204
+ if (!isRendererKey(key, name)) {
205
+ continue;
206
+ }
207
+ found = true;
208
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
209
+ continue;
210
+ }
211
+ const integrity = value['integrity'];
212
+ if (typeof integrity !== 'string') {
213
+ continue;
214
+ }
215
+ const candidate = {
216
+ key,
217
+ underProduct: isUnderProduct(key, name),
218
+ level: nestingLevel(key),
219
+ recordIndex,
220
+ integrity,
221
+ };
222
+ if (best === undefined || isBetterCandidate(candidate, best)) {
223
+ best = candidate;
224
+ }
225
+ }
226
+ });
227
+ return best === undefined ? { found } : { found: true, integrity: best.integrity };
228
+ }
229
+ /**
230
+ * The install root: the top of the `node_modules` chain the renderer sits in,
231
+ * which is also the nearest ancestor of the product package that owns a
232
+ * `node_modules` directory. In a hoisted install the renderer is at
233
+ * `<root>/node_modules/<renderer>`, so that is `<root>`, the directory holding
234
+ * the install's records.
235
+ *
236
+ * The climb follows the chain to its end rather than stopping at the first
237
+ * package that owns a `node_modules`. In a nested install
238
+ * (`npm install --install-strategy=nested`) the renderer's own package also
239
+ * owns a `node_modules`, so `<root>/node_modules/<product>/node_modules/<renderer>`
240
+ * is reached by hopping `<renderer> -> <product> -> <root>`; the install's
241
+ * records, keyed `node_modules/<product>/node_modules/<renderer>`, sit at that
242
+ * last hop.
243
+ *
244
+ * A scoped package adds one directory level between the package and its
245
+ * `node_modules` (`<root>/node_modules/@scope/<name>`), so the scope directory
246
+ * is skipped in the same climb; without that, a scoped install's records were
247
+ * never reached and a present record looked absent.
248
+ *
249
+ * The walk never climbs above this boundary, because it only leaves
250
+ * `node_modules` directories. A workspace root, a parent monorepo or any other
251
+ * ancestor outside that chain is never read, and a package that is not inside a
252
+ * `node_modules` directory (a linked install) is bounded by itself.
253
+ */
254
+ function installRootFor(packageDir) {
255
+ let root = packageDir;
256
+ for (let current = packageDir;;) {
257
+ const parent = dirname(current);
258
+ if (parent === current) {
259
+ break;
260
+ }
261
+ if (basename(parent) === 'node_modules') {
262
+ // `current` is inside a `node_modules` directory, so the package that
263
+ // owns that directory is one level further out on the same chain.
264
+ root = dirname(parent);
265
+ current = root;
266
+ continue;
267
+ }
268
+ if (basename(parent).startsWith('@') && basename(dirname(parent)) === 'node_modules') {
269
+ // A scoped package: `<root>/node_modules/@scope/<name>`. The scope
270
+ // directory is part of the package path, not an install boundary.
271
+ root = dirname(dirname(parent));
272
+ current = root;
273
+ continue;
274
+ }
275
+ break;
276
+ }
277
+ return root;
278
+ }
279
+ /**
280
+ * The renderer's recorded integrity, from exactly two records at the install
281
+ * root:
282
+ *
283
+ * 1. the hidden record npm writes beside the installed tree,
284
+ * `<installRoot>/node_modules/.package-lock.json`;
285
+ * 2. the install root's lockfile, `<installRoot>/package-lock.json`.
286
+ *
287
+ * Nothing above the install root is read: a workspace root, a parent monorepo
288
+ * or a sibling package may record a different copy of the renderer, and taking
289
+ * its integrity refused a healthy install or verified one that was never
290
+ * checked. Those layouts yield `W114` instead.
291
+ *
292
+ * Both records are read before the search, so a present record that cannot be
293
+ * read, is not a regular file, is a symlink or is over the npm-record bound is
294
+ * refused with `F010` even when the other record is usable. Only a genuinely
295
+ * absent record is skipped, and only a genuinely absent renderer entry, or an
296
+ * entry with no string integrity, is `W114`.
297
+ *
298
+ * The result is structured, never `undefined` for both "no record" and "no
299
+ * usable entry". The renderer identity policy reports those as `W114` and names
300
+ * which one happened, so they must not be indistinguishable at this seam.
301
+ *
302
+ * @internal Exported so a test can prove the bound on a supported record;
303
+ * callers use `installedRendererIdentity`.
304
+ */
305
+ export function readRecordedIntegrity(packageDir, name) {
306
+ const installRoot = installRootFor(packageDir);
307
+ const records = [
308
+ readLockRecord(join(installRoot, 'node_modules', '.package-lock.json')),
309
+ readLockRecord(join(installRoot, 'package-lock.json')),
310
+ ];
311
+ const lookup = bestRendererEntry(records, name);
312
+ if (lookup.integrity !== undefined) {
313
+ return { verified: true, integrity: lookup.integrity };
314
+ }
315
+ return lookup.found
316
+ ? { verified: false, reason: 'no-integrity' }
317
+ : { verified: false, reason: 'no-record' };
318
+ }
319
+ /**
320
+ * The structured integrity record for an identity. The real target attaches the
321
+ * npm lookup directly; an injected target that only supplied `integrity` has a
322
+ * present value treated as verified and a missing one as no record. This keeps
323
+ * the warning decision in one place instead of re-deriving it at each caller.
324
+ */
325
+ export function integrityRecordOf(identity) {
326
+ if (identity.integrityRecord !== undefined) {
327
+ return identity.integrityRecord;
328
+ }
329
+ return identity.integrity === undefined
330
+ ? { verified: false, reason: 'no-record' }
331
+ : { verified: true, integrity: identity.integrity };
332
+ }
333
+ /** Read the installed renderer's own package manifest and recorded integrity. */
334
+ export function installedRendererIdentity(name) {
335
+ const packageDir = findPackageDir(name);
336
+ const manifest = readJson(join(packageDir, 'package.json'));
337
+ const version = manifest?.['version'];
338
+ if (manifest === undefined || typeof version !== 'string') {
339
+ throw rendererMismatch(`the installed ${name} package has no readable version`, {
340
+ subject: name,
341
+ action: 're-install dependencies so the pinned renderer is present',
342
+ });
343
+ }
344
+ const integrityRecord = readRecordedIntegrity(packageDir, name);
345
+ return {
346
+ name,
347
+ version,
348
+ integrityRecord,
349
+ ...(integrityRecord.verified ? { integrity: integrityRecord.integrity } : {}),
350
+ };
351
+ }
352
+ /**
353
+ * Compare the renderer recorded in the lockfile with the one that is installed.
354
+ *
355
+ * A differing name or version always fails, and so does a lockfile that records
356
+ * no integrity: the committed bytes must be tied to a pinned renderer. An
357
+ * installed package whose npm lock record supplied no string integrity is not a
358
+ * mismatch: its version has already been enforced, and the caller reports the
359
+ * unverified digest as `W114_RENDERER_INTEGRITY_UNVERIFIED` rather than
360
+ * refusing a normal global or linked install. When an integrity was read, it is
361
+ * compared exactly; the check never degrades a known integrity to a
362
+ * version-only comparison.
363
+ */
364
+ export function verifyRendererIdentity(recorded, installed, subject = '.farna/lock.json') {
365
+ if (recorded.name !== installed.name) {
366
+ throw rendererMismatch(`the lockfile records renderer "${recorded.name}" but "${installed.name}" is installed`, {
367
+ subject,
368
+ action: 'delete the lockfile and re-run generate to record the installed renderer',
369
+ });
370
+ }
371
+ if (recorded.version !== installed.version) {
372
+ throw rendererMismatch(`the lockfile records ${recorded.name} ${recorded.version} but ${installed.version} is installed`, {
373
+ subject,
374
+ action: 'delete the lockfile and re-run generate to record the installed renderer',
375
+ });
376
+ }
377
+ if (recorded.integrity === undefined) {
378
+ throw rendererMismatch(`the lockfile records no integrity for ${recorded.name} ${recorded.version}, so the committed bytes cannot be tied to a pinned renderer`, {
379
+ subject,
380
+ action: 'delete the lockfile and re-run generate to record the pinned renderer',
381
+ });
382
+ }
383
+ const installedRecord = integrityRecordOf(installed);
384
+ if (!installedRecord.verified) {
385
+ // Not a refusal: the version matched, and `prepareRender` names the
386
+ // unverified integrity as W114. An unknown integrity must not be compared
387
+ // to anything, and must not be silently treated as a pass either.
388
+ return;
389
+ }
390
+ if (recorded.integrity !== installedRecord.integrity) {
391
+ throw rendererMismatch(`the lockfile records ${recorded.name} integrity ${recorded.integrity} but the installed package is ${installedRecord.integrity}`, {
392
+ subject,
393
+ action: 're-install dependencies from the lockfile, or re-run generate to record the installed renderer',
394
+ });
395
+ }
396
+ }
@@ -0,0 +1,59 @@
1
+ import type { LockFileEntry } from '../lock/lockfile.js';
2
+ /**
3
+ * A path recorded in the committed lockfile is this tool's output. When the
4
+ * current source no longer produces it — a persona switch, a removed resource,
5
+ * a target edit — it is an orphan: `check` reports it as drift, and `generate`
6
+ * may remove it.
7
+ *
8
+ * Removal is deliberately narrow, because a lockfile is a file a user could
9
+ * hand-edit and a managed directory is one a user may also keep files in:
10
+ *
11
+ * - the path must be relative and escape-free;
12
+ * - it must lie in a location one of the supported targets can own (a managed
13
+ * directory subtree, or a whole root config file); this deliberately spans
14
+ * targets, so switching the configured target does not strand the previous
15
+ * target's recorded artefacts as unremovable;
16
+ * - it must still be a regular file (a symlink is refused, never followed);
17
+ * - its bytes must still equal the SHA-256 the lockfile recorded. A changed file
18
+ * is drift, not this tool's output any more, so it is refused rather than
19
+ * destroyed.
20
+ *
21
+ * An absent path is dropped from the new lockfile before any of the guards
22
+ * apply: there is nothing to remove, and a recorded path outside a managed
23
+ * location that no longer exists could never satisfy an action that says
24
+ * "remove it deliberately".
25
+ *
26
+ * A `structured` entry owns only its declared keys. When the current source no
27
+ * longer produces it, only those keys are deleted in place: a file that also
28
+ * carries the user's own keys is kept (with their comments) and the record is
29
+ * dropped, while a file left with nothing but the owned keys is removed. The
30
+ * record is also dropped, without touching the file, once the user has already
31
+ * removed the owned keys.
32
+ */
33
+ /** True when one of the supported renderers can own this repository-relative path. */
34
+ export declare function isManagedOutputPath(path: string): boolean;
35
+ /** What `generate` will do for a recorded path the current plan no longer produces. */
36
+ export type OrphanPlan = {
37
+ entry: LockFileEntry;
38
+ action: 'remove' | 'rewrite';
39
+ };
40
+ /**
41
+ * Validate every recorded path the current plan no longer produces, and return
42
+ * the action `generate` will take. Nothing is written here: a dry run and a
43
+ * real run share this preflight, so the plan can never report an edit the write
44
+ * path would refuse.
45
+ */
46
+ export declare function planOrphans(repoRoot: string, recorded: readonly LockFileEntry[], expected: ReadonlySet<string>): Promise<OrphanPlan[]>;
47
+ export type RemovedOrphan = {
48
+ path: string;
49
+ status: 'removed' | 'updated' | 'missing';
50
+ };
51
+ /** A bare entry is accepted for callers that already preflighted (and for tests). */
52
+ export type OrphanTarget = LockFileEntry | OrphanPlan;
53
+ /**
54
+ * Remove the preflighted orphans, re-checking each one immediately before the
55
+ * `rm`. A path that vanished since the preflight is reported as `missing`; a
56
+ * failure names the path, and every path already removed this run, rather than
57
+ * pretending the tree is unchanged.
58
+ */
59
+ export declare function removeOrphans(repoRoot: string, orphans: readonly OrphanTarget[]): Promise<RemovedOrphan[]>;
@@ -0,0 +1,234 @@
1
+ import { rm } from 'node:fs/promises';
2
+ import { LOCK_PATH, MANAGED_FILE_MAX_BYTES, MANAGED_OUTPUT_DIRS, MANAGED_OUTPUT_FILES, SUPPORTED_TARGETS, } from '../core/constants.js';
3
+ import { driftRefused, FarnaError, pathUnsafe, writeFailed } from '../core/errors.js';
4
+ import { decodeUtf8, describeFsError, readBoundedBytes } from '../core/fs.js';
5
+ import { compareCodepoints, sha256Hex } from '../core/json.js';
6
+ import { containedTarget, lstatOrUndefined } from '../core/paths.js';
7
+ import { assertSafeRelativePath, commitFiles } from './commit.js';
8
+ import { mergeStructuredText, ownedSubset, parseStructuredDocument, structuredOwnedDigest, } from './structured.js';
9
+ /**
10
+ * A path recorded in the committed lockfile is this tool's output. When the
11
+ * current source no longer produces it — a persona switch, a removed resource,
12
+ * a target edit — it is an orphan: `check` reports it as drift, and `generate`
13
+ * may remove it.
14
+ *
15
+ * Removal is deliberately narrow, because a lockfile is a file a user could
16
+ * hand-edit and a managed directory is one a user may also keep files in:
17
+ *
18
+ * - the path must be relative and escape-free;
19
+ * - it must lie in a location one of the supported targets can own (a managed
20
+ * directory subtree, or a whole root config file); this deliberately spans
21
+ * targets, so switching the configured target does not strand the previous
22
+ * target's recorded artefacts as unremovable;
23
+ * - it must still be a regular file (a symlink is refused, never followed);
24
+ * - its bytes must still equal the SHA-256 the lockfile recorded. A changed file
25
+ * is drift, not this tool's output any more, so it is refused rather than
26
+ * destroyed.
27
+ *
28
+ * An absent path is dropped from the new lockfile before any of the guards
29
+ * apply: there is nothing to remove, and a recorded path outside a managed
30
+ * location that no longer exists could never satisfy an action that says
31
+ * "remove it deliberately".
32
+ *
33
+ * A `structured` entry owns only its declared keys. When the current source no
34
+ * longer produces it, only those keys are deleted in place: a file that also
35
+ * carries the user's own keys is kept (with their comments) and the record is
36
+ * dropped, while a file left with nothing but the owned keys is removed. The
37
+ * record is also dropped, without touching the file, once the user has already
38
+ * removed the owned keys.
39
+ */
40
+ /** True when one of the supported renderers can own this repository-relative path. */
41
+ export function isManagedOutputPath(path) {
42
+ for (const target of SUPPORTED_TARGETS) {
43
+ if (MANAGED_OUTPUT_FILES[target].includes(path)) {
44
+ return true;
45
+ }
46
+ const managed = MANAGED_OUTPUT_DIRS[target].some((directory) => path.startsWith(`${directory}/`) && path.length > directory.length + 1);
47
+ if (managed) {
48
+ return true;
49
+ }
50
+ }
51
+ return false;
52
+ }
53
+ /**
54
+ * Inspect one recorded orphan. Shared by the preflight and the removal itself,
55
+ * so the bytes that are deleted are re-checked against the recorded digest
56
+ * immediately before `rm` rather than trusted from an earlier pass (a file can
57
+ * change between the two).
58
+ */
59
+ async function inspectOrphan(repoRoot, entry) {
60
+ const path = entry.path;
61
+ assertSafeRelativePath(path);
62
+ const absolute = await containedTarget(repoRoot, path);
63
+ const stats = await lstatOrUndefined(absolute, path);
64
+ if (stats === undefined) {
65
+ return { kind: 'absent' };
66
+ }
67
+ // The managed-location guard applies only to a path that exists: a missing
68
+ // path is dropped from the lockfile, never refused with an action the user
69
+ // cannot carry out.
70
+ if (!isManagedOutputPath(path)) {
71
+ throw pathUnsafe(`refusing to remove ${path}: it is recorded but is not a managed output location`, {
72
+ subject: path,
73
+ action: 'remove it deliberately, then re-run generate',
74
+ });
75
+ }
76
+ if (stats.isSymbolicLink()) {
77
+ throw pathUnsafe(`refusing to remove a symbolic link at a recorded path: ${path}`, {
78
+ subject: path,
79
+ action: 'remove the symbolic link deliberately, then re-run generate',
80
+ });
81
+ }
82
+ if (!stats.isFile()) {
83
+ throw writeFailed(`cannot remove ${path}: it is not a regular file`, {
84
+ subject: path,
85
+ action: 'remove the directory or special file deliberately, then re-run generate',
86
+ });
87
+ }
88
+ const ownedKeys = entry.shape === 'structured' ? entry.ownedKeys : undefined;
89
+ if (ownedKeys === undefined) {
90
+ const bytes = await readBoundedBytes(absolute, path, {
91
+ action: 'make the recorded file readable and re-run generate',
92
+ maxBytes: MANAGED_FILE_MAX_BYTES,
93
+ });
94
+ if (sha256Hex(bytes) !== entry.sha256) {
95
+ throw driftRefused(`refusing to remove ${path}: it no longer matches the bytes recorded as owned`, {
96
+ subject: path,
97
+ action: 'move the file aside deliberately, or restore the recorded bytes, then re-run generate',
98
+ });
99
+ }
100
+ return { kind: 'removable' };
101
+ }
102
+ const bytes = await readBoundedBytes(absolute, path, {
103
+ action: 'make the recorded file readable and re-run generate',
104
+ maxBytes: MANAGED_FILE_MAX_BYTES,
105
+ });
106
+ const text = decodeUtf8(bytes, path);
107
+ let document;
108
+ try {
109
+ document = parseStructuredDocument(text, path);
110
+ }
111
+ catch (error) {
112
+ throw driftRefused(`refusing to remove ${path}: it is no longer a JSON object this tool wrote`, {
113
+ subject: path,
114
+ action: 'restore the recorded document, or move it aside deliberately, then re-run generate',
115
+ cause: error,
116
+ });
117
+ }
118
+ const owned = ownedSubset(document, ownedKeys);
119
+ if (Object.keys(owned).length === 0) {
120
+ // The user already removed the keys this tool owned. The file is theirs
121
+ // now, so it is left alone and the record is dropped.
122
+ return { kind: 'already-removed' };
123
+ }
124
+ const digest = structuredOwnedDigest(document, ownedKeys);
125
+ if (digest.sha256 !== entry.sha256) {
126
+ throw driftRefused(`refusing to remove ${path}: ${ownedKeys.join(', ')} no longer matches the bytes recorded as owned`, {
127
+ subject: path,
128
+ action: 'restore the recorded value, or move the file aside deliberately, then re-run generate',
129
+ });
130
+ }
131
+ const foreignKeys = Object.keys(document)
132
+ .filter((key) => !ownedKeys.includes(key))
133
+ .sort(compareCodepoints);
134
+ if (foreignKeys.length > 0) {
135
+ // The file is still partly the user's. Delete only the key this tool owns
136
+ // and leave their keys and comments exactly where they were; the new
137
+ // lockfile drops this record because the path is no longer produced.
138
+ return {
139
+ kind: 'rewrite',
140
+ bytes: mergeStructuredText(text, '{}\n', ownedKeys, path),
141
+ };
142
+ }
143
+ return { kind: 'removable' };
144
+ }
145
+ /**
146
+ * Validate every recorded path the current plan no longer produces, and return
147
+ * the action `generate` will take. Nothing is written here: a dry run and a
148
+ * real run share this preflight, so the plan can never report an edit the write
149
+ * path would refuse.
150
+ */
151
+ export async function planOrphans(repoRoot, recorded, expected) {
152
+ const orphans = [];
153
+ for (const entry of recorded) {
154
+ if (entry.path === LOCK_PATH || expected.has(entry.path)) {
155
+ continue;
156
+ }
157
+ const inspection = await inspectOrphan(repoRoot, entry);
158
+ if (inspection.kind === 'removable') {
159
+ orphans.push({ entry, action: 'remove' });
160
+ }
161
+ else if (inspection.kind === 'rewrite') {
162
+ orphans.push({ entry, action: 'rewrite' });
163
+ }
164
+ }
165
+ return orphans.sort((a, b) => compareCodepoints(a.entry.path, b.entry.path));
166
+ }
167
+ function lockEntry(target) {
168
+ return 'entry' in target ? target.entry : target;
169
+ }
170
+ /**
171
+ * Re-throw a removal failure with the paths this run already removed named. The
172
+ * failure is true of one path and false of the run: earlier removals happened,
173
+ * so the tree is partially updated and the reader must be told which paths are
174
+ * gone. This is the same honesty the commit failure carries.
175
+ */
176
+ function removalFailure(error, removed) {
177
+ const paths = removed.filter((entry) => entry.status === 'removed').map((entry) => entry.path);
178
+ const updated = removed.filter((entry) => entry.status === 'updated').map((entry) => entry.path);
179
+ if (!(error instanceof FarnaError) || (paths.length === 0 && updated.length === 0)) {
180
+ return error;
181
+ }
182
+ const details = [];
183
+ if (paths.length > 0) {
184
+ details.push(`this run already removed ${paths.length} recorded path(s) (${paths.join(', ')})`);
185
+ }
186
+ if (updated.length > 0) {
187
+ details.push(`this run already updated ${updated.length} recorded path(s) (${updated.join(', ')})`);
188
+ }
189
+ return new FarnaError(error.code, `${error.message}; ${details.join('; ')} before the write failed, so the tree is partially updated`, {
190
+ ...(error.subject === undefined ? {} : { subject: error.subject }),
191
+ action: 're-run generate after fixing the filesystem; the lockfile still records the affected paths',
192
+ cause: error,
193
+ });
194
+ }
195
+ /**
196
+ * Remove the preflighted orphans, re-checking each one immediately before the
197
+ * `rm`. A path that vanished since the preflight is reported as `missing`; a
198
+ * failure names the path, and every path already removed this run, rather than
199
+ * pretending the tree is unchanged.
200
+ */
201
+ export async function removeOrphans(repoRoot, orphans) {
202
+ const removed = [];
203
+ for (const target of orphans) {
204
+ const entry = lockEntry(target);
205
+ try {
206
+ const inspection = await inspectOrphan(repoRoot, entry);
207
+ if (inspection.kind === 'rewrite') {
208
+ await commitFiles(repoRoot, [{ path: entry.path, bytes: inspection.bytes }]);
209
+ removed.push({ path: entry.path, status: 'updated' });
210
+ continue;
211
+ }
212
+ if (inspection.kind !== 'removable') {
213
+ removed.push({ path: entry.path, status: 'missing' });
214
+ continue;
215
+ }
216
+ const absolute = await containedTarget(repoRoot, entry.path);
217
+ try {
218
+ await rm(absolute, { force: true });
219
+ }
220
+ catch (error) {
221
+ throw writeFailed(`cannot remove ${entry.path} (${describeFsError(error)}); the tree is partially updated`, {
222
+ subject: entry.path,
223
+ action: 'remove the file deliberately, then re-run generate',
224
+ cause: error,
225
+ });
226
+ }
227
+ removed.push({ path: entry.path, status: 'removed' });
228
+ }
229
+ catch (error) {
230
+ throw removalFailure(error, removed);
231
+ }
232
+ }
233
+ return removed;
234
+ }