@xlinklight/testkit 0.0.0-stage → 7.0.0-rc.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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -3
  3. package/content/platform-baseline.sql +273 -0
  4. package/package.json +274 -3
  5. package/src/acceptance-oracle.d.mts +24 -0
  6. package/src/acceptance-oracle.mjs +79 -0
  7. package/src/architecture-database.d.mts +36 -0
  8. package/src/architecture-database.mjs +64 -0
  9. package/src/artifact-build.d.mts +3 -0
  10. package/src/artifact-build.mjs +35 -0
  11. package/src/artifact-declarations.mjs +24 -0
  12. package/src/artifact-graphs.mjs +61 -0
  13. package/src/artifact-lock.mjs +32 -0
  14. package/src/artifact-observation.mjs +50 -0
  15. package/src/artifact-publisher.d.mts +30 -0
  16. package/src/artifact-publisher.mjs +84 -0
  17. package/src/browser-lifecycle.mjs +45 -0
  18. package/src/browser-operation-owner.mjs +28 -0
  19. package/src/cloudflare-browser.d.mts +14 -0
  20. package/src/cloudflare-browser.mjs +41 -0
  21. package/src/cloudflare-build.d.mts +19 -0
  22. package/src/cloudflare-build.mjs +61 -0
  23. package/src/cloudflare-http.d.mts +5 -0
  24. package/src/cloudflare-http.mjs +65 -0
  25. package/src/cloudflare-pages.d.mts +34 -0
  26. package/src/cloudflare-pages.mjs +170 -0
  27. package/src/cloudflare-provider-http.d.mts +8 -0
  28. package/src/cloudflare-provider-http.mjs +32 -0
  29. package/src/cloudflare-worker-package.d.mts +6 -0
  30. package/src/cloudflare-worker-package.mjs +24 -0
  31. package/src/cloudflare-worker-qualification.d.mts +4 -0
  32. package/src/cloudflare-worker-qualification.mjs +63 -0
  33. package/src/cloudflare-workers.d.mts +37 -0
  34. package/src/cloudflare-workers.mjs +90 -0
  35. package/src/cluster-directory.d.mts +16 -0
  36. package/src/cluster-directory.mjs +90 -0
  37. package/src/core-publishing.d.mts +75 -0
  38. package/src/core-publishing.mjs +214 -0
  39. package/src/dev-command-runner.mjs +97 -0
  40. package/src/fixture-path.mjs +19 -0
  41. package/src/function-admission.d.mts +1 -0
  42. package/src/function-admission.mjs +58 -0
  43. package/src/host-artifact.mjs +32 -0
  44. package/src/host-stop.mjs +15 -0
  45. package/src/independent-artifact-qualification.mjs +67 -0
  46. package/src/independent-runtime-qualification.mjs +647 -0
  47. package/src/isolated-browser-child.mjs +29 -0
  48. package/src/isolated-browser.mjs +69 -0
  49. package/src/lifecycle-trace.mjs +32 -0
  50. package/src/managed-native-fixture.d.mts +84 -0
  51. package/src/managed-native-fixture.mjs +209 -0
  52. package/src/native-fixture.mjs +125 -0
  53. package/src/native-platform.mjs +56 -0
  54. package/src/operator-accounts.mjs +103 -0
  55. package/src/operator-vault.d.mts +2 -0
  56. package/src/operator-vault.mjs +9 -0
  57. package/src/owned-process.mjs +75 -0
  58. package/src/owner-build-cli.d.mts +1 -0
  59. package/src/owner-build-cli.mjs +31 -0
  60. package/src/owner-database.mjs +215 -0
  61. package/src/owner-operator-build.d.mts +1 -0
  62. package/src/owner-operator-build.mjs +33 -0
  63. package/src/owner-package-build.d.mts +2 -0
  64. package/src/owner-package-build.mjs +29 -0
  65. package/src/owner-production-browser.mjs +215 -0
  66. package/src/owner-production-instances.mjs +41 -0
  67. package/src/owner-production.d.mts +104 -0
  68. package/src/owner-production.mjs +338 -0
  69. package/src/owner-release.mjs +41 -0
  70. package/src/owner-worker-build.d.mts +3 -0
  71. package/src/owner-worker-build.mjs +83 -0
  72. package/src/prebuilt-build.d.mts +8 -0
  73. package/src/prebuilt-build.mjs +69 -0
  74. package/src/prebuilt-output.d.mts +2 -0
  75. package/src/prebuilt-output.mjs +104 -0
  76. package/src/production-hosts.mjs +38 -0
  77. package/src/publisher-acceptance-host-cli.mjs +23 -0
  78. package/src/publisher-acceptance-owner.mjs +116 -0
  79. package/src/publisher-acceptance-runner.mjs +250 -0
  80. package/src/publisher-acceptance-service.mjs +49 -0
  81. package/src/publisher-acceptance.d.mts +61 -0
  82. package/src/publisher-acceptance.mjs +3 -0
  83. package/src/publishing-source.d.mts +11 -0
  84. package/src/publishing-source.mjs +32 -0
  85. package/src/qualification-function-host.mjs +26 -0
  86. package/src/qualification-route-owner.mjs +64 -0
  87. package/src/qualification-transport.mjs +18 -0
  88. package/src/registry-core-selection.mjs +41 -0
  89. package/src/release-artifact.d.mts +17 -0
  90. package/src/release-artifact.mjs +113 -0
  91. package/src/release-build.d.mts +12 -0
  92. package/src/release-build.mjs +71 -0
  93. package/src/release-cli.d.mts +27 -0
  94. package/src/release-cli.mjs +79 -0
  95. package/src/release-control.mjs +45 -0
  96. package/src/release-coordinator.d.mts +9 -0
  97. package/src/release-coordinator.mjs +222 -0
  98. package/src/release-credentials.d.mts +8 -0
  99. package/src/release-credentials.mjs +97 -0
  100. package/src/release-environment.mjs +60 -0
  101. package/src/release-mutex.d.mts +10 -0
  102. package/src/release-mutex.mjs +38 -0
  103. package/src/release-operator.d.mts +6 -0
  104. package/src/release-operator.mjs +59 -0
  105. package/src/release-supabase.d.mts +7 -0
  106. package/src/release-supabase.mjs +37 -0
  107. package/src/release-vercel.d.mts +22 -0
  108. package/src/release-vercel.mjs +51 -0
  109. package/src/release-writer.d.mts +6 -0
  110. package/src/release-writer.mjs +172 -0
  111. package/src/retained-postgres-shutdown.d.mts +51 -0
  112. package/src/retained-postgres-shutdown.mjs +262 -0
  113. package/src/schema-snapshot.mjs +51 -0
  114. package/src/static-ui-artifact.mjs +54 -0
  115. package/src/static-ui-routes.mjs +3 -0
  116. package/src/temporary-acquisition.mjs +62 -0
  117. package/src/temporary-scope.d.mts +47 -0
  118. package/src/temporary-scope.mjs +268 -0
  119. package/src/unscoped-read.mjs +14 -0
  120. package/src/worker-artifact.mjs +214 -0
@@ -0,0 +1,268 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {randomUUID} from 'node:crypto';
4
+ import {acquireTemporaryScope} from './temporary-acquisition.mjs';
5
+
6
+ const metadataLimit = 8192;
7
+ const fail = code => { throw Error(code); };
8
+ const same = (a, b) => a?.path === b?.path && a?.dev === b?.dev && a?.ino === b?.ino;
9
+ function frozen(value) {
10
+ if (value && typeof value === 'object') { for (const child of Object.values(value)) frozen(child); Object.freeze(value); }
11
+ return value;
12
+ }
13
+ export function temporaryChildClosed(handle) {
14
+ return handle.state.closed === true && !handle.state.stopError
15
+ && (handle.state.stdoutEof === true || handle.child?.stdout?.readableEnded === true)
16
+ && (handle.state.stderrEof === true || handle.child?.stderr?.readableEnded === true);
17
+ }
18
+ function ownerState(pid) {
19
+ try { process.kill(pid, 0); return 'alive'; }
20
+ catch (error) { return error.code === 'ESRCH' ? 'dead' : 'unknown'; }
21
+ }
22
+ function validClosureConfirmation(proof, owner) {
23
+ return proof && typeof proof === 'object' && Object.keys(proof).sort().join(',') === 'evidenceSha256,inputDigest,ownerToken,status'
24
+ && proof.status === 'closed' && proof.ownerToken === owner.token && proof.inputDigest === owner.inputDigest
25
+ && typeof proof.evidenceSha256 === 'string' && /^[a-f0-9]{64}$/.test(proof.evidenceSha256);
26
+ }
27
+
28
+ // One admitted payload per label. This journal owns new attempts only; it never
29
+ // adopts an unregistered historical directory or a package-manager store.
30
+ export function createTemporaryScope({root, scope, label, maximumBytes, inputDigest = null, requiresClosureProof = false, filesystem = fs, probeOwner = ownerState, confirmPreviousClosure}) {
31
+ const io = filesystem, repository = path.resolve(root), directory = path.resolve(scope);
32
+ const relative = path.relative(path.join(repository, 'tmp'), directory);
33
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) fail('TEMPORARY_SCOPE_OUTSIDE_ROOT');
34
+ if (relative.split(path.sep).some(part => ['consumer-pnpm-store', 'node_modules', '.git'].includes(part))) fail('TEMPORARY_SCOPE_PROTECTED');
35
+ if (!/^[a-z][a-z0-9-]*$/.test(label) || !Number.isSafeInteger(maximumBytes) || maximumBytes <= 0) fail('TEMPORARY_SCOPE_INVALID');
36
+ if (inputDigest !== null && !/^[a-f0-9]{64}$/.test(inputDigest)) fail('TEMPORARY_INPUT_DIGEST_INVALID');
37
+ function realDirectory(file) {
38
+ for (let p = path.resolve(file);; p = path.dirname(p)) {
39
+ const stat = io.lstatSync(p);
40
+ if (!stat.isDirectory() || stat.isSymbolicLink()) fail('TEMPORARY_LINKED_DIRECTORY');
41
+ if (p === path.dirname(p)) break;
42
+ }
43
+ const stat = io.lstatSync(file);
44
+ return {path: path.resolve(file), dev: String(stat.dev), ino: String(stat.ino)};
45
+ }
46
+ realDirectory(repository);
47
+ for (let p = directory; p !== repository; p = path.dirname(p)) {
48
+ if (io.existsSync(p)) realDirectory(p);
49
+ }
50
+ if (!io.existsSync(directory)) io.mkdirSync(directory, {recursive: true, mode: 0o700});
51
+ const rootIdentity = realDirectory(repository), scopeIdentity = realDirectory(directory);
52
+ const journal = path.join(directory, label + '-owner.json'), closeout = path.join(directory, label + '-closeout.json');
53
+ const prefix = label + '-';
54
+ const slot = path.join(directory, label + '-slot');
55
+ function verifyScope() {
56
+ if (!same(rootIdentity, realDirectory(repository)) || !same(scopeIdentity, realDirectory(directory))) fail('TEMPORARY_SCOPE_IDENTITY_CHANGED');
57
+ }
58
+ function write(file, value, exclusive = false) {
59
+ verifyScope();
60
+ const body = JSON.stringify(value) + '\n';
61
+ if (Buffer.byteLength(body) > metadataLimit) fail('TEMPORARY_METADATA_LIMIT');
62
+ if (io.existsSync(file)) {
63
+ const stat = io.lstatSync(file);
64
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) fail('TEMPORARY_METADATA_CHANGED');
65
+ }
66
+ io.writeFileSync(file, body, {mode: 0o600, flag: exclusive ? 'wx' : 'w'});
67
+ }
68
+ function readDocument(file = journal) {
69
+ verifyScope();
70
+ const before = io.lstatSync(file);
71
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size > metadataLimit) fail('TEMPORARY_METADATA_CHANGED');
72
+ const body = io.readFileSync(file, 'utf8'), after = io.lstatSync(file);
73
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || Buffer.byteLength(body) !== after.size) fail('TEMPORARY_METADATA_CHANGED');
74
+ return {value: JSON.parse(body), body, identity: {path: file, dev: String(before.dev), ino: String(before.ino)}};
75
+ }
76
+ function read(file = journal) { return readDocument(file).value; }
77
+ function storeVerifiedClosure(original, previous, proof) {
78
+ const record = {...previous, state: 'closed', closureConfirmation: proof};
79
+ const pending = path.join(directory, label + '-owner-' + previous.token + '.next');
80
+ const staged = io.existsSync(pending);
81
+ if (staged && io.lstatSync(pending).size > metadataLimit) fail('TEMPORARY_METADATA_CHANGED');
82
+ write(pending, record, !staged);
83
+ if (readDocument(pending).body !== JSON.stringify(record) + '\n') fail('TEMPORARY_OWNER_CHANGED');
84
+ const current = readDocument();
85
+ if (!same(original.identity, current.identity) || original.body !== current.body) fail('TEMPORARY_OWNER_CHANGED');
86
+ verifyScope();
87
+ io.renameSync(pending, journal);
88
+ }
89
+ function attempts() {
90
+ return io.readdirSync(directory).filter(name => name.startsWith(prefix) && io.lstatSync(path.join(directory, name)).isDirectory());
91
+ }
92
+ function validate(record) {
93
+ if (record.version !== 1 || record.label !== label || !same(record.root, rootIdentity) || !same(record.scope, scopeIdentity) || !Number.isSafeInteger(record.ownerPid) || record.ownerPid <= 0 || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.token ?? '') || typeof record.requiresClosureProof !== 'boolean' || !Array.isArray(record.children) || record.children.length > 64) fail('TEMPORARY_OWNER_UNKNOWN');
94
+ if (record.inputDigest !== null && !/^[a-f0-9]{64}$/.test(record.inputDigest ?? '')) fail('TEMPORARY_OWNER_UNKNOWN');
95
+ if (record.payload && record.payload.path !== slot) fail('TEMPORARY_OWNER_UNKNOWN');
96
+ if (record.children.some(pid => !Number.isSafeInteger(pid) || pid <= 0)) fail('TEMPORARY_OWNER_UNKNOWN');
97
+ if (record.closureConfirmation !== undefined && (record.state !== 'closed' || !validClosureConfirmation(record.closureConfirmation, record))) fail('TEMPORARY_OWNER_UNKNOWN');
98
+ }
99
+ function verifyPayload(record) {
100
+ verifyScope(); validate(record);
101
+ if (!record.payload || !same(record.payload, realDirectory(record.payload.path))) fail('TEMPORARY_PAYLOAD_IDENTITY_CHANGED');
102
+ }
103
+ function verifyEvidence(identity) {
104
+ verifyScope();
105
+ const relative = path.relative(path.join(repository, 'tmp'), identity?.path ?? repository);
106
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)
107
+ || !same(identity, realDirectory(identity.path))) fail('TEMPORARY_EVIDENCE_CHANGED');
108
+ }
109
+ function remove(record) {
110
+ verifyPayload(record);
111
+ // Node's recursive rm unlinks internal symbolic links; it does not traverse
112
+ // their targets. The owned root itself must remain the original real inode.
113
+ io.rmSync(record.payload.path, {recursive: true});
114
+ }
115
+ let confirmedClosure;
116
+ function writeCloseout(value) { write(closeout, {version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, ...(confirmedClosure ? {previousClosure: confirmedClosure} : {}), ...value}); }
117
+ const release = acquireTemporaryScope({io, directory, label, probeOwner, verifyScope});
118
+ let acquisitionError;
119
+ try {
120
+ let previousInputMatched = false, recovery;
121
+ if (io.existsSync(closeout)) {
122
+ const previous = read(closeout);
123
+ if (previous.version !== 1 || previous.label !== label || !same(previous.root, rootIdentity) || !same(previous.scope, scopeIdentity)) fail('TEMPORARY_CLOSEOUT_UNKNOWN');
124
+ previousInputMatched = inputDigest !== null && previous.inputDigest === inputDigest && previous.status === 'success' && previous.closed === true && previous.removed === true && !io.existsSync(journal);
125
+ }
126
+ if (io.existsSync(journal)) {
127
+ const original = readDocument(), previous = original.value; validate(previous);
128
+ const found = attempts();
129
+ if (found.some(name => path.join(directory, name) !== previous.payload?.path)) fail('TEMPORARY_UNREGISTERED_ATTEMPT');
130
+ const state = probeOwner(previous.ownerPid);
131
+ if (state === 'alive') fail('TEMPORARY_SCOPE_BUSY');
132
+ if (state !== 'dead' || previous.launching || previous.children.some(pid => probeOwner(pid) !== 'dead')) fail('TEMPORARY_OWNER_UNKNOWN');
133
+ if (previous.closureConfirmation) confirmedClosure = frozen(previous.closureConfirmation);
134
+ if ((previous.requiresClosureProof || previous.children.length) && previous.state !== 'closed') {
135
+ if (typeof confirmPreviousClosure !== 'function') fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
136
+ if (previous.launching !== false || !['active', 'blocked'].includes(previous.state)) fail('TEMPORARY_OWNER_UNKNOWN');
137
+ verifyPayload(previous); if (previous.evidence) verifyEvidence(previous.evidence);
138
+ // Only a trusted local-tool owner may confirm its original resource
139
+ // evidence. Dead PIDs alone never prove native/tree/output closure.
140
+ const {token, ...metadata} = structuredClone(previous), view = frozen({...metadata, ownerToken: token});
141
+ try {
142
+ const confirmation = confirmPreviousClosure(view);
143
+ if (confirmation instanceof Promise) { void confirmation.catch(() => {}); fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN'); }
144
+ if (!confirmation || typeof confirmation !== 'object' || typeof confirmation.then === 'function') fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
145
+ const proof = structuredClone(confirmation);
146
+ if (!validClosureConfirmation(proof, previous)) fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
147
+ confirmedClosure = frozen(proof);
148
+ } catch { fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN'); }
149
+ verifyPayload(previous); if (previous.evidence) verifyEvidence(previous.evidence);
150
+ if (probeOwner(previous.ownerPid) !== 'dead' || previous.children.some(pid => probeOwner(pid) !== 'dead')) fail('TEMPORARY_OWNER_UNKNOWN');
151
+ // Persist the bound closure before touching the payload. A later
152
+ // acquisition can finish cleanup even if this owner stops mid-closeout.
153
+ const current = readDocument();
154
+ if (!same(original.identity, current.identity) || original.body !== current.body) fail('TEMPORARY_OWNER_CHANGED');
155
+ storeVerifiedClosure(original, previous, confirmedClosure);
156
+ }
157
+ if (previous.payload && io.existsSync(previous.payload.path)) remove(previous);
158
+ else if (previous.payload && previous.state !== 'closed') fail('TEMPORARY_PAYLOAD_IDENTITY_CHANGED');
159
+ recovery = {status: 'recovered', ownerPid: previous.ownerPid, inputDigest: previous.inputDigest, removed: true, ...(confirmedClosure ? {closureConfirmation: confirmedClosure} : {})};
160
+ writeCloseout(recovery);
161
+ io.unlinkSync(journal);
162
+ }
163
+ if (attempts().length) fail('TEMPORARY_UNREGISTERED_ATTEMPT');
164
+ const record = {version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, ownerPid: process.pid, token: randomUUID(), payload: null, children: [], launching: false, requiresClosureProof, state: 'allocating'};
165
+ write(journal, record, true);
166
+ let completed;
167
+ function verify() {
168
+ const stored = read();
169
+ if (stored.token !== record.token || JSON.stringify(stored) !== JSON.stringify(record)) fail('TEMPORARY_OWNER_CHANGED');
170
+ verifyPayload(record);
171
+ }
172
+ function finish({status, closed}) {
173
+ if (completed) return completed;
174
+ verify();
175
+ if (closed !== true || record.launching) {
176
+ record.state = 'blocked'; write(journal, record);
177
+ writeCloseout({status: 'closure-unknown', removed: false, closed: false});
178
+ fail('TEMPORARY_CLOSURE_UNKNOWN');
179
+ }
180
+ record.state = 'closed'; write(journal, record);
181
+ try { remove(record); }
182
+ catch (error) {
183
+ writeCloseout({status: 'cleanup-failed', removed: false, closed: true, error: String(error.code ?? error.message).slice(0, 512)});
184
+ throw error;
185
+ }
186
+ completed = Object.freeze({version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, status: String(status).slice(0, 64), directory: record.payload.path, ownerPid: record.ownerPid, closed: true, removed: true, ...(confirmedClosure ? {previousClosure: confirmedClosure} : {})});
187
+ writeCloseout(completed); io.unlinkSync(journal);
188
+ return completed;
189
+ }
190
+ try {
191
+ io.mkdirSync(slot, {mode: 0o700});
192
+ record.payload = realDirectory(slot); record.state = 'active'; write(journal, record);
193
+ writeCloseout({status: 'active', closed: false, removed: false});
194
+ } catch (error) {
195
+ try {
196
+ if (record.payload) { write(journal, record); finish({status: 'initialization-failed', closed: true}); }
197
+ else { writeCloseout({status: 'initialization-failed', removed: false, closed: false}); io.unlinkSync(journal); }
198
+ } catch (cleanupError) { error.cleanupError = cleanupError; }
199
+ throw error;
200
+ }
201
+ return {
202
+ directory: record.payload.path, token: record.token, verify, finish, previousInputMatched, recovery,
203
+ registerEvidence(directory) { verify(); if (record.evidence) fail('TEMPORARY_EVIDENCE_ALREADY_REGISTERED'); const identity = realDirectory(directory); verifyEvidence(identity); record.evidence = identity; write(journal, record); },
204
+ beginLaunch() { verify(); if (record.launching || record.children.length >= 64) fail('TEMPORARY_CHILD_LIMIT'); record.launching = true; write(journal, record); },
205
+ trackPid(pid) { verify(); if (!Number.isSafeInteger(pid) || pid <= 0) fail('TEMPORARY_CHILD_IDENTITY_UNKNOWN'); record.children.push(pid); record.launching = false; write(journal, record); },
206
+ checkBudget() {
207
+ verify(); let bytes = 0, entries = 0; const stack = [record.payload.path];
208
+ while (stack.length) {
209
+ if (++entries > 100000) fail('TEMPORARY_ENTRY_LIMIT');
210
+ const file = stack.pop(), stat = io.lstatSync(file);
211
+ if (stat.isSymbolicLink()) bytes += Buffer.byteLength(io.readlinkSync(file));
212
+ else if (stat.isDirectory()) for (const name of io.readdirSync(file)) stack.push(path.join(file, name));
213
+ else if (stat.isFile()) bytes += stat.size;
214
+ else fail('TEMPORARY_FILE_TYPE_UNKNOWN');
215
+ if (bytes > maximumBytes) fail('TEMPORARY_BUDGET_EXCEEDED');
216
+ }
217
+ verify(); return {bytes, entries};
218
+ },
219
+ };
220
+ } catch (error) { acquisitionError = error; throw error; }
221
+ finally {
222
+ try { release(); }
223
+ catch (releaseError) { if (acquisitionError) acquisitionError.releaseError = releaseError; else throw releaseError; }
224
+ }
225
+ }
226
+
227
+ // Ordinary verification keeps one bounded result. Generated fixtures and tool
228
+ // output belong to the fixed payload; an unresolved owner blocks another run.
229
+ export function createVerificationRun({root,scope,label,maximumBytes,inputDigest=null,filesystem=fs,probeOwner,confirmPreviousClosure}) {
230
+ const io=filesystem,owner=createTemporaryScope({root,scope,label,maximumBytes,inputDigest,requiresClosureProof:true,filesystem:io,probeOwner,confirmPreviousClosure});
231
+ const resultFile=path.join(path.resolve(scope),label+'-results.json');
232
+ const stat=io.lstatSync(path.resolve(scope));
233
+ const binding={version:1,label,root:path.resolve(root),scope:path.resolve(scope),dev:String(stat.dev),ino:String(stat.ino)};
234
+ function validateResult(){
235
+ if(!io.existsSync(resultFile))return false;
236
+ const before=io.lstatSync(resultFile);
237
+ if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1||before.size>65536)fail('VERIFICATION_RESULT_CHANGED');
238
+ const bytes=io.readFileSync(resultFile,'utf8'),after=io.lstatSync(resultFile);
239
+ if(before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||Buffer.byteLength(bytes)!==after.size)fail('VERIFICATION_RESULT_CHANGED');
240
+ const previous=JSON.parse(bytes);
241
+ if(Object.entries(binding).some(([key,value])=>previous[key]!==value))fail('VERIFICATION_RESULT_UNOWNED');
242
+ return true;
243
+ }
244
+ function publish(result){
245
+ const body=JSON.stringify({...binding,ownerToken:owner.token,result})+'\n';
246
+ if(Buffer.byteLength(body)>65536)fail('VERIFICATION_RESULT_LIMIT');
247
+ const existed=validateResult();io.writeFileSync(resultFile,body,{flag:existed?'w':'wx',mode:0o600});
248
+ }
249
+ try{publish({status:'RUNNING',inputDigest});}catch(error){try{owner.finish({status:'initialization-failed',closed:true});}catch(cleanupError){error.cleanupError=cleanupError;}throw error;}
250
+ return {directory:owner.directory,resultFile,checkBudget:owner.checkBudget,finish({result,closed}){
251
+ owner.verify();
252
+ let budgetFailure;
253
+ try{owner.checkBudget();}catch(error){budgetFailure=error;result={...result,status:'FAIL',budgetError:String(error)};}
254
+ try{publish({...result,status:closed===true?'FINALIZING':'FAIL',closed,artifactsRetained:true});}
255
+ catch(error){if(budgetFailure){budgetFailure.publishError=error;throw budgetFailure;}throw error;}
256
+ let receipt;
257
+ try{
258
+ receipt=owner.finish({status:result.status==='PASS'?'success':'failure',closed});
259
+ publish({...result,closed:true,artifactsRetained:false});
260
+ }
261
+ catch(error){
262
+ try{publish({...result,status:'FAIL',closed,artifactsRetained:receipt?.removed!==true,cleanupError:String(error)});}catch(publishError){error.publishError=publishError;}
263
+ if(budgetFailure){budgetFailure.cleanupError=error;throw budgetFailure;}throw error;
264
+ }
265
+ if(budgetFailure)throw budgetFailure;
266
+ return receipt;
267
+ }};
268
+ }
@@ -0,0 +1,14 @@
1
+ import assert from 'node:assert/strict';
2
+
3
+ /** An unscoped read may return no rows or be rejected by the platform RLS fence. */
4
+ export async function assertUnscopedRead(pool,domain){
5
+ for(const relation of domain.relations){
6
+ let reply;
7
+ try{reply=await pool.query(`select * from ${domain.schema}.${relation.name}`);}
8
+ catch(error){
9
+ if(error.code!=='42501'||error.routine!=='exec_stmt_raise'||typeof error.where!=='string'||!error.where.includes('function platform_private.lock_authorization()'))throw error;
10
+ continue;
11
+ }
12
+ assert.equal(reply.rowCount,0,'Unscoped reads must never expose rows');
13
+ }
14
+ }
@@ -0,0 +1,214 @@
1
+ import assert from 'node:assert/strict';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {createHash} from 'node:crypto';
5
+ import {performance} from 'node:perf_hooks';
6
+
7
+ const digest=body=>createHash('sha256').update(body).digest('hex');
8
+ const inside=(root,file)=>{const relative=path.relative(root,file);assert(relative!== '..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative),'WORKER_ARTIFACT_BOUNDARY');return file;};
9
+ const portable=file=>file.split(path.sep).join('/');
10
+ export const workerArtifactLimits=Object.freeze({maximumPayloadBytes:64*1024**2,maximumFiles:8192,maximumPathBytes:1024,entriesPerFile:4});
11
+ function ownedOutput(root,destination,maximumBytes,maximumFiles,maximumFileBytes=maximumBytes){
12
+ try{
13
+ const info=fs.lstatSync(destination);assert(info.isDirectory()&&!info.isSymbolicLink()&&fs.realpathSync(destination)===destination);
14
+ const receiptFile=path.join(destination,'worker-artifact.json'),receiptInfo=fs.lstatSync(receiptFile);assert(receiptInfo.isFile()&&!receiptInfo.isSymbolicLink()&&receiptInfo.size<=2097152);
15
+ const body=fs.readFileSync(receiptFile),manifest=JSON.parse(body);
16
+ assert(manifest.schemaVersion===1&&manifest.status==='WORKER_ARTIFACT_PREPARED'&&Array.isArray(manifest.files)&&manifest.files.length<maximumFiles&&Number.isSafeInteger(manifest.payloadBytes)&&manifest.payloadBytes>=0&&manifest.payloadBytes+body.length<=maximumBytes);
17
+ const files=new Map();let bytes=0;
18
+ for(const record of manifest.files){
19
+ assert(typeof record.path==='string'&&Buffer.byteLength(record.path)<=workerArtifactLimits.maximumPathBytes&&!/[\\:\0\r\n]/.test(record.path)&&!record.path.startsWith('/')&&record.path.split('/').every(part=>part&&part!=='.'&&part!=='..')&&!files.has(record.path)&&record.path!=='worker-artifact.json');
20
+ assert(Number.isSafeInteger(record.bytes)&&record.bytes>=0&&record.bytes<=maximumFileBytes&&/^[a-f0-9]{64}$/.test(record.sha256));bytes+=record.bytes;assert(bytes<=maximumBytes);files.set(record.path,record);
21
+ }
22
+ assert(bytes===manifest.payloadBytes&&files.has(manifest.entry)&&files.has('package.json'));
23
+ const expected=[...files.keys()];let visited=0;
24
+ const walk=filename=>{
25
+ assert(++visited<=maximumFiles*4);const relative=portable(path.relative(destination,filename)),stat=fs.lstatSync(filename);
26
+ if(stat.isDirectory()&&!stat.isSymbolicLink()){assert(!relative||expected.some(name=>name.startsWith(relative+'/')));for(const name of fs.readdirSync(filename))walk(path.join(filename,name));return;}
27
+ if(relative==='worker-artifact.json')return;
28
+ const record=files.get(relative);assert(record);
29
+ if(Object.hasOwn(record,'link')){assert(stat.isSymbolicLink()&&record.bytes===0&&typeof record.link==='string'&&record.link.length>0&&Buffer.byteLength(record.link)<=workerArtifactLimits.maximumPathBytes&&digest(record.link)===record.sha256);const target=inside(destination,fs.realpathSync(filename));assert(target!==destination&&path.resolve(path.dirname(filename),record.link)===target);}
30
+ else{assert(stat.isFile()&&!stat.isSymbolicLink()&&stat.size===record.bytes&&digest(fs.readFileSync(filename))===record.sha256);}
31
+ files.delete(relative);
32
+ };
33
+ walk(destination);assert(files.size===0);
34
+ assert(JSON.parse(fs.readFileSync(path.join(destination,'package.json'),'utf8')).name===JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8')).name);
35
+ return {dev:info.dev,ino:info.ino,digest:digest(body)};
36
+ }catch{assert.fail('WORKER_ARTIFACT_REPLACEMENT');}
37
+ }
38
+ /** Read-only final build-stage check. Run immediately before the runtime COPY,
39
+ * after every application build command, so an unreceipted extra file cannot
40
+ * invalidate the image-size admission bound. */
41
+ export function verifyWorkerArtifact({root,output}){
42
+ root=fs.realpathSync(root);assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');
43
+ const destination=path.resolve(root,output);assert(path.relative(root,destination).startsWith('tmp'+path.sep),'WORKER_ARTIFACT_OUTPUT');
44
+ ownedOutput(root,destination,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles);
45
+ const manifest=JSON.parse(fs.readFileSync(path.join(destination,'worker-artifact.json'),'utf8'));
46
+ return {status:'WORKER_ARTIFACT_VERIFIED',files:manifest.files.length+1,payloadBytes:manifest.payloadBytes};
47
+ }
48
+
49
+ // Preserve the verified relative resolver links. Expanding a package directory
50
+ // changes Node's realpath-based transitive dependency lookup. All link targets
51
+ // are part of the same pruned payload; no installation/source fallback is used.
52
+ function functionWorker(source,manifest){
53
+ const files=[];let bytes=0;
54
+ for(const record of manifest.files){
55
+ const relative=record.path,selected=path.join(source,relative);assert(files.length<workerArtifactLimits.maximumFiles-1,'FUNCTION_FILE_LIMIT');
56
+ if(Object.hasOwn(record,'link')){
57
+ const target=inside(source,fs.realpathSync(selected)),raw=fs.readlinkSync(selected);assert(!path.isAbsolute(record.link)&&!path.isAbsolute(raw)&&portable(raw)===record.link,'FUNCTION_LINK_INVALID');
58
+ bytes+=Buffer.byteLength(record.link);assert(bytes<=workerArtifactLimits.maximumPayloadBytes,'FUNCTION_BYTE_LIMIT');
59
+ files.push({...record,directory:fs.statSync(target).isDirectory()});continue;
60
+ }
61
+ assert(record.bytes<=workerArtifactLimits.maximumPayloadBytes-bytes,'FUNCTION_BYTE_LIMIT');
62
+ const body=fs.readFileSync(selected);assert(body.length===record.bytes&&digest(body)===record.sha256,'FUNCTION_SOURCE_CHANGED');
63
+ // A native Windows runtime cannot establish Linux Function compatibility.
64
+ assert(!/\.(?:dll|exe|pdb)$/i.test(relative)&&(!/\.node$/i.test(relative)||body.length>=20&&body.subarray(0,4).equals(Buffer.from([127,69,76,70]))&&body[4]===2&&body[5]===1&&body.readUInt16LE(18)===62),'FUNCTION_NATIVE_TARGET_INVALID');
65
+ bytes+=body.length;files.push({...record,body});
66
+ }
67
+ const receipt=fs.readFileSync(path.join(source,'worker-artifact.json'));
68
+ assert(bytes+receipt.length<=workerArtifactLimits.maximumPayloadBytes,'FUNCTION_BYTE_LIMIT');
69
+ return {files,receipt,digest:digest(receipt),bytes:bytes+receipt.length};
70
+ }
71
+
72
+ /** Capture the same verified Node closure without materializing resolver links
73
+ * into a publication format. No provider API or local runtime is invoked. */
74
+ export function readWorkerArtifact({root,output,maximumBytes=workerArtifactLimits.maximumPayloadBytes,maximumFiles=workerArtifactLimits.maximumFiles,maximumFileBytes=maximumBytes}){
75
+ root=fs.realpathSync(root);assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');const source=path.resolve(root,output);assert(path.relative(root,source).startsWith('tmp'+path.sep),'WORKER_ARTIFACT_OUTPUT');
76
+ assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=workerArtifactLimits.maximumPayloadBytes&&Number.isSafeInteger(maximumFiles)&&maximumFiles>0&&maximumFiles<=workerArtifactLimits.maximumFiles&&Number.isSafeInteger(maximumFileBytes)&&maximumFileBytes>0&&maximumFileBytes<=maximumBytes,'WORKER_ARTIFACT_LIMIT_INVALID');
77
+ const identity=ownedOutput(root,source,maximumBytes,maximumFiles,maximumFileBytes),manifest=JSON.parse(fs.readFileSync(path.join(source,'worker-artifact.json')));
78
+ const captured=functionWorker(source,manifest);assert.deepEqual(ownedOutput(root,source,maximumBytes,maximumFiles,maximumFileBytes),identity,'WORKER_ARTIFACT_SOURCE_CHANGED');
79
+ return {entry:manifest.entry,files:captured.files.map(file=>Object.hasOwn(file,'link')?{path:file.path,link:file.link,directory:file.directory}:{path:file.path,bytes:file.body}),receipt:captured.receipt,payloadBytes:captured.bytes};
80
+ }
81
+
82
+ /** Add exact-path Node functions to a freshly built Build Output API v3 tree.
83
+ * Different endpoints have separately budgeted payloads; no billing deduplication
84
+ * is assumed. A changed or interrupted tree must be rebuilt by its build owner. */
85
+ export function emitVercelWorkerFunctions({root,workerOutput,paths,maxDuration,region,maximumBytes=64*1024**2}){
86
+ root=fs.realpathSync(root);
87
+ assert(Array.isArray(paths)&&paths.length>=1&&paths.length<=2&&new Set(paths).size===paths.length,'FUNCTION_PATH_INVALID');
88
+ assert(Number.isSafeInteger(maxDuration)&&maxDuration>=1&&maxDuration<=300,'FUNCTION_DURATION_INVALID');
89
+ assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=128*1024**2,'FUNCTION_BYTE_LIMIT');
90
+ for(const value of paths)assert(typeof value==='string'&&value.startsWith('/')&&value.length<=512&&value.slice(1).split('/').every(part=>/^[A-Za-z0-9._-]+$/.test(part)&&!['.','..'].includes(part)&&!/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part)),'FUNCTION_PATH_INVALID');
91
+ const assertDirectories=selected=>{
92
+ inside(root,selected);let current=root;
93
+ for(const part of path.relative(root,selected).split(path.sep).filter(Boolean)){
94
+ current=path.join(current,part);const info=fs.lstatSync(current,{throwIfNoEntry:false});
95
+ if(!info)break;assert(info.isDirectory()&&!info.isSymbolicLink()&&fs.realpathSync(current)===current,'FUNCTION_OUTPUT_BOUNDARY');
96
+ }
97
+ };
98
+ const output=path.join(root,'.vercel/output'),configFile=path.join(output,'config.json');assertDirectories(output);
99
+ const info=fs.lstatSync(configFile);assert(info.isFile()&&!info.isSymbolicLink()&&info.nlink===1&&info.size<=2*1024**2,'FUNCTION_OUTPUT_INVALID');
100
+ const original=fs.readFileSync(configFile),config=JSON.parse(original);
101
+ assert(config?.version===3&&(config.routes===undefined||Array.isArray(config.routes)&&config.routes.length<=4096),'FUNCTION_OUTPUT_INVALID');
102
+ verifyWorkerArtifact({root,output:workerOutput});
103
+ const source=path.resolve(root,workerOutput),identity=ownedOutput(root,source,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles);
104
+ const manifest=JSON.parse(fs.readFileSync(path.join(source,'worker-artifact.json')));
105
+ const materialized=functionWorker(source,manifest);
106
+ const wrapper=Buffer.from('export { default } from '+JSON.stringify('./runtime/'+manifest.entry)+';\n');
107
+ const functionConfig=Buffer.from(JSON.stringify({runtime:'nodejs24.x',handler:'index.mjs',launcherType:'Nodejs',shouldAddHelpers:false,memory:2048,maxDuration,...(region===undefined?{}:{regions:[region]})})+'\n');
108
+ const routes=paths.map(value=>({src:'^'+value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')+'$',dest:value})),sources=new Set(routes.map(route=>route.src));
109
+ for(const route of config.routes??[])if(sources.has(route?.src))assert(routes.some(selected=>JSON.stringify(selected)===JSON.stringify(route)),'FUNCTION_ROUTE_CONFLICT');
110
+ const configBytes=Buffer.from(JSON.stringify({...config,routes:[...routes,...(config.routes??[]).filter(route=>!sources.has(route?.src))]},null,2)+'\n');
111
+ const bytes=paths.length*(materialized.bytes+wrapper.length+functionConfig.length)+configBytes.length;
112
+ assert(bytes<=maximumBytes,'FUNCTION_BYTE_LIMIT');
113
+ const selected=paths.map(value=>{
114
+ const destination=path.join(output,'functions',value.slice(1)+'.func');assertDirectories(destination);
115
+ const exists=fs.existsSync(destination);
116
+ if(exists){
117
+ try{
118
+ assert.deepEqual(fs.readdirSync(destination).sort(),['.vc-config.json','index.mjs','runtime']);
119
+ for(const [name,body]of [['.vc-config.json',functionConfig],['index.mjs',wrapper]]){const file=path.join(destination,name),stat=fs.lstatSync(file);assert(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&fs.readFileSync(file).equals(body));}
120
+ assert.equal(ownedOutput(root,path.join(destination,'runtime'),workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,materialized.digest);
121
+ }catch{assert.fail('FUNCTION_OUTPUT_REBUILD_REQUIRED');}
122
+ }
123
+ return {destination,exists};
124
+ });
125
+ for(const {destination,exists}of selected)if(!exists){
126
+ fs.mkdirSync(destination,{recursive:true});
127
+ for(const file of materialized.files){const target=path.join(destination,'runtime',file.path);fs.mkdirSync(path.dirname(target),{recursive:true});if(!Object.hasOwn(file,'link'))fs.writeFileSync(target,file.body,{flag:'wx'});}
128
+ for(const file of materialized.files)if(Object.hasOwn(file,'link'))fs.symlinkSync(file.link,path.join(destination,'runtime',file.path),file.directory?'dir':'file');
129
+ fs.writeFileSync(path.join(destination,'runtime/worker-artifact.json'),materialized.receipt,{flag:'wx'});
130
+ assert.equal(ownedOutput(root,path.join(destination,'runtime'),workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,materialized.digest,'FUNCTION_SOURCE_CHANGED');
131
+ fs.writeFileSync(path.join(destination,'index.mjs'),wrapper,{flag:'wx'});fs.writeFileSync(path.join(destination,'.vc-config.json'),functionConfig,{flag:'wx'});
132
+ }
133
+ assert.equal(ownedOutput(root,source,workerArtifactLimits.maximumPayloadBytes,workerArtifactLimits.maximumFiles).digest,identity.digest,'FUNCTION_SOURCE_CHANGED');
134
+ assert(fs.readFileSync(configFile).equals(original),'FUNCTION_OUTPUT_CHANGED');
135
+ if(!original.equals(configBytes))fs.writeFileSync(configFile,configBytes);
136
+ return {status:'NODE_FUNCTIONS_PREPARED',functions:paths.length,bytes,paths:[...paths]};
137
+ }
138
+
139
+ /** Package a caller-selected built entry and assets. The caller supplies its pinned
140
+ * tracer and closes all consumers before explicitly replacing a build-only slot. */
141
+ export async function prepareWorkerArtifact({root,entry,output,trace,additionalEntries=[],resources=[],maximumBytes=16*1024**2,maximumFiles=4096,ignore=()=>false,replace=false}){
142
+ const started=performance.now();root=fs.realpathSync(root);
143
+ assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>0&&maximumBytes<=workerArtifactLimits.maximumPayloadBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
144
+ assert(Number.isSafeInteger(maximumFiles)&&maximumFiles>0&&maximumFiles<=workerArtifactLimits.maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
145
+ assert(typeof trace==='function'&&typeof entry==='string'&&!path.isAbsolute(entry),'WORKER_ARTIFACT_INPUT');
146
+ assert(Array.isArray(additionalEntries)&&additionalEntries.length<=32&&Array.isArray(resources)&&resources.length<=32,'WORKER_ARTIFACT_INPUT');
147
+ assert(typeof output==='string'&&!path.isAbsolute(output),'WORKER_ARTIFACT_OUTPUT');
148
+ const destination=path.resolve(root,output),relativeOutput=path.relative(root,destination);
149
+ const existing=fs.lstatSync(destination,{throwIfNoEntry:false});
150
+ assert(typeof replace==='boolean'&&relativeOutput.startsWith('tmp'+path.sep)&&(!existing||replace),'WORKER_ARTIFACT_OUTPUT');
151
+ const previous=existing?ownedOutput(root,destination,maximumBytes,maximumFiles):undefined;
152
+ let parent=path.dirname(destination);
153
+ while(!fs.existsSync(parent))parent=path.dirname(parent);
154
+ assert(fs.realpathSync(parent)===parent,'WORKER_ARTIFACT_OUTPUT');
155
+ const files=new Map(),links=new Map();let bytes=0;
156
+ const add=file=>{
157
+ file=inside(root,path.resolve(root,file));inside(root,fs.realpathSync(file));
158
+ const relative=portable(path.relative(root,file));if(files.has(relative))return;
159
+ assert(Buffer.byteLength(relative)<=workerArtifactLimits.maximumPathBytes,'WORKER_ARTIFACT_PATH_LIMIT');
160
+ const stat=fs.lstatSync(file);assert(stat.isFile()||stat.isSymbolicLink(),'WORKER_ARTIFACT_FILE_TYPE');
161
+ assert(files.size<maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
162
+ if(stat.isSymbolicLink()){
163
+ const target=inside(root,fs.realpathSync(file)),link=portable(path.relative(path.dirname(file),target));assert(Buffer.byteLength(link)<=workerArtifactLimits.maximumPathBytes,'WORKER_ARTIFACT_PATH_LIMIT');links.set(relative,target);files.set(relative,{path:relative,bytes:0,sha256:digest(link),link});return;
164
+ }
165
+ assert(stat.size<=maximumBytes-bytes,'WORKER_ARTIFACT_BYTE_LIMIT');
166
+ let body=fs.readFileSync(file);assert.equal(body.length,stat.size,'WORKER_ARTIFACT_SOURCE_CHANGED');
167
+ if(path.basename(file)==='package.json')assert(!['react','react-dom','next','@xlinklight/workbench'].includes(JSON.parse(body).name),'WORKER_ARTIFACT_UI_DEPENDENCY');
168
+ if(relative==='package.json'){
169
+ const source=JSON.parse(body),metadata={private:true};
170
+ for(const key of ['name','version','type','exports','imports'])if(Object.hasOwn(source,key))metadata[key]=source[key];
171
+ body=Buffer.from(JSON.stringify(metadata)+'\n');
172
+ }
173
+ bytes+=body.length;assert(bytes<=maximumBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
174
+ files.set(relative,{path:relative,bytes:body.length,sha256:digest(body),source:file,body});
175
+ };
176
+ const resolverLinks=new Set();
177
+ const traced=await trace([entry,...additionalEntries].map(file=>{assert(typeof file==='string'&&!path.isAbsolute(file),'WORKER_ARTIFACT_INPUT');return inside(root,path.resolve(root,file));}),{
178
+ base:root,processCwd:root,exportsOnly:true,ignore,
179
+ async readlink(file){
180
+ try{const target=await fs.promises.readlink(file);inside(root,file);inside(root,fs.realpathSync(file));assert(resolverLinks.size<maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');resolverLinks.add(file);return target;}
181
+ catch(error){if(['ENOENT','EINVAL','ENOTDIR'].includes(error.code))return null;throw error;}
182
+ },
183
+ });
184
+ assert.equal(traced.warnings.size,0,'WORKER_ARTIFACT_TRACE_WARNING: '+[...traced.warnings].map(error=>error.message).join('; '));
185
+ for(const file of [...traced.fileList,...resolverLinks].sort())add(file);
186
+ const walk=file=>{
187
+ file=inside(root,path.resolve(root,file));inside(root,fs.realpathSync(file));
188
+ assert(!fs.lstatSync(file).isSymbolicLink(),'WORKER_ARTIFACT_BOUNDARY');
189
+ if(fs.statSync(file).isDirectory())for(const name of fs.readdirSync(file).sort())walk(path.join(file,name));else add(file);
190
+ };
191
+ for(const resource of resources)walk(resource);
192
+ add('package.json');assert(files.has(portable(entry)),'WORKER_ARTIFACT_ENTRY_MISSING');
193
+ for(const [alias,target]of links){
194
+ const selected=portable(path.relative(root,target));assert([...files.keys()].some(file=>file===selected||file.startsWith(selected+'/')),'WORKER_ARTIFACT_LINK_TARGET_MISSING: '+alias);
195
+ }
196
+ const manifest={schemaVersion:1,status:'WORKER_ARTIFACT_PREPARED',entry:portable(entry),files:[...files.values()].map(record=>({path:record.path,bytes:record.bytes,sha256:record.sha256,...(record.link?{link:record.link}:{})})),payloadBytes:bytes};
197
+ const receipt=Buffer.from(JSON.stringify(manifest,null,2)+'\n');assert(bytes+receipt.length<=maximumBytes,'WORKER_ARTIFACT_BYTE_LIMIT');
198
+ assert(files.size+1<=maximumFiles,'WORKER_ARTIFACT_FILE_LIMIT');
199
+ const entries=new Set([...files.keys(),'worker-artifact.json']);
200
+ for(const record of files.keys()){let parent=path.posix.dirname(record);while(parent!=='.'){entries.add(parent);assert(entries.size+1<=maximumFiles*workerArtifactLimits.entriesPerFile,'WORKER_ARTIFACT_ENTRY_LIMIT');parent=path.posix.dirname(parent);}}
201
+ const tracedAt=performance.now();
202
+ if(previous){assert.deepEqual(ownedOutput(root,destination,maximumBytes,maximumFiles),previous,'WORKER_ARTIFACT_REPLACEMENT');fs.rmSync(destination,{recursive:true});}
203
+ fs.mkdirSync(destination,{recursive:true});
204
+ for(const record of files.values())if(!record.link){
205
+ const target=path.join(destination,record.path);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,record.body,{flag:'wx'});
206
+ }
207
+ for(const [alias,target]of links){
208
+ const filename=path.join(destination,alias),selected=path.join(destination,path.relative(root,target));
209
+ assert(fs.existsSync(selected),'WORKER_ARTIFACT_LINK_TARGET_MISSING');fs.mkdirSync(path.dirname(filename),{recursive:true});
210
+ fs.symlinkSync(path.relative(path.dirname(filename),selected),filename,fs.statSync(target).isDirectory()?'dir':'file');
211
+ }
212
+ fs.writeFileSync(path.join(destination,'worker-artifact.json'),receipt,{flag:'wx'});
213
+ return {...manifest,bytes:bytes+receipt.length,output:destination,timings:{traceMs:tracedAt-started,writeMs:performance.now()-tracedAt,totalMs:performance.now()-started}};
214
+ }