anhedral 0.22.0 → 0.23.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 (92) hide show
  1. package/README.md +37 -51
  2. package/assets/contracts/deployment-provenance.json +4 -4
  3. package/assets/contracts/environment-provenance.json +2 -2
  4. package/dist/cli-commands.js +5 -17
  5. package/dist/cli-errors.js +1 -1
  6. package/dist/cli-output.js +1 -1
  7. package/dist/command-schema.d.ts +1 -0
  8. package/dist/command-schema.js +19 -1
  9. package/dist/completion.js +1 -1
  10. package/dist/{capability-catalog.d.ts → composition/catalog.d.ts} +2 -2
  11. package/dist/{capability-catalog.js → composition/catalog.js} +2 -2
  12. package/dist/{capability-command.d.ts → composition/command.d.ts} +3 -3
  13. package/dist/{capability-command.js → composition/command.js} +29 -22
  14. package/dist/{composition.d.ts → composition/composition.d.ts} +1 -1
  15. package/dist/{composition.js → composition/composition.js} +2 -2
  16. package/dist/{capability-editor.js → composition/editor.js} +1 -1
  17. package/dist/{capability-recipes.d.ts → composition/recipes.d.ts} +2 -2
  18. package/dist/{capability-recipes.js → composition/recipes.js} +7 -7
  19. package/dist/{capability-references.js → composition/references.js} +2 -2
  20. package/dist/{stack-update.d.ts → composition/update.d.ts} +3 -3
  21. package/dist/{stack-update.js → composition/update.js} +11 -11
  22. package/dist/contracts/cli-transport.d.ts +1 -1
  23. package/dist/contracts/deployment.d.ts +4 -65
  24. package/dist/contracts/deployment.js +0 -29
  25. package/dist/contracts/environment-file.d.ts +3 -0
  26. package/dist/contracts/environment-file.js +8 -5
  27. package/dist/contracts/production-transport.d.ts +2 -2
  28. package/dist/contracts/staging-transport.d.ts +2 -2
  29. package/dist/dependencies.d.ts +1 -1
  30. package/dist/dependencies.js +1 -1
  31. package/dist/launch.js +8 -8
  32. package/dist/platform/auth.d.ts +14 -0
  33. package/dist/platform/auth.js +62 -0
  34. package/dist/{platform-command.d.ts → platform/command.d.ts} +2 -2
  35. package/dist/platform/command.js +279 -0
  36. package/dist/{credential-helper.js → platform/credential-helper.js} +1 -1
  37. package/dist/platform/deploy.d.ts +2 -0
  38. package/dist/platform/deploy.js +158 -0
  39. package/dist/{platform-environment.d.ts → platform/environment.d.ts} +1 -1
  40. package/dist/{platform-environment.js → platform/environment.js} +12 -12
  41. package/dist/platform/http.d.ts +7 -0
  42. package/dist/platform/http.js +105 -0
  43. package/dist/{platform-operations.d.ts → platform/operations.d.ts} +1 -1
  44. package/dist/{platform-operations.js → platform/operations.js} +5 -5
  45. package/dist/platform/output.d.ts +2 -0
  46. package/dist/platform/output.js +79 -0
  47. package/dist/{platform-production.d.ts → platform/production.d.ts} +1 -1
  48. package/dist/{platform-production.js → platform/production.js} +4 -4
  49. package/dist/platform/projects.d.ts +12 -0
  50. package/dist/platform/projects.js +125 -0
  51. package/dist/{platform-source.js → platform/source.js} +7 -7
  52. package/dist/platform/state-schema.d.ts +25 -0
  53. package/dist/platform/state-schema.js +11 -0
  54. package/dist/{platform-state.d.ts → platform/state.d.ts} +1 -1
  55. package/dist/{platform-state.js → platform/state.js} +3 -4
  56. package/dist/platform/types.d.ts +26 -0
  57. package/dist/platform/upload.d.ts +2 -0
  58. package/dist/platform/upload.js +60 -0
  59. package/dist/process/runner.d.ts +1 -0
  60. package/dist/{command-runner.js → process/runner.js} +1 -1
  61. package/dist/registry/usage.d.ts +1 -0
  62. package/dist/{platforms → scaffold}/tanstack.d.ts +2 -2
  63. package/dist/{platforms → scaffold}/tanstack.js +2 -2
  64. package/dist/transactions/durable-files.d.ts +8 -0
  65. package/dist/transactions/durable-files.js +132 -0
  66. package/dist/transactions/journal.d.ts +4 -0
  67. package/dist/transactions/journal.js +141 -0
  68. package/dist/{transaction-lock.js → transactions/lock.js} +2 -2
  69. package/dist/transactions/model.d.ts +18 -0
  70. package/dist/transactions/model.js +4 -0
  71. package/dist/transactions/paths.d.ts +12 -0
  72. package/dist/transactions/paths.js +155 -0
  73. package/dist/transactions/recovery.d.ts +7 -0
  74. package/dist/transactions/recovery.js +132 -0
  75. package/dist/{transaction.d.ts → transactions/transaction.d.ts} +1 -2
  76. package/dist/transactions/transaction.js +179 -0
  77. package/dist/util.js +2 -2
  78. package/dist/version.d.ts +1 -1
  79. package/dist/version.js +1 -1
  80. package/docs/capabilities.md +8 -6
  81. package/docs/software-factory.md +36 -6
  82. package/package.json +22 -22
  83. package/dist/platform-command.js +0 -787
  84. package/dist/transaction.js +0 -716
  85. /package/dist/{capability-editor.d.ts → composition/editor.d.ts} +0 -0
  86. /package/dist/{capability-references.d.ts → composition/references.d.ts} +0 -0
  87. /package/dist/{credential-helper.d.ts → platform/credential-helper.d.ts} +0 -0
  88. /package/dist/{platform-source.d.ts → platform/source.d.ts} +0 -0
  89. /package/dist/{command-runner.d.ts → platform/types.js} +0 -0
  90. /package/dist/{command.d.ts → process/resolve-command.d.ts} +0 -0
  91. /package/dist/{command.js → process/resolve-command.js} +0 -0
  92. /package/dist/{transaction-lock.d.ts → transactions/lock.d.ts} +0 -0
@@ -1,716 +0,0 @@
1
- import { LOCK_FILE, acquireTransactionLock, releaseTransactionLock } from './transaction-lock.js';
2
- import { readBoundedFile } from './bounded-file.js';
3
- import { closeSync, cpSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, rmSync, unlinkSync, writeFileSync, } from 'node:fs';
4
- import { createHash, randomUUID } from 'node:crypto';
5
- import path from 'node:path';
6
- const JOURNAL_FILE = '.anhedral-journal.json';
7
- const TRANSACTION_DIRECTORY = '.anhedral-txn';
8
- const JOURNAL_VERSION = 2;
9
- const LOCAL_TRANSACTION_ROOT_PATTERN = /^(?:stage|backup)-\d+-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10
- function assertRelativePath(relativePath) {
11
- const normalized = path.normalize(relativePath);
12
- const rawSegments = relativePath.split(/[\\/]/);
13
- if (!relativePath ||
14
- relativePath.includes('\0') ||
15
- relativePath.includes('\\') ||
16
- path.isAbsolute(relativePath) ||
17
- rawSegments.some((segment) => segment === '' || segment === '.' || segment === '..') ||
18
- normalized === '.' ||
19
- normalized === '..' ||
20
- normalized.startsWith(`..${path.sep}`) ||
21
- normalized.split(path.sep).includes('..') ||
22
- rawSegments[0] === TRANSACTION_DIRECTORY ||
23
- rawSegments[0] === LOCK_FILE ||
24
- rawSegments[0] === JOURNAL_FILE) {
25
- throw new Error(`Unsafe transaction path: ${relativePath}`);
26
- }
27
- }
28
- function resolveTransactionPath(root, relativePath) {
29
- assertRelativePath(relativePath);
30
- const resolvedRoot = path.resolve(root);
31
- const resolved = path.resolve(resolvedRoot, relativePath);
32
- if (!resolved.startsWith(`${resolvedRoot}${path.sep}`)) {
33
- throw new Error(`Unsafe transaction path: ${relativePath}`);
34
- }
35
- return resolved;
36
- }
37
- function ancestorInSet(relativePath, candidates) {
38
- const segments = relativePath.split('/');
39
- for (let index = 1; index < segments.length; index += 1) {
40
- const ancestor = segments.slice(0, index).join('/');
41
- if (candidates.has(ancestor))
42
- return ancestor;
43
- }
44
- return null;
45
- }
46
- function assertNoPathAncestry(paths, context) {
47
- const seen = new Set();
48
- const ordered = [...paths].sort((left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right));
49
- for (const relativePath of ordered) {
50
- assertRelativePath(relativePath);
51
- const ancestor = ancestorInSet(relativePath, seen);
52
- if (ancestor) {
53
- throw new Error(`Ambiguous transaction ${context}: ${ancestor} is an ancestor of ${relativePath}.`);
54
- }
55
- seen.add(relativePath);
56
- }
57
- }
58
- function normalizeTransactionPaths(rawCommitPaths, rawDeletePaths) {
59
- const commitPaths = [...new Set(rawCommitPaths)];
60
- for (const relativePath of commitPaths)
61
- assertRelativePath(relativePath);
62
- assertNoPathAncestry(commitPaths, 'write paths');
63
- const deleteCandidates = [...new Set(rawDeletePaths)];
64
- for (const relativePath of deleteCandidates)
65
- assertRelativePath(relativePath);
66
- deleteCandidates.sort((left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right));
67
- const deleteSet = new Set();
68
- const deletePaths = deleteCandidates.filter((candidate) => {
69
- if (ancestorInSet(candidate, deleteSet))
70
- return false;
71
- deleteSet.add(candidate);
72
- return true;
73
- });
74
- const deleteAncestorPaths = new Set();
75
- for (const deleted of deletePaths) {
76
- const segments = deleted.split('/');
77
- for (let index = 1; index < segments.length; index += 1) {
78
- deleteAncestorPaths.add(segments.slice(0, index).join('/'));
79
- }
80
- }
81
- for (const written of commitPaths) {
82
- const deletedAncestor = ancestorInSet(written, deleteSet);
83
- if (deleteSet.has(written) || deletedAncestor || deleteAncestorPaths.has(written)) {
84
- throw new Error(`Ambiguous transaction write/delete paths include ${written}` +
85
- (deletedAncestor ? ` below ${deletedAncestor}` : ''));
86
- }
87
- }
88
- const uniquePaths = [...commitPaths, ...deletePaths].sort();
89
- return { commitPaths, deletePaths, uniquePaths };
90
- }
91
- function isRecord(value) {
92
- return typeof value === 'object' && value !== null && !Array.isArray(value);
93
- }
94
- function assertExactObjectKeys(value, expected, context) {
95
- const expectedKeys = new Set(expected);
96
- const missing = expected.filter((key) => !Object.hasOwn(value, key));
97
- const unknown = Object.keys(value).filter((key) => !expectedKeys.has(key));
98
- if (missing.length === 0 && unknown.length === 0)
99
- return;
100
- const details = [
101
- missing.length > 0 ? `missing ${missing.join(', ')}` : null,
102
- unknown.length > 0 ? `unknown ${unknown.join(', ')}` : null,
103
- ]
104
- .filter((entry) => entry !== null)
105
- .join('; ');
106
- throw new Error(`Invalid ${context} fields (${details}).`);
107
- }
108
- function lstatIfPresent(target) {
109
- try {
110
- return lstatSync(target);
111
- }
112
- catch (error) {
113
- if (error.code === 'ENOENT')
114
- return null;
115
- throw error;
116
- }
117
- }
118
- function pathEntryExists(target) {
119
- return lstatIfPresent(target) !== null;
120
- }
121
- function fingerprintEntry(target) {
122
- const hash = createHash('sha256');
123
- const visit = (absolutePath, relativePath) => {
124
- const stat = lstatSync(absolutePath);
125
- const mode = stat.mode & 0o7777;
126
- if (stat.isDirectory()) {
127
- hash.update(`directory\0${relativePath}\0${mode}\0`);
128
- for (const entry of readdirSync(absolutePath).sort()) {
129
- visit(path.join(absolutePath, entry), relativePath === '.' ? entry : `${relativePath}/${entry}`);
130
- }
131
- return;
132
- }
133
- if (stat.isFile()) {
134
- hash.update(`file\0${relativePath}\0${mode}\0${stat.size}\0`);
135
- hash.update(readFileSync(absolutePath));
136
- return;
137
- }
138
- throw new Error(`Cannot fingerprint unsupported transaction entry: ${absolutePath}`);
139
- };
140
- visit(target, '.');
141
- return hash.digest('hex');
142
- }
143
- function isUnsupportedDirectorySync(error, operation) {
144
- const code = error.code;
145
- if (['ENOTSUP', 'EOPNOTSUPP'].includes(code ?? ''))
146
- return true;
147
- // Some filesystems expose directories as readable handles but reject fsync.
148
- // Windows may reject opening or syncing directory handles altogether. Keep
149
- // these narrowly scoped so permission and I/O failures remain actionable.
150
- if (operation === 'fsync' && code === 'EINVAL')
151
- return true;
152
- if (process.platform !== 'win32')
153
- return false;
154
- const windowsCodes = operation === 'open' ? ['EISDIR', 'EPERM'] : ['EBADF', 'EPERM'];
155
- return windowsCodes.includes(code ?? '');
156
- }
157
- function syncDirectory(directory) {
158
- let descriptor;
159
- try {
160
- descriptor = openSync(directory, 'r');
161
- }
162
- catch (error) {
163
- if (isUnsupportedDirectorySync(error, 'open'))
164
- return;
165
- throw error;
166
- }
167
- try {
168
- try {
169
- fsyncSync(descriptor);
170
- }
171
- catch (error) {
172
- if (!isUnsupportedDirectorySync(error, 'fsync'))
173
- throw error;
174
- }
175
- }
176
- finally {
177
- closeSync(descriptor);
178
- }
179
- }
180
- function directoryChainToRoot(directory, root) {
181
- const resolvedRoot = path.resolve(root);
182
- let cursor = path.resolve(directory);
183
- if (cursor !== resolvedRoot && !cursor.startsWith(`${resolvedRoot}${path.sep}`)) {
184
- throw new Error(`Cannot sync transaction directory outside its root: ${directory}`);
185
- }
186
- const directories = [];
187
- while (true) {
188
- directories.push(cursor);
189
- if (cursor === resolvedRoot)
190
- return directories;
191
- cursor = path.dirname(cursor);
192
- }
193
- }
194
- function syncDirectories(directories) {
195
- const seen = new Set();
196
- for (const directory of directories) {
197
- const resolved = path.resolve(directory);
198
- if (seen.has(resolved))
199
- continue;
200
- seen.add(resolved);
201
- syncDirectory(resolved);
202
- }
203
- }
204
- function syncEntryRecursively(target) {
205
- const stat = lstatSync(target);
206
- if (stat.isDirectory()) {
207
- for (const entry of readdirSync(target))
208
- syncEntryRecursively(path.join(target, entry));
209
- syncDirectory(target);
210
- return;
211
- }
212
- if (!stat.isFile())
213
- return;
214
- // Windows FlushFileBuffers requires a handle opened with write access. The
215
- // staged file is owned by this transaction, so opening it read/write retains
216
- // the durability guarantee instead of treating EPERM as an unsupported sync.
217
- const descriptor = openSync(target, process.platform === 'win32' ? 'r+' : 'r');
218
- try {
219
- fsyncSync(descriptor);
220
- }
221
- finally {
222
- closeSync(descriptor);
223
- }
224
- }
225
- function renameDurably(source, target, root) {
226
- renameSync(source, target);
227
- const targetDirectories = directoryChainToRoot(path.dirname(target), root);
228
- const sourceParent = path.dirname(source);
229
- syncDirectories([...targetDirectories, sourceParent]);
230
- }
231
- function removeEntryDurably(target) {
232
- rmSync(target, { recursive: true, force: true });
233
- const parent = path.dirname(target);
234
- if (pathEntryExists(parent))
235
- syncDirectory(parent);
236
- }
237
- function assertExpectedTempRoot(root, candidate, kind) {
238
- const resolved = path.resolve(candidate);
239
- const tokenPattern = '(\\d+-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})';
240
- const localParent = path.join(path.resolve(root), TRANSACTION_DIRECTORY);
241
- const localMatch = new RegExp(`^${kind}-${tokenPattern}$`, 'i').exec(path.basename(resolved));
242
- if (path.dirname(resolved) === localParent && localMatch) {
243
- const namespaceStat = lstatIfPresent(localParent);
244
- if (namespaceStat && (namespaceStat.isSymbolicLink() || !namespaceStat.isDirectory())) {
245
- throw new Error(`Unsafe reserved transaction namespace: ${localParent}`);
246
- }
247
- return { token: localMatch[1] };
248
- }
249
- throw new Error(`Unsafe transaction ${kind} root: ${candidate}`);
250
- }
251
- function assertNoSymlinkComponents(root, relativePath) {
252
- resolveTransactionPath(root, relativePath);
253
- let cursor = path.resolve(root);
254
- if (lstatIfPresent(cursor)?.isSymbolicLink()) {
255
- throw new Error(`Refusing transaction root that is a symbolic link: ${root}`);
256
- }
257
- for (const segment of relativePath.split('/')) {
258
- cursor = path.join(cursor, segment);
259
- if (lstatIfPresent(cursor)?.isSymbolicLink()) {
260
- throw new Error(`Refusing transaction path containing a symbolic link: ${relativePath}`);
261
- }
262
- }
263
- }
264
- function assertNoSymlinksRecursively(target) {
265
- const stat = lstatSync(target);
266
- if (stat.isSymbolicLink())
267
- throw new Error(`Refusing symbolic link in staged output: ${target}`);
268
- if (!stat.isDirectory())
269
- return;
270
- for (const entry of readdirSync(target))
271
- assertNoSymlinksRecursively(path.join(target, entry));
272
- }
273
- function assertJournalRoots(root, backupRoot, stageRoot) {
274
- const backupIdentity = assertExpectedTempRoot(root, backupRoot, 'backup');
275
- const stageIdentity = assertExpectedTempRoot(root, stageRoot, 'stage');
276
- if (backupIdentity.token !== stageIdentity.token) {
277
- throw new Error('Transaction stage and backup roots do not share one token.');
278
- }
279
- for (const temporaryRoot of [backupRoot, stageRoot]) {
280
- const stat = lstatIfPresent(temporaryRoot);
281
- if (stat) {
282
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
283
- throw new Error(`Unsafe transaction temporary root: ${temporaryRoot}`);
284
- }
285
- }
286
- }
287
- }
288
- function validateJournal(root, value) {
289
- if (!isRecord(value) || value.version !== JOURNAL_VERSION) {
290
- throw new Error(`Cannot recover unsupported transaction journal at ${path.join(root, JOURNAL_FILE)}`);
291
- }
292
- assertExactObjectKeys(value, ['version', 'backupRoot', 'stageRoot', 'entries', 'createdDirectories'], 'transaction journal');
293
- if (typeof value.backupRoot !== 'string' ||
294
- typeof value.stageRoot !== 'string' ||
295
- !Array.isArray(value.entries)) {
296
- throw new Error(`Invalid transaction journal at ${path.join(root, JOURNAL_FILE)}`);
297
- }
298
- assertJournalRoots(root, value.backupRoot, value.stageRoot);
299
- const seen = new Set();
300
- const entries = value.entries.map((entry, index) => {
301
- if (!isRecord(entry) ||
302
- typeof entry.relativePath !== 'string' ||
303
- typeof entry.installed !== 'boolean') {
304
- throw new Error(`Invalid transaction journal entry at index ${index}`);
305
- }
306
- assertExactObjectKeys(entry, [
307
- 'relativePath',
308
- 'backupPath',
309
- 'installed',
310
- 'installedFingerprint',
311
- ...(Object.hasOwn(entry, 'backupFingerprint') ? ['backupFingerprint'] : []),
312
- ], `transaction journal entry at index ${index}`);
313
- assertRelativePath(entry.relativePath);
314
- if (seen.has(entry.relativePath))
315
- throw new Error(`Duplicate transaction journal path: ${entry.relativePath}`);
316
- seen.add(entry.relativePath);
317
- if (entry.backupPath !== null && typeof entry.backupPath !== 'string') {
318
- throw new Error(`Invalid transaction backup path at index ${index}`);
319
- }
320
- if (Object.hasOwn(entry, 'backupFingerprint') &&
321
- (typeof entry.backupFingerprint !== 'string' ||
322
- !/^[a-f0-9]{64}$/.test(entry.backupFingerprint)))
323
- throw new Error(`Invalid backup transaction fingerprint at index ${index}`);
324
- const installedFingerprint = entry.installedFingerprint;
325
- if (installedFingerprint !== null &&
326
- (typeof installedFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(installedFingerprint))) {
327
- throw new Error(`Invalid installed transaction fingerprint at index ${index}`);
328
- }
329
- if (entry.installed ? installedFingerprint === null : installedFingerprint !== null) {
330
- throw new Error(`Transaction journal entry fingerprint state is inconsistent at index ${index}`);
331
- }
332
- const expectedBackup = resolveTransactionPath(value.backupRoot, entry.relativePath);
333
- if (entry.backupPath !== null &&
334
- path.resolve(entry.backupPath) !== path.resolve(expectedBackup)) {
335
- throw new Error(`Unsafe transaction backup path: ${entry.backupPath}`);
336
- }
337
- return {
338
- relativePath: entry.relativePath,
339
- backupPath: entry.backupPath,
340
- ...(typeof entry.backupFingerprint === 'string'
341
- ? { backupFingerprint: entry.backupFingerprint }
342
- : {}),
343
- installed: entry.installed,
344
- installedFingerprint,
345
- };
346
- });
347
- assertNoPathAncestry(entries.map((entry) => entry.relativePath), 'journal paths');
348
- const rawCreatedDirectories = value.createdDirectories;
349
- if (!Array.isArray(rawCreatedDirectories)) {
350
- throw new Error(`Invalid transaction created-directory inventory at ${path.join(root, JOURNAL_FILE)}`);
351
- }
352
- const createdDirectories = rawCreatedDirectories.map((entry, index) => {
353
- if (typeof entry !== 'string')
354
- throw new Error(`Invalid transaction created directory at index ${index}`);
355
- assertRelativePath(entry);
356
- return entry;
357
- });
358
- if (new Set(createdDirectories).size !== createdDirectories.length) {
359
- throw new Error('Duplicate transaction created-directory path.');
360
- }
361
- for (const directory of createdDirectories) {
362
- if (!entries.some((entry) => entry.relativePath.startsWith(`${directory}/`))) {
363
- throw new Error(`Transaction created directory is not a parent of any journal entry: ${directory}`);
364
- }
365
- }
366
- return {
367
- version: JOURNAL_VERSION,
368
- backupRoot: value.backupRoot,
369
- stageRoot: value.stageRoot,
370
- entries,
371
- createdDirectories,
372
- };
373
- }
374
- function writeJournal(root, journal) {
375
- const journalPath = path.join(root, JOURNAL_FILE);
376
- const temporaryPath = `${journalPath}.tmp-${process.pid}-${randomUUID()}`;
377
- let descriptor = null;
378
- try {
379
- descriptor = openSync(temporaryPath, 'wx', 0o600);
380
- writeFileSync(descriptor, JSON.stringify(journal, null, 2) + '\n', { encoding: 'utf8' });
381
- fsyncSync(descriptor);
382
- const completedDescriptor = descriptor;
383
- descriptor = null;
384
- closeSync(completedDescriptor);
385
- renameSync(temporaryPath, journalPath);
386
- syncDirectory(path.dirname(journalPath));
387
- }
388
- finally {
389
- if (descriptor !== null)
390
- closeSync(descriptor);
391
- rmSync(temporaryPath, { force: true });
392
- }
393
- }
394
- function removeJournal(root) {
395
- const journalPath = path.join(root, JOURNAL_FILE);
396
- try {
397
- unlinkSync(journalPath);
398
- }
399
- catch (error) {
400
- if (error.code === 'ENOENT')
401
- return;
402
- throw error;
403
- }
404
- syncDirectory(path.dirname(journalPath));
405
- }
406
- function removeEmptyTransactionDirectory(root) {
407
- const transactionDirectory = path.join(path.resolve(root), TRANSACTION_DIRECTORY);
408
- try {
409
- rmdirSync(transactionDirectory);
410
- }
411
- catch (error) {
412
- const code = error.code;
413
- // Preserve rejected files/symlinks and the original namespace validation error.
414
- if (!['ENOENT', 'ENOTDIR', 'ENOTEMPTY', 'EEXIST'].includes(code ?? ''))
415
- throw error;
416
- }
417
- }
418
- function cleanupOrphanTransactionRoots(root) {
419
- const transactionDirectory = path.join(path.resolve(root), TRANSACTION_DIRECTORY);
420
- const namespaceStat = lstatIfPresent(transactionDirectory);
421
- if (!namespaceStat)
422
- return;
423
- if (namespaceStat.isSymbolicLink() || !namespaceStat.isDirectory()) {
424
- throw new Error(`Unsafe reserved transaction namespace requires manual inspection: ${transactionDirectory}`);
425
- }
426
- for (const entry of readdirSync(transactionDirectory)) {
427
- if (!LOCAL_TRANSACTION_ROOT_PATTERN.test(entry)) {
428
- throw new Error(`Unknown artifact in reserved transaction namespace requires manual inspection: ${path.join(transactionDirectory, entry)}`);
429
- }
430
- const candidate = path.join(transactionDirectory, entry);
431
- const stat = lstatIfPresent(candidate);
432
- if (!stat)
433
- continue;
434
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
435
- throw new Error(`Unsafe orphan transaction root requires manual inspection: ${candidate}`);
436
- }
437
- rmSync(candidate, { recursive: true });
438
- }
439
- removeEmptyTransactionDirectory(root);
440
- }
441
- function restoreInstalledEntry(root, journal, entry, target) {
442
- if (entry.installed) {
443
- if (pathEntryExists(target)) {
444
- if (entry.installedFingerprint === null) {
445
- throw new Error(`Installed transaction path has no trusted fingerprint: ${entry.relativePath}. ` +
446
- 'Recovery stopped without modifying it; inspect the journal, target, and backup manually.');
447
- }
448
- const actualFingerprint = fingerprintEntry(target);
449
- if (actualFingerprint !== entry.installedFingerprint) {
450
- throw new Error(`Installed transaction path changed after an interrupted commit: ${entry.relativePath}. ` +
451
- 'Recovery stopped without modifying it; inspect the journal, target, and backup manually.');
452
- }
453
- }
454
- removeEntryDurably(target);
455
- entry.installed = false;
456
- entry.installedFingerprint = null;
457
- writeJournal(root, journal);
458
- }
459
- }
460
- function restoreJournal(root, journal) {
461
- for (const entry of [...journal.entries].reverse()) {
462
- assertNoSymlinkComponents(root, entry.relativePath);
463
- const target = resolveTransactionPath(root, entry.relativePath);
464
- restoreInstalledEntry(root, journal, entry, target);
465
- if (entry.backupPath) {
466
- assertNoSymlinkComponents(journal.backupRoot, entry.relativePath);
467
- if (pathEntryExists(entry.backupPath)) {
468
- if (pathEntryExists(target))
469
- throw new Error(`Transaction recovery target was recreated: ${entry.relativePath}. Recovery stopped without modifying it; preserve the journal, target and backup for manual inspection.`);
470
- const backupFingerprint = fingerprintEntry(entry.backupPath);
471
- if (entry.backupFingerprint && entry.backupFingerprint !== backupFingerprint)
472
- throw new Error(`Transaction backup changed: ${entry.relativePath}. Preserve the journal and backup for manual inspection.`);
473
- // Persist original identity before restore so a crash after rename can be replayed.
474
- entry.backupFingerprint = backupFingerprint;
475
- writeJournal(root, journal);
476
- mkdirSync(path.dirname(target), { recursive: true });
477
- renameDurably(entry.backupPath, target, root);
478
- }
479
- else if (!pathEntryExists(target) ||
480
- !entry.backupFingerprint ||
481
- fingerprintEntry(target) !== entry.backupFingerprint) {
482
- throw new Error(`Cannot recover missing transaction backup or unverified target: ${entry.backupPath}. Recovery stopped; preserve the journal and target for manual inspection.`);
483
- }
484
- entry.backupPath = null;
485
- delete entry.backupFingerprint;
486
- writeJournal(root, journal);
487
- }
488
- }
489
- for (const relativePath of [...journal.createdDirectories].sort((left, right) => right.split('/').length - left.split('/').length || right.localeCompare(left))) {
490
- assertNoSymlinkComponents(root, relativePath);
491
- const target = resolveTransactionPath(root, relativePath);
492
- try {
493
- rmdirSync(target);
494
- syncDirectory(path.dirname(target));
495
- }
496
- catch (error) {
497
- const code = error.code;
498
- if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(code ?? ''))
499
- throw error;
500
- }
501
- }
502
- removeJournal(root);
503
- rmSync(journal.stageRoot, { recursive: true, force: true });
504
- rmSync(journal.backupRoot, { recursive: true, force: true });
505
- removeEmptyTransactionDirectory(root);
506
- }
507
- function recoverInterruptedTransactionUnlocked(root) {
508
- const journalPath = path.join(root, JOURNAL_FILE);
509
- if (!pathEntryExists(journalPath))
510
- return false;
511
- if (lstatSync(journalPath).isSymbolicLink()) {
512
- throw new Error(`Refusing symbolic-link transaction journal at ${journalPath}.`);
513
- }
514
- const journal = validateJournal(root, JSON.parse(readBoundedFile(journalPath, 16 * 1024 * 1024).toString('utf8')));
515
- restoreJournal(root, journal);
516
- return true;
517
- }
518
- /** Recover an interrupted commit while holding the same lock used by normal transactions. */
519
- export function recoverInterruptedTransaction(root) {
520
- const lock = acquireTransactionLock(root);
521
- try {
522
- const recovered = recoverInterruptedTransactionUnlocked(root);
523
- cleanupOrphanTransactionRoots(root);
524
- return recovered;
525
- }
526
- finally {
527
- releaseTransactionLock(lock);
528
- }
529
- }
530
- /** The filesystem commit succeeded, but a follow-up action such as install failed. */
531
- export class PostCommitError extends Error {
532
- committedPaths;
533
- constructor(committedPaths, cause) {
534
- const causeMessage = cause instanceof Error ? cause.message : String(cause);
535
- super(`Changes were committed successfully, but the post-commit action failed: ${causeMessage}. ` +
536
- 'The generated files were kept; resolve the failure and rerun the post-commit command.', { cause });
537
- this.name = 'PostCommitError';
538
- this.committedPaths = Object.freeze([...committedPaths]);
539
- }
540
- }
541
- function assertTransactionNamespace(transactionDirectory) {
542
- const namespaceStat = lstatIfPresent(transactionDirectory);
543
- if (namespaceStat && (namespaceStat.isSymbolicLink() || !namespaceStat.isDirectory())) {
544
- throw new Error(`Unsafe reserved transaction namespace requires manual inspection: ${transactionDirectory}`);
545
- }
546
- if (!namespaceStat)
547
- return;
548
- for (const entry of readdirSync(transactionDirectory)) {
549
- const candidate = path.join(transactionDirectory, entry);
550
- const stat = lstatIfPresent(candidate);
551
- if (!LOCAL_TRANSACTION_ROOT_PATTERN.test(entry) ||
552
- !stat ||
553
- stat.isSymbolicLink() ||
554
- !stat.isDirectory()) {
555
- throw new Error(`Unknown or unsafe artifact in reserved transaction namespace requires manual inspection: ${candidate}`);
556
- }
557
- }
558
- }
559
- function seedTransaction(root, stageRoot, seedPaths) {
560
- for (const relativePath of seedPaths) {
561
- assertRelativePath(relativePath);
562
- assertNoSymlinkComponents(root, relativePath);
563
- const source = resolveTransactionPath(root, relativePath);
564
- if (!pathEntryExists(source))
565
- continue;
566
- assertNoSymlinksRecursively(source);
567
- const target = resolveTransactionPath(stageRoot, relativePath);
568
- mkdirSync(path.dirname(target), { recursive: true });
569
- cpSync(source, target, { recursive: true, preserveTimestamps: true });
570
- }
571
- }
572
- function ensureTransactionParents(root, entry, journal, createdDirectorySet) {
573
- const segments = entry.relativePath.split('/').slice(0, -1);
574
- let cursor = root;
575
- let relativeDirectory = '';
576
- const missingDirectories = [];
577
- for (const segment of segments) {
578
- cursor = path.join(cursor, segment);
579
- relativeDirectory = relativeDirectory ? `${relativeDirectory}/${segment}` : segment;
580
- if (!pathEntryExists(cursor))
581
- missingDirectories.push(relativeDirectory);
582
- else if (!lstatSync(cursor).isDirectory()) {
583
- throw new Error(`Transaction parent is not a directory: ${relativeDirectory}`);
584
- }
585
- }
586
- const newDirectories = missingDirectories.filter((directory) => !createdDirectorySet.has(directory));
587
- if (newDirectories.length > 0) {
588
- journal.createdDirectories.push(...newDirectories);
589
- for (const directory of newDirectories)
590
- createdDirectorySet.add(directory);
591
- writeJournal(root, journal);
592
- }
593
- }
594
- function commitJournal(root, journal, deletePaths) {
595
- const { stageRoot, backupRoot } = journal;
596
- const createdDirectorySet = new Set(journal.createdDirectories);
597
- for (const entry of journal.entries) {
598
- const source = resolveTransactionPath(stageRoot, entry.relativePath);
599
- const deleting = deletePaths.has(entry.relativePath);
600
- if (!deleting && !pathEntryExists(source)) {
601
- throw new Error(`Staged output is missing declared path: ${entry.relativePath}`);
602
- }
603
- if (deleting && pathEntryExists(source))
604
- throw new Error(`Deleted transaction path still exists in staging: ${entry.relativePath}`);
605
- assertNoSymlinkComponents(root, entry.relativePath);
606
- if (!deleting) {
607
- assertNoSymlinksRecursively(source);
608
- syncEntryRecursively(source);
609
- }
610
- const target = resolveTransactionPath(root, entry.relativePath);
611
- if (pathEntryExists(target)) {
612
- const backup = resolveTransactionPath(backupRoot, entry.relativePath);
613
- mkdirSync(path.dirname(backup), { recursive: true });
614
- entry.backupPath = backup;
615
- entry.backupFingerprint = fingerprintEntry(target);
616
- writeJournal(root, journal);
617
- renameDurably(target, backup, root);
618
- }
619
- if (!deleting) {
620
- ensureTransactionParents(root, entry, journal, createdDirectorySet);
621
- mkdirSync(path.dirname(target), { recursive: true });
622
- entry.installedFingerprint = fingerprintEntry(source);
623
- entry.installed = true;
624
- writeJournal(root, journal);
625
- renameDurably(source, target, root);
626
- }
627
- }
628
- }
629
- /**
630
- * Build changes away from the destination and install only the declared paths.
631
- * Every replaced path is journaled first, so errors and later invocations can
632
- * restore the original workspace.
633
- */
634
- export async function runStagedTransaction(root, options) {
635
- const lock = acquireTransactionLock(root);
636
- const token = `${process.pid}-${randomUUID()}`;
637
- const transactionDirectory = path.join(path.resolve(root), TRANSACTION_DIRECTORY);
638
- const stageRoot = path.join(transactionDirectory, `stage-${token}`);
639
- const backupRoot = path.join(transactionDirectory, `backup-${token}`);
640
- let namespaceValidated = false;
641
- try {
642
- if (options.dryRun && pathEntryExists(path.join(root, JOURNAL_FILE))) {
643
- throw new Error('Dry-run cannot recover an interrupted transaction. Re-run the original command without --dry-run first.');
644
- }
645
- if (options.recover === false && pathEntryExists(path.join(root, JOURNAL_FILE)))
646
- throw new Error('An interrupted transaction requires recovery before this operation.');
647
- recoverInterruptedTransactionUnlocked(root);
648
- if (!options.dryRun)
649
- cleanupOrphanTransactionRoots(root);
650
- if ((await options.prepare?.()) === false)
651
- return Object.freeze([]);
652
- assertTransactionNamespace(transactionDirectory);
653
- namespaceValidated = true;
654
- mkdirSync(stageRoot, { recursive: true, mode: 0o700 });
655
- mkdirSync(backupRoot, { recursive: true, mode: 0o700 });
656
- seedTransaction(root, stageRoot, options.seedPaths ?? []);
657
- await options.build(stageRoot);
658
- const normalizedPaths = normalizeTransactionPaths(options.commitPaths, options.deletePaths ?? []);
659
- const deletePaths = new Set(normalizedPaths.deletePaths);
660
- const uniquePaths = normalizedPaths.uniquePaths;
661
- options.onPlan?.(Object.freeze([...uniquePaths]));
662
- if (options.dryRun)
663
- return Object.freeze(uniquePaths);
664
- const journal = {
665
- version: JOURNAL_VERSION,
666
- backupRoot,
667
- stageRoot,
668
- createdDirectories: [],
669
- entries: uniquePaths.map((relativePath) => {
670
- assertRelativePath(relativePath);
671
- return { relativePath, backupPath: null, installed: false, installedFingerprint: null };
672
- }),
673
- };
674
- writeJournal(root, journal);
675
- try {
676
- commitJournal(root, journal, deletePaths);
677
- }
678
- catch (error) {
679
- restoreJournal(root, journal);
680
- throw error;
681
- }
682
- removeJournal(root);
683
- rmSync(stageRoot, { recursive: true, force: true });
684
- rmSync(backupRoot, { recursive: true, force: true });
685
- removeEmptyTransactionDirectory(root);
686
- try {
687
- await options.afterCommit?.();
688
- }
689
- catch (error) {
690
- throw new PostCommitError(uniquePaths, error);
691
- }
692
- return Object.freeze(uniquePaths);
693
- }
694
- finally {
695
- try {
696
- if (namespaceValidated && !pathEntryExists(path.join(root, JOURNAL_FILE))) {
697
- rmSync(stageRoot, { recursive: true, force: true });
698
- rmSync(backupRoot, { recursive: true, force: true });
699
- removeEmptyTransactionDirectory(root);
700
- }
701
- }
702
- finally {
703
- releaseTransactionLock(lock);
704
- }
705
- }
706
- }
707
- /** Serialize short source updates with generation/add transactions as well as other writers. */
708
- export function withSourceWriteLock(root, write) {
709
- const lock = acquireTransactionLock(root);
710
- try {
711
- return write();
712
- }
713
- finally {
714
- releaseTransactionLock(lock);
715
- }
716
- }