@xlinklight/testkit 7.0.0-rc.0 → 7.0.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 (59) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +169 -169
  3. package/package.json +4 -4
  4. package/src/architecture-database.d.mts +36 -36
  5. package/src/architecture-database.mjs +64 -64
  6. package/src/artifact-observation.mjs +50 -50
  7. package/src/browser-lifecycle.mjs +45 -45
  8. package/src/cloudflare-browser.mjs +41 -41
  9. package/src/cloudflare-pages.d.mts +34 -34
  10. package/src/cloudflare-pages.mjs +170 -170
  11. package/src/cloudflare-provider-http.mjs +32 -32
  12. package/src/cluster-directory.d.mts +16 -16
  13. package/src/cluster-directory.mjs +90 -90
  14. package/src/core-publishing.d.mts +75 -75
  15. package/src/core-publishing.mjs +214 -214
  16. package/src/dev-command-runner.mjs +97 -97
  17. package/src/fixture-path.mjs +19 -19
  18. package/src/function-admission.d.mts +1 -1
  19. package/src/function-admission.mjs +58 -58
  20. package/src/host-artifact.mjs +32 -32
  21. package/src/host-stop.mjs +15 -15
  22. package/src/lifecycle-trace.mjs +32 -32
  23. package/src/managed-native-fixture.d.mts +84 -84
  24. package/src/managed-native-fixture.mjs +209 -209
  25. package/src/native-fixture.mjs +125 -125
  26. package/src/native-platform.mjs +56 -56
  27. package/src/operator-accounts.mjs +103 -103
  28. package/src/owned-process.mjs +75 -75
  29. package/src/owner-database.mjs +215 -215
  30. package/src/owner-operator-build.mjs +33 -33
  31. package/src/owner-production-browser.mjs +215 -215
  32. package/src/owner-production-instances.mjs +41 -41
  33. package/src/owner-production.d.mts +104 -104
  34. package/src/owner-production.mjs +338 -338
  35. package/src/owner-worker-build.mjs +83 -83
  36. package/src/prebuilt-output.d.mts +2 -2
  37. package/src/prebuilt-output.mjs +104 -104
  38. package/src/production-hosts.mjs +38 -38
  39. package/src/release-build.mjs +71 -71
  40. package/src/release-control.mjs +45 -45
  41. package/src/release-coordinator.d.mts +9 -9
  42. package/src/release-coordinator.mjs +222 -222
  43. package/src/release-credentials.d.mts +8 -8
  44. package/src/release-credentials.mjs +97 -97
  45. package/src/release-mutex.mjs +38 -38
  46. package/src/release-operator.d.mts +6 -6
  47. package/src/release-operator.mjs +59 -59
  48. package/src/release-supabase.d.mts +7 -7
  49. package/src/release-supabase.mjs +37 -37
  50. package/src/release-vercel.d.mts +22 -22
  51. package/src/release-vercel.mjs +51 -51
  52. package/src/release-writer.d.mts +6 -6
  53. package/src/release-writer.mjs +172 -172
  54. package/src/retained-postgres-shutdown.d.mts +51 -51
  55. package/src/retained-postgres-shutdown.mjs +262 -262
  56. package/src/temporary-acquisition.mjs +62 -62
  57. package/src/temporary-scope.d.mts +47 -47
  58. package/src/temporary-scope.mjs +268 -268
  59. package/src/worker-artifact.mjs +214 -214
@@ -1,83 +1,83 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import {fileURLToPath} from 'node:url';
4
- import {createHash} from 'node:crypto';
5
- import {createVerificationRun} from './temporary-scope.mjs';
6
- import {bundleCloudflareWorker} from './cloudflare-build.mjs';
7
- import {parseCloudflareWorkerPackage} from './cloudflare-worker-package.mjs';
8
-
9
- const fail=()=>Error('OWNER_WORKER_BUILD_INVALID');
10
- const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
11
- const canonical=value=>JSON.stringify(value)+'\n';
12
- function regular(root,relative,maximum=16777216){
13
- if(typeof relative!=='string'||!relative||/[\\:\0-\x1f\x7f]/.test(relative)||relative.split('/').some(part=>!part||part==='.'||part==='..'))throw fail();
14
- const selected=path.resolve(root,relative),suffix=path.relative(root,selected),info=fs.lstatSync(selected);
15
- if(!suffix||suffix.startsWith('..'+path.sep)||path.isAbsolute(suffix)||!info.isFile()||info.isSymbolicLink()||info.size>maximum||fs.realpathSync(selected)!==selected)throw fail();return fs.readFileSync(selected);
16
- }
17
- function json(root,relative,maximum=1048576){return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(regular(root,relative,maximum)));}
18
- function filename(value){return typeof value==='string'&&value&&!/[\\:\0-\x1f\x7f]/.test(value)&&value.split('/').every(part=>part&&part!=='.'&&part!=='..'&&!part.startsWith('.'));}
19
-
20
- /** Read only a complete original byte-bound local Worker artifact. */
21
- export function readOwnerCloudflareWorkerBuild({root,output='dist-worker',maximumFiles=8192,maximumFileBytes=16777216,maximumTotalBytes=67108864}){
22
- if(typeof root!=='string'||!path.isAbsolute(root)||!filename(output)||![maximumFiles,maximumFileBytes,maximumTotalBytes].every(value=>Number.isSafeInteger(value)&&value>0))throw fail();root=fs.realpathSync(root);
23
- const index=json(root,output+'/worker-build.json',8388608),files=[];let total=0;
24
- if(index?.schemaVersion!==1||index.kind!=='cloudflare-worker'||index.entry!=='worker.mjs'||!Array.isArray(index.files)||index.files.length<3||index.files.length>maximumFiles)throw fail();
25
- const names=new Set();for(const record of index.files){if(!filename(record.path)||names.has(record.path)||!Number.isSafeInteger(record.byteLength)||record.byteLength<0||record.byteLength>maximumFileBytes||!/^[a-f0-9]{64}$/.test(record.sha256??''))throw fail();names.add(record.path);const bytes=regular(root,output+'/'+record.path,maximumFileBytes);if(bytes.byteLength!==record.byteLength||sha(bytes)!==record.sha256||(total+=bytes.byteLength)>maximumTotalBytes)throw fail();files.push({path:'server/'+record.path,role:'control',bytes});}
26
- const control=files.find(file=>file.path==='server/cloudflare-worker.json');if(!control)throw fail();
27
- const plan=parseCloudflareWorkerPackage(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(control.bytes)),{descriptor:{runtime:{entry:'server/'+index.entry,links:[]}},files:files.map(file=>({path:file.path,role:file.role}))});
28
- return {index,plan,files,payloadBytes:total};
29
- }
30
-
31
- /** One source-owned build, sealed raw resources and static/AOT catalog. The
32
- * real business-library tarball is already complete before this begins. */
33
- export async function prepareOwnerCloudflareWorkerBuild(options){
34
- const {root:inputRoot,bindingEntry,registration,uiExportNames,resourceEntry,domain,wranglerEntry,signal,compatibilityDate='2026-11-04',compatibilityFlags=['nodejs_compat']}=options??{};
35
- if(!registration?.descriptor||!Array.isArray(uiExportNames)||uiExportNames.some(value=>typeof value!=='string')||!(resourceEntry instanceof URL)||resourceEntry.protocol!=='file:')throw fail();
36
- if(typeof inputRoot!=='string'||!path.isAbsolute(inputRoot)||typeof bindingEntry!=='string'||!path.isAbsolute(bindingEntry)||typeof wranglerEntry!=='string'||!path.isAbsolute(wranglerEntry)||!domain||!/^[a-z][a-z0-9_]{0,62}$/.test(domain.schema??'')||!Array.isArray(domain.relations)||!domain.relations.length||domain.relations.length>128||domain.relations.some(value=>!value||!/^[a-z][a-z0-9_]{0,62}$/.test(value.name??'')||!Array.isArray(value.privileges)||!value.privileges.length||value.privileges.some(name=>!['SELECT','INSERT','UPDATE','DELETE'].includes(name))))throw fail();
37
- signal?.throwIfAborted();const root=fs.realpathSync(inputRoot),relativeBinding=path.relative(root,bindingEntry).split(path.sep).join('/');regular(root,relativeBinding);
38
- const metadata=json(root,'package.json',65536),build=json(root,'deployment/generated/package-build.json',65536),archive=regular(root,'deployment/generated/package.tgz',67108864);
39
- if(build.schemaVersion!==2||build.name!==metadata.name||build.version!==metadata.version||build.integrity!=='sha512-'+createHash('sha512').update(archive).digest('base64'))throw fail();
40
- regular(root,path.relative(root,fileURLToPath(resourceEntry)).split(path.sep).join('/'));
41
- if(registration.descriptor.version!==metadata.version)throw fail();
42
- const [{prepareWorkerCatalog},{metadataDigest},{readPackageResource}]=await Promise.all([import('@xlinklight/platform/build'),import('@xlinklight/platform/worker'),import('@xlinklight/solution-sdk/server')]);
43
- const resources=registration.resources.map(definition=>({definition,bytes:readPackageResource(resourceEntry,definition,1048576)})),profile=json(root,'deployment/runtime-profile.json'),publisher=json(root,'deployment/publisher.json'),target=json(root,'deployment/target.json'),uiReceipt=regular(root,'deployment/generated/ui.json',1048576);
44
- const installation={...profile.installation,packages:[{solutionId:registration.descriptor.solutionId,version:metadata.version,packageName:metadata.name,packageVersion:metadata.version,integrity:build.integrity,uiExportNames,resourceReader:(definition,maximum)=>readPackageResource(resourceEntry,definition,maximum)}]};
45
- const catalog=prepareWorkerCatalog({registration,installation}),resourcesDigest=metadataDigest(registration.resources),uiDigest='sha256:'+sha(uiReceipt),identity={packageName:metadata.name,packageVersion:metadata.version,integrity:build.integrity,resourcesDigest,uiDigest};
46
- const scope=createVerificationRun({root,scope:path.join(root,'tmp/worker-build'),label:'worker-build',maximumBytes:67108864,inputDigest:sha(canonical({identity,domain,catalog:catalog.catalogIdentity,compatibilityDate,compatibilityFlags}))}),slot=scope.directory;
47
- let closed=true,failure,result={status:'FAIL'};
48
- try{
49
- const definitions=resources.map(value=>value.definition),imports=[],entries=[];
50
- for(const [index,item]of resources.entries()){
51
- const relative='resources/'+item.definition.path;if(!filename(relative))throw fail();const selected=path.join(slot,relative);fs.mkdirSync(path.dirname(selected),{recursive:true});fs.writeFileSync(selected,item.bytes);imports.push('import resource'+index+' from '+JSON.stringify('./'+relative)+';');entries.push('{path:'+JSON.stringify(item.definition.path)+',bytes:new Uint8Array(resource'+index+')}');
52
- }
53
- fs.writeFileSync(path.join(slot,'resources.mjs'),imports.join('\n')+'\nimport {createSealedPackageResourceReader,PackageResourceError} from "@xlinklight/solution-sdk/resources-runtime";\nexport const solutionPackageVersion='+JSON.stringify(metadata.version)+';\nconst definitions='+JSON.stringify(definitions)+';\nexport const resourceReader=createSealedPackageResourceReader(['+entries.join(',')+'],{maximumFiles:8192,maximumFileBytes:1048576,maximumTotalBytes:33554432});\nexport function readResourceBytes(name){const definition=definitions.find(value=>value.path===name);if(!definition)throw new PackageResourceError("MISSING_DEFINITION");return resourceReader(definition,1048576);}\n');
54
- fs.writeFileSync(path.join(slot,'catalog.mjs'),catalog.validatorSource);
55
- fs.writeFileSync(path.join(slot,'validators.mjs'),'import validators from "./catalog.mjs";\nexport const getSchemaValidator=name=>validators.validators['+JSON.stringify(registration.descriptor.solutionId+'.')+'+name];\n');
56
- const serializedInstallation={...installation,packages:installation.packages.map(value=>({solutionId:value.solutionId,version:value.version,packageName:value.packageName,packageVersion:value.packageVersion,integrity:value.integrity,uiExportNames:value.uiExportNames}))},bindingImport=path.relative(slot,bindingEntry).split(path.sep).join('/');
57
- const pinnedPublisher={publisherId:publisher.publisherId,enabled:publisher.enabled,keys:publisher.keys};
58
- const code='import {serverBinding} from '+JSON.stringify(bindingImport.startsWith('.')?bindingImport:'./'+bindingImport)+';\nimport {createPreparedRuntimeCatalog,createCloudflareRuntimeHandler,verifyIndependentNodeRelations} from "@xlinklight/platform/worker";\nimport validators from "./catalog.mjs";import {resourceReader} from "./resources.mjs";import serverReceipt from "./release-server.json";\nconst installation='+JSON.stringify(serializedInstallation)+';installation.packages[0].resourceReader=resourceReader;\nconst catalog=createPreparedRuntimeCatalog({registration:serverBinding.registration(),installation,validators,catalogIdentity:'+JSON.stringify(catalog.catalogIdentity)+'});\nlet selectedKeys,handler;\nexport default {async fetch(request,env,context){try{if(typeof env.CORE_RUNTIME_KEYS!=="string"||env.CORE_RUNTIME_KEYS.length>65536)throw Error("CORE_KEYS_REQUIRED");if(!handler||selectedKeys!==env.CORE_RUNTIME_KEYS){handler=createCloudflareRuntimeHandler({binding:serverBinding,installation,catalog,bundle:{...'+JSON.stringify(identity)+',serverReceipt},core:{origin:'+JSON.stringify(target.coreOrigin)+',publisher:'+JSON.stringify(pinnedPublisher)+',verificationKeys:JSON.parse(env.CORE_RUNTIME_KEYS)},database:value=>({application:{database:value.API_DATABASE,role:value.API_DATABASE_ROLE},worker:{database:value.WORKER_DATABASE,role:value.WORKER_DATABASE_ROLE}}),readiness:db=>verifyIndependentNodeRelations(db,'+JSON.stringify(domain)+')});selectedKeys=env.CORE_RUNTIME_KEYS;}return await handler.fetch(request,env,context);}catch{return new Response(JSON.stringify({code:"SERVICE_UNAVAILABLE"}),{status:503,headers:{"content-type":"application/json","cache-control":"no-store"}});}}};\n';
59
- fs.writeFileSync(path.join(slot,'worker.mjs'),code);fs.writeFileSync(path.join(slot,'release-server.json'),'LINK_LIGHT_RECEIPT_NOT_FINAL\n');
60
- closed=false;let bundled;
61
- try{bundled=await bundleCloudflareWorker({root:slot,entry:path.join(slot,'worker.mjs'),output:'output',wranglerEntry,compatibilityDate,compatibilityFlags,rules:[{type:'Text',globs:['**/release-server.json'],fallthrough:false},{type:'Data',globs:['**/resources/**'],fallthrough:false}],signal,timeoutMs:60000,maxOutputBytes:65536,maximumFiles:8192,maximumFileBytes:16777216,maximumTotalBytes:33554432});closed=bundled.process.closed&&bundled.process.stdoutEof&&bundled.process.stderrEof&&!bundled.process.stopError;}
62
- catch(error){const receipt=error.process??error.cause?.cause?.process;closed=receipt?.closed===true&&receipt.stdoutEof===true&&receipt.stderrEof===true&&!receipt.stopError;throw error;}
63
- if(!closed)throw fail();
64
- const files=bundled.files.filter(file=>file.path!=='README.md'&&!file.path.endsWith('.map')).map(file=>({path:file.path===bundled.entry?'worker.mjs':file.path,bytes:file.bytes}));
65
- const main=files.find(file=>file.path==='worker.mjs'),receipt=files.find(file=>file.path==='release-server.json');if(!main||!receipt||Buffer.from(main.bytes).includes(Buffer.from('LINK_LIGHT_RECEIPT_NOT_FINAL')))throw fail();
66
- const types={'.mjs':'esm','.js':'esm','.json':'text','.wasm':'wasm'},modules=files.map(file=>({path:'server/'+file.path,type:file.path.startsWith('resources/')?'data':types[path.posix.extname(file.path)]}));if(modules.some(value=>!value.type))throw fail();
67
- const plan={schemaVersion:1,mainModule:'server/worker.mjs',compatibilityDate,compatibilityFlags,modules,receiptPath:'server/release-server.json'};
68
- files.push({path:'cloudflare-worker.json',bytes:Buffer.from(canonical(plan))});
69
- const receiptFiles=files.filter(file=>file!==receipt).map(file=>({path:'server/'+file.path,bytes:file.bytes.byteLength,sha256:'sha256:'+sha(file.bytes)})).sort((a,b)=>a.path<b.path?-1:1);
70
- receipt.bytes=Buffer.from(canonical({schemaVersion:1,kind:'server',payloadBytes:receiptFiles.reduce((sum,file)=>sum+file.bytes,0),files:receiptFiles}));
71
- const index={schemaVersion:1,kind:'cloudflare-worker',entry:'worker.mjs',...identity,catalogIdentity:catalog.catalogIdentity,graph:bundled.metadata,files:files.map(file=>({path:file.path,byteLength:file.bytes.byteLength,sha256:sha(file.bytes)})).sort((a,b)=>a.path<b.path?-1:1)};
72
- if(Buffer.byteLength(canonical(index))>8388608)throw fail();
73
- parseCloudflareWorkerPackage(plan,{descriptor:{runtime:{entry:plan.mainModule,links:[]}},files:files.map(file=>({path:'server/'+file.path,role:'control'}))});
74
- const output=path.join(root,'dist-worker');if(fs.existsSync(output)){const old=readOwnerCloudflareWorkerBuild({root}),expected=[...old.index.files.map(file=>file.path),'worker-build.json'].sort(),names=[];
75
- for(const value of fs.readdirSync(output,{recursive:true})){const selected=path.join(output,value),portable=value.split(path.sep).join('/'),info=fs.lstatSync(selected);if(info.isSymbolicLink()||fs.realpathSync(selected)!==selected)throw fail();if(info.isFile())names.push(portable);else if(!info.isDirectory()||!expected.some(name=>name.startsWith(portable+'/')))throw fail();}
76
- if(names.sort().join('\n')!==expected.join('\n'))throw fail();for(const file of old.index.files)fs.unlinkSync(path.join(output,file.path));fs.unlinkSync(path.join(output,'worker-build.json'));}
77
- else fs.mkdirSync(output);
78
- for(const file of files){const selected=path.join(output,file.path);fs.mkdirSync(path.dirname(selected),{recursive:true});if(fs.realpathSync(path.dirname(selected))!==path.dirname(selected))throw fail();fs.writeFileSync(selected,file.bytes,{flag:'wx'});}fs.writeFileSync(path.join(output,'worker-build.json'),canonical(index),{flag:'wx'});
79
- scope.checkBudget();result={status:'PASS',entry:index.entry,files:files.length,bytes:files.reduce((sum,file)=>sum+file.bytes.byteLength,0),serverDigest:'sha256:'+sha(receipt.bytes),...identity};
80
- }catch(error){failure=error;result={status:'FAIL',code:error.message,process:error.process??error.cause?.cause?.process};}
81
- finally{try{scope.finish({result,closed});}catch(error){if(failure)failure.cleanupError=error;else failure=error;}}
82
- if(failure){failure.closure={processesClosed:closed,slotRemoved:!fs.existsSync(slot)};throw failure;}return result;
83
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {fileURLToPath} from 'node:url';
4
+ import {createHash} from 'node:crypto';
5
+ import {createVerificationRun} from './temporary-scope.mjs';
6
+ import {bundleCloudflareWorker} from './cloudflare-build.mjs';
7
+ import {parseCloudflareWorkerPackage} from './cloudflare-worker-package.mjs';
8
+
9
+ const fail=()=>Error('OWNER_WORKER_BUILD_INVALID');
10
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
11
+ const canonical=value=>JSON.stringify(value)+'\n';
12
+ function regular(root,relative,maximum=16777216){
13
+ if(typeof relative!=='string'||!relative||/[\\:\0-\x1f\x7f]/.test(relative)||relative.split('/').some(part=>!part||part==='.'||part==='..'))throw fail();
14
+ const selected=path.resolve(root,relative),suffix=path.relative(root,selected),info=fs.lstatSync(selected);
15
+ if(!suffix||suffix.startsWith('..'+path.sep)||path.isAbsolute(suffix)||!info.isFile()||info.isSymbolicLink()||info.size>maximum||fs.realpathSync(selected)!==selected)throw fail();return fs.readFileSync(selected);
16
+ }
17
+ function json(root,relative,maximum=1048576){return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(regular(root,relative,maximum)));}
18
+ function filename(value){return typeof value==='string'&&value&&!/[\\:\0-\x1f\x7f]/.test(value)&&value.split('/').every(part=>part&&part!=='.'&&part!=='..'&&!part.startsWith('.'));}
19
+
20
+ /** Read only a complete original byte-bound local Worker artifact. */
21
+ export function readOwnerCloudflareWorkerBuild({root,output='dist-worker',maximumFiles=8192,maximumFileBytes=16777216,maximumTotalBytes=67108864}){
22
+ if(typeof root!=='string'||!path.isAbsolute(root)||!filename(output)||![maximumFiles,maximumFileBytes,maximumTotalBytes].every(value=>Number.isSafeInteger(value)&&value>0))throw fail();root=fs.realpathSync(root);
23
+ const index=json(root,output+'/worker-build.json',8388608),files=[];let total=0;
24
+ if(index?.schemaVersion!==1||index.kind!=='cloudflare-worker'||index.entry!=='worker.mjs'||!Array.isArray(index.files)||index.files.length<3||index.files.length>maximumFiles)throw fail();
25
+ const names=new Set();for(const record of index.files){if(!filename(record.path)||names.has(record.path)||!Number.isSafeInteger(record.byteLength)||record.byteLength<0||record.byteLength>maximumFileBytes||!/^[a-f0-9]{64}$/.test(record.sha256??''))throw fail();names.add(record.path);const bytes=regular(root,output+'/'+record.path,maximumFileBytes);if(bytes.byteLength!==record.byteLength||sha(bytes)!==record.sha256||(total+=bytes.byteLength)>maximumTotalBytes)throw fail();files.push({path:'server/'+record.path,role:'control',bytes});}
26
+ const control=files.find(file=>file.path==='server/cloudflare-worker.json');if(!control)throw fail();
27
+ const plan=parseCloudflareWorkerPackage(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(control.bytes)),{descriptor:{runtime:{entry:'server/'+index.entry,links:[]}},files:files.map(file=>({path:file.path,role:file.role}))});
28
+ return {index,plan,files,payloadBytes:total};
29
+ }
30
+
31
+ /** One source-owned build, sealed raw resources and static/AOT catalog. The
32
+ * real business-library tarball is already complete before this begins. */
33
+ export async function prepareOwnerCloudflareWorkerBuild(options){
34
+ const {root:inputRoot,bindingEntry,registration,uiExportNames,resourceEntry,domain,wranglerEntry,signal,compatibilityDate='2026-11-04',compatibilityFlags=['nodejs_compat']}=options??{};
35
+ if(!registration?.descriptor||!Array.isArray(uiExportNames)||uiExportNames.some(value=>typeof value!=='string')||!(resourceEntry instanceof URL)||resourceEntry.protocol!=='file:')throw fail();
36
+ if(typeof inputRoot!=='string'||!path.isAbsolute(inputRoot)||typeof bindingEntry!=='string'||!path.isAbsolute(bindingEntry)||typeof wranglerEntry!=='string'||!path.isAbsolute(wranglerEntry)||!domain||!/^[a-z][a-z0-9_]{0,62}$/.test(domain.schema??'')||!Array.isArray(domain.relations)||!domain.relations.length||domain.relations.length>128||domain.relations.some(value=>!value||!/^[a-z][a-z0-9_]{0,62}$/.test(value.name??'')||!Array.isArray(value.privileges)||!value.privileges.length||value.privileges.some(name=>!['SELECT','INSERT','UPDATE','DELETE'].includes(name))))throw fail();
37
+ signal?.throwIfAborted();const root=fs.realpathSync(inputRoot),relativeBinding=path.relative(root,bindingEntry).split(path.sep).join('/');regular(root,relativeBinding);
38
+ const metadata=json(root,'package.json',65536),build=json(root,'deployment/generated/package-build.json',65536),archive=regular(root,'deployment/generated/package.tgz',67108864);
39
+ if(build.schemaVersion!==2||build.name!==metadata.name||build.version!==metadata.version||build.integrity!=='sha512-'+createHash('sha512').update(archive).digest('base64'))throw fail();
40
+ regular(root,path.relative(root,fileURLToPath(resourceEntry)).split(path.sep).join('/'));
41
+ if(registration.descriptor.version!==metadata.version)throw fail();
42
+ const [{prepareWorkerCatalog},{metadataDigest},{readPackageResource}]=await Promise.all([import('@xlinklight/platform/build'),import('@xlinklight/platform/worker'),import('@xlinklight/solution-sdk/server')]);
43
+ const resources=registration.resources.map(definition=>({definition,bytes:readPackageResource(resourceEntry,definition,1048576)})),profile=json(root,'deployment/runtime-profile.json'),publisher=json(root,'deployment/publisher.json'),target=json(root,'deployment/target.json'),uiReceipt=regular(root,'deployment/generated/ui.json',1048576);
44
+ const installation={...profile.installation,packages:[{solutionId:registration.descriptor.solutionId,version:metadata.version,packageName:metadata.name,packageVersion:metadata.version,integrity:build.integrity,uiExportNames,resourceReader:(definition,maximum)=>readPackageResource(resourceEntry,definition,maximum)}]};
45
+ const catalog=prepareWorkerCatalog({registration,installation}),resourcesDigest=metadataDigest(registration.resources),uiDigest='sha256:'+sha(uiReceipt),identity={packageName:metadata.name,packageVersion:metadata.version,integrity:build.integrity,resourcesDigest,uiDigest};
46
+ const scope=createVerificationRun({root,scope:path.join(root,'tmp/worker-build'),label:'worker-build',maximumBytes:67108864,inputDigest:sha(canonical({identity,domain,catalog:catalog.catalogIdentity,compatibilityDate,compatibilityFlags}))}),slot=scope.directory;
47
+ let closed=true,failure,result={status:'FAIL'};
48
+ try{
49
+ const definitions=resources.map(value=>value.definition),imports=[],entries=[];
50
+ for(const [index,item]of resources.entries()){
51
+ const relative='resources/'+item.definition.path;if(!filename(relative))throw fail();const selected=path.join(slot,relative);fs.mkdirSync(path.dirname(selected),{recursive:true});fs.writeFileSync(selected,item.bytes);imports.push('import resource'+index+' from '+JSON.stringify('./'+relative)+';');entries.push('{path:'+JSON.stringify(item.definition.path)+',bytes:new Uint8Array(resource'+index+')}');
52
+ }
53
+ fs.writeFileSync(path.join(slot,'resources.mjs'),imports.join('\n')+'\nimport {createSealedPackageResourceReader,PackageResourceError} from "@xlinklight/solution-sdk/resources-runtime";\nexport const solutionPackageVersion='+JSON.stringify(metadata.version)+';\nconst definitions='+JSON.stringify(definitions)+';\nexport const resourceReader=createSealedPackageResourceReader(['+entries.join(',')+'],{maximumFiles:8192,maximumFileBytes:1048576,maximumTotalBytes:33554432});\nexport function readResourceBytes(name){const definition=definitions.find(value=>value.path===name);if(!definition)throw new PackageResourceError("MISSING_DEFINITION");return resourceReader(definition,1048576);}\n');
54
+ fs.writeFileSync(path.join(slot,'catalog.mjs'),catalog.validatorSource);
55
+ fs.writeFileSync(path.join(slot,'validators.mjs'),'import validators from "./catalog.mjs";\nexport const getSchemaValidator=name=>validators.validators['+JSON.stringify(registration.descriptor.solutionId+'.')+'+name];\n');
56
+ const serializedInstallation={...installation,packages:installation.packages.map(value=>({solutionId:value.solutionId,version:value.version,packageName:value.packageName,packageVersion:value.packageVersion,integrity:value.integrity,uiExportNames:value.uiExportNames}))},bindingImport=path.relative(slot,bindingEntry).split(path.sep).join('/');
57
+ const pinnedPublisher={publisherId:publisher.publisherId,enabled:publisher.enabled,keys:publisher.keys};
58
+ const code='import {serverBinding} from '+JSON.stringify(bindingImport.startsWith('.')?bindingImport:'./'+bindingImport)+';\nimport {createPreparedRuntimeCatalog,createCloudflareRuntimeHandler,verifyIndependentNodeRelations} from "@xlinklight/platform/worker";\nimport validators from "./catalog.mjs";import {resourceReader} from "./resources.mjs";import serverReceipt from "./release-server.json";\nconst installation='+JSON.stringify(serializedInstallation)+';installation.packages[0].resourceReader=resourceReader;\nconst catalog=createPreparedRuntimeCatalog({registration:serverBinding.registration(),installation,validators,catalogIdentity:'+JSON.stringify(catalog.catalogIdentity)+'});\nlet selectedKeys,handler;\nexport default {async fetch(request,env,context){try{if(typeof env.CORE_RUNTIME_KEYS!=="string"||env.CORE_RUNTIME_KEYS.length>65536)throw Error("CORE_KEYS_REQUIRED");if(!handler||selectedKeys!==env.CORE_RUNTIME_KEYS){handler=createCloudflareRuntimeHandler({binding:serverBinding,installation,catalog,bundle:{...'+JSON.stringify(identity)+',serverReceipt},core:{origin:'+JSON.stringify(target.coreOrigin)+',publisher:'+JSON.stringify(pinnedPublisher)+',verificationKeys:JSON.parse(env.CORE_RUNTIME_KEYS)},database:value=>({application:{database:value.API_DATABASE,role:value.API_DATABASE_ROLE},worker:{database:value.WORKER_DATABASE,role:value.WORKER_DATABASE_ROLE}}),readiness:db=>verifyIndependentNodeRelations(db,'+JSON.stringify(domain)+')});selectedKeys=env.CORE_RUNTIME_KEYS;}return await handler.fetch(request,env,context);}catch{return new Response(JSON.stringify({code:"SERVICE_UNAVAILABLE"}),{status:503,headers:{"content-type":"application/json","cache-control":"no-store"}});}}};\n';
59
+ fs.writeFileSync(path.join(slot,'worker.mjs'),code);fs.writeFileSync(path.join(slot,'release-server.json'),'LINK_LIGHT_RECEIPT_NOT_FINAL\n');
60
+ closed=false;let bundled;
61
+ try{bundled=await bundleCloudflareWorker({root:slot,entry:path.join(slot,'worker.mjs'),output:'output',wranglerEntry,compatibilityDate,compatibilityFlags,rules:[{type:'Text',globs:['**/release-server.json'],fallthrough:false},{type:'Data',globs:['**/resources/**'],fallthrough:false}],signal,timeoutMs:60000,maxOutputBytes:65536,maximumFiles:8192,maximumFileBytes:16777216,maximumTotalBytes:33554432});closed=bundled.process.closed&&bundled.process.stdoutEof&&bundled.process.stderrEof&&!bundled.process.stopError;}
62
+ catch(error){const receipt=error.process??error.cause?.cause?.process;closed=receipt?.closed===true&&receipt.stdoutEof===true&&receipt.stderrEof===true&&!receipt.stopError;throw error;}
63
+ if(!closed)throw fail();
64
+ const files=bundled.files.filter(file=>file.path!=='README.md'&&!file.path.endsWith('.map')).map(file=>({path:file.path===bundled.entry?'worker.mjs':file.path,bytes:file.bytes}));
65
+ const main=files.find(file=>file.path==='worker.mjs'),receipt=files.find(file=>file.path==='release-server.json');if(!main||!receipt||Buffer.from(main.bytes).includes(Buffer.from('LINK_LIGHT_RECEIPT_NOT_FINAL')))throw fail();
66
+ const types={'.mjs':'esm','.js':'esm','.json':'text','.wasm':'wasm'},modules=files.map(file=>({path:'server/'+file.path,type:file.path.startsWith('resources/')?'data':types[path.posix.extname(file.path)]}));if(modules.some(value=>!value.type))throw fail();
67
+ const plan={schemaVersion:1,mainModule:'server/worker.mjs',compatibilityDate,compatibilityFlags,modules,receiptPath:'server/release-server.json'};
68
+ files.push({path:'cloudflare-worker.json',bytes:Buffer.from(canonical(plan))});
69
+ const receiptFiles=files.filter(file=>file!==receipt).map(file=>({path:'server/'+file.path,bytes:file.bytes.byteLength,sha256:'sha256:'+sha(file.bytes)})).sort((a,b)=>a.path<b.path?-1:1);
70
+ receipt.bytes=Buffer.from(canonical({schemaVersion:1,kind:'server',payloadBytes:receiptFiles.reduce((sum,file)=>sum+file.bytes,0),files:receiptFiles}));
71
+ const index={schemaVersion:1,kind:'cloudflare-worker',entry:'worker.mjs',...identity,catalogIdentity:catalog.catalogIdentity,graph:bundled.metadata,files:files.map(file=>({path:file.path,byteLength:file.bytes.byteLength,sha256:sha(file.bytes)})).sort((a,b)=>a.path<b.path?-1:1)};
72
+ if(Buffer.byteLength(canonical(index))>8388608)throw fail();
73
+ parseCloudflareWorkerPackage(plan,{descriptor:{runtime:{entry:plan.mainModule,links:[]}},files:files.map(file=>({path:'server/'+file.path,role:'control'}))});
74
+ const output=path.join(root,'dist-worker');if(fs.existsSync(output)){const old=readOwnerCloudflareWorkerBuild({root}),expected=[...old.index.files.map(file=>file.path),'worker-build.json'].sort(),names=[];
75
+ for(const value of fs.readdirSync(output,{recursive:true})){const selected=path.join(output,value),portable=value.split(path.sep).join('/'),info=fs.lstatSync(selected);if(info.isSymbolicLink()||fs.realpathSync(selected)!==selected)throw fail();if(info.isFile())names.push(portable);else if(!info.isDirectory()||!expected.some(name=>name.startsWith(portable+'/')))throw fail();}
76
+ if(names.sort().join('\n')!==expected.join('\n'))throw fail();for(const file of old.index.files)fs.unlinkSync(path.join(output,file.path));fs.unlinkSync(path.join(output,'worker-build.json'));}
77
+ else fs.mkdirSync(output);
78
+ for(const file of files){const selected=path.join(output,file.path);fs.mkdirSync(path.dirname(selected),{recursive:true});if(fs.realpathSync(path.dirname(selected))!==path.dirname(selected))throw fail();fs.writeFileSync(selected,file.bytes,{flag:'wx'});}fs.writeFileSync(path.join(output,'worker-build.json'),canonical(index),{flag:'wx'});
79
+ scope.checkBudget();result={status:'PASS',entry:index.entry,files:files.length,bytes:files.reduce((sum,file)=>sum+file.bytes.byteLength,0),serverDigest:'sha256:'+sha(receipt.bytes),...identity};
80
+ }catch(error){failure=error;result={status:'FAIL',code:error.message,process:error.process??error.cause?.cause?.process};}
81
+ finally{try{scope.finish({result,closed});}catch(error){if(failure)failure.cleanupError=error;else failure=error;}}
82
+ if(failure){failure.closure={processesClosed:closed,slotRemoved:!fs.existsSync(slot)};throw failure;}return result;
83
+ }
@@ -1,2 +1,2 @@
1
- export function requirePrebuiltFunctionRegion(regions:unknown):string;
2
- export function finalizePrebuiltOutput(options:{root:string;region?:string;maximumFiles?:number;maximumBytes?:number}):{status:'PREBUILT_OUTPUT_SELF_CONTAINED';rewrittenLinks:number;internalLinks:number;files:number;bytes:number};
1
+ export function requirePrebuiltFunctionRegion(regions:unknown):string;
2
+ export function finalizePrebuiltOutput(options:{root:string;region?:string;maximumFiles?:number;maximumBytes?:number}):{status:'PREBUILT_OUTPUT_SELF_CONTAINED';rewrittenLinks:number;internalLinks:number;files:number;bytes:number};
@@ -1,104 +1,104 @@
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
- const digest=body=>createHash('sha256').update(body).digest('hex');
7
- function inside(root,file){const relative=path.relative(root,file);return relative!== '..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);}
8
- function identity(file){const info=fs.lstatSync(file,{bigint:true});return [info.dev,info.ino,info.mode,info.size,info.mtimeNs].map(String).join(':');}
9
- const regionIdentifier=/^[a-z]{3}[1-9][0-9]?$/u;
10
- const functionConfig=/^(?:services\/[^/]+\/)?functions\/(?:[^/]+\/)*[^/]+\.func\/\.vc-config\.json$/u;
11
-
12
- export function requirePrebuiltFunctionRegion(regions){
13
- assert(Array.isArray(regions)&&regions.length===1&&typeof regions[0]==='string'&&regionIdentifier.test(regions[0]),'PREBUILT_FUNCTION_REGION_INVALID');
14
- return regions[0];
15
- }
16
-
17
- /** Finalize the pinned official producer's trace, never an installed package
18
- * directory. An external resolver link may use only its already emitted mirror
19
- * in that exact Function. Missing mirrors fail; untraced package files are never
20
- * added. Preserve Node's realpath semantics with portable internal links, rather
21
- * than duplicating modules at aliases. The caller owns the closed fresh build. */
22
- export function finalizePrebuiltOutput({root,region,maximumFiles=10000,maximumBytes=256*1024**2}){
23
- assert(typeof root==='string'&&path.isAbsolute(root)&&path.resolve(root)===fs.realpathSync(root),'PREBUILT_OUTPUT_BOUNDARY');
24
- if(region!==undefined)requirePrebuiltFunctionRegion([region]);
25
- assert(Number.isSafeInteger(maximumFiles)&&maximumFiles>=1&&maximumFiles<=10000,'PREBUILT_FILE_LIMIT');
26
- assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>=1&&maximumBytes<=256*1024**2,'PREBUILT_BYTE_LIMIT');
27
- const output=path.join(root,'.vercel/output'),stage=output+'-materializing',previous=output+'-source';
28
- for(const directory of [path.join(root,'.vercel'),output])assert(fs.lstatSync(directory).isDirectory()&&fs.realpathSync(directory)===directory,'PREBUILT_OUTPUT_BOUNDARY');
29
- assert(!fs.lstatSync(stage,{throwIfNoEntry:false})&&!fs.lstatSync(previous,{throwIfNoEntry:false}),'PREBUILT_OUTPUT_RECOVERY_REQUIRED');
30
- const configuration=path.join(output,'config.json'),configInfo=fs.lstatSync(configuration);assert(configInfo.isFile()&&!configInfo.isSymbolicLink()&&configInfo.size<=2097152,'PREBUILT_OUTPUT_INVALID');
31
- assert(JSON.parse(fs.readFileSync(configuration,'utf8')).version===3,'PREBUILT_OUTPUT_INVALID');
32
- const started=performance.now(),references=new Map(),changedLinks=new Set(),directories=[],files=[],links=[],children=new Map();let bytes=0,entries=0,regionalFunctions=0,regionChanged=false;
33
- const check=()=>assert(performance.now()-started<=30000,'PREBUILT_FINALIZATION_TIMEOUT');
34
- const observe=file=>{if(!references.has(file)){const info=fs.lstatSync(file),record={identity:identity(file)};if(info.isSymbolicLink())record.link=fs.readlinkSync(file);references.set(file,record);}return references.get(file);};
35
- const resolve=file=>{
36
- observe(file);let actual;try{actual=fs.realpathSync(file);}catch(error){if(error.code==='ELOOP')assert.fail('PREBUILT_LINK_CYCLE');throw error;}if(inside(output,actual))return actual;
37
- assert(inside(root,actual),'PREBUILT_TRACE_MIRROR_MISSING');
38
- let owner=path.dirname(file);while(owner!==output&&!owner.endsWith('.func'))owner=path.dirname(owner);
39
- assert(owner!==output&&inside(output,owner),'PREBUILT_TRACE_MIRROR_MISSING');
40
- const mirror=path.join(owner,path.relative(root,actual));
41
- assert(fs.existsSync(mirror)&&inside(output,fs.realpathSync(mirror)),'PREBUILT_TRACE_MIRROR_MISSING');
42
- return fs.realpathSync(mirror);
43
- };
44
- const walk=(file,relative)=>{
45
- check();assert(++entries<=maximumFiles*4,'PREBUILT_ENTRY_LIMIT');assert(Buffer.byteLength(relative)<=1024,'PREBUILT_PATH_LIMIT');
46
- observe(file);const info=fs.lstatSync(file);
47
- if(info.isSymbolicLink()){
48
- assert(files.length+links.length<maximumFiles,'PREBUILT_FILE_LIMIT');
49
- const target=resolve(file),directory=fs.statSync(target).isDirectory();assert(!directory||!inside(target,path.dirname(file)),'PREBUILT_LINK_CYCLE');
50
- const link=path.relative(path.dirname(file),target).split(path.sep).join('/');
51
- assert(link&&!path.isAbsolute(link)&&Buffer.byteLength(link)<=1024,'PREBUILT_PATH_LIMIT');
52
- bytes+=Buffer.byteLength(link);assert(bytes<=maximumBytes,'PREBUILT_BYTE_LIMIT');
53
- links.push({path:relative,target,link,directory});
54
- if(fs.readlinkSync(file).split(path.sep).join('/')!==link)changedLinks.add(file);
55
- return;
56
- }
57
- const selected=file;assert(inside(output,selected),'PREBUILT_OUTPUT_BOUNDARY');
58
- if(info.isDirectory()){
59
- directories.push(relative);const names=fs.readdirSync(selected).sort();children.set(selected,names.map(name=>path.join(selected,name)));
60
- for(const name of names)walk(path.join(selected,name),relative?relative+'/'+name:name);
61
- return;
62
- }
63
- assert(info.isFile()&&files.length+links.length<maximumFiles,'PREBUILT_FILE_LIMIT');assert(info.size<=maximumBytes-bytes,'PREBUILT_BYTE_LIMIT');
64
- const body=fs.readFileSync(selected);assert(body.length===info.size,'PREBUILT_SOURCE_CHANGED');
65
- assert(!/\.(?:dll|exe|pdb|dylib)$/i.test(relative)&&(!/\.(?:node|so(?:\.[0-9]+)*)$/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),'PREBUILT_NATIVE_TARGET_INVALID');
66
- const sha256=digest(body);observe(selected).sha256=sha256;
67
- let replacement;
68
- if(region!==undefined&&functionConfig.test(relative)){
69
- assert(body.length<=65536,'PREBUILT_OUTPUT_INVALID');
70
- const config=JSON.parse(body.toString('utf8'));
71
- assert(config&&typeof config.runtime==='string'&&config.runtime.startsWith('nodejs'),'PREBUILT_OUTPUT_INVALID');
72
- regionalFunctions++;
73
- if(!Array.isArray(config.regions)||config.regions.length!==1||config.regions[0]!==region){
74
- replacement=Buffer.from(JSON.stringify({...config,regions:[region]})+'\n');
75
- regionChanged=true;
76
- }
77
- }
78
- bytes+=(replacement??body).length;assert(bytes<=maximumBytes,'PREBUILT_BYTE_LIMIT');
79
- files.push({path:relative,source:selected,bytes:body.length,sha256,mode:info.mode&0o777,replacement});
80
- };
81
- walk(output,'');
82
- if(region!==undefined)assert(regionalFunctions>0,'PREBUILT_OUTPUT_INVALID');
83
- const linkTargets=new Map(links.map(link=>[path.join(output,link.path),link.target])),active=new Set(),finished=new Set();
84
- const checkCycles=file=>{check();const selected=linkTargets.get(file)??file;assert(references.has(selected),'PREBUILT_TRACE_MIRROR_MISSING');if(!children.has(selected)||finished.has(selected))return;assert(!active.has(selected),'PREBUILT_LINK_CYCLE');active.add(selected);for(const child of children.get(selected))checkCycles(child);active.delete(selected);finished.add(selected);};
85
- checkCycles(output);
86
- const verifySource=()=>{for(const [file,record]of references){check();assert(identity(file)===record.identity,'PREBUILT_SOURCE_CHANGED');if(record.link!==undefined)assert(fs.readlinkSync(file)===record.link,'PREBUILT_SOURCE_CHANGED');if(record.sha256)assert(digest(fs.readFileSync(file))===record.sha256,'PREBUILT_SOURCE_CHANGED');}};
87
- verifySource();
88
- const result={status:'PREBUILT_OUTPUT_SELF_CONTAINED',rewrittenLinks:changedLinks.size,internalLinks:links.length,files:files.length+links.length,bytes};
89
- if(!changedLinks.size&&!regionChanged)return result;
90
- fs.mkdirSync(stage);
91
- for(const directory of directories)if(directory)fs.mkdirSync(path.join(stage,directory),{recursive:true});
92
- for(const file of files){
93
- check();const body=fs.readFileSync(file.source);assert(body.length===file.bytes&&digest(body)===file.sha256,'PREBUILT_SOURCE_CHANGED');
94
- const destination=path.join(stage,file.path),expected=file.replacement??body;
95
- fs.writeFileSync(destination,expected,{flag:'wx',mode:file.mode});assert(fs.readFileSync(destination).equals(expected),'PREBUILT_COPY_CHANGED');
96
- }
97
- for(const link of links){const destination=path.join(stage,link.path);fs.symlinkSync(link.link,destination,link.directory?'dir':'file');assert(fs.readlinkSync(destination).split(path.sep).join('/')===link.link&&fs.realpathSync(destination)===path.join(stage,path.relative(output,link.target)),'PREBUILT_COPY_CHANGED');}
98
- verifySource();const original=fs.lstatSync(output,{bigint:true});fs.renameSync(output,previous);fs.renameSync(stage,output);
99
- const retired=fs.lstatSync(previous,{bigint:true});assert(fs.realpathSync(previous)===previous&&retired.dev===original.dev&&retired.ino===original.ino,'PREBUILT_OUTPUT_RECOVERY_REQUIRED');
100
- // This is only the closed producer's exact verified old output. rm does not
101
- // follow its resolver links into formal dependencies or another workspace.
102
- fs.rmSync(previous,{recursive:true});
103
- return result;
104
- }
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
+ const digest=body=>createHash('sha256').update(body).digest('hex');
7
+ function inside(root,file){const relative=path.relative(root,file);return relative!== '..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);}
8
+ function identity(file){const info=fs.lstatSync(file,{bigint:true});return [info.dev,info.ino,info.mode,info.size,info.mtimeNs].map(String).join(':');}
9
+ const regionIdentifier=/^[a-z]{3}[1-9][0-9]?$/u;
10
+ const functionConfig=/^(?:services\/[^/]+\/)?functions\/(?:[^/]+\/)*[^/]+\.func\/\.vc-config\.json$/u;
11
+
12
+ export function requirePrebuiltFunctionRegion(regions){
13
+ assert(Array.isArray(regions)&&regions.length===1&&typeof regions[0]==='string'&&regionIdentifier.test(regions[0]),'PREBUILT_FUNCTION_REGION_INVALID');
14
+ return regions[0];
15
+ }
16
+
17
+ /** Finalize the pinned official producer's trace, never an installed package
18
+ * directory. An external resolver link may use only its already emitted mirror
19
+ * in that exact Function. Missing mirrors fail; untraced package files are never
20
+ * added. Preserve Node's realpath semantics with portable internal links, rather
21
+ * than duplicating modules at aliases. The caller owns the closed fresh build. */
22
+ export function finalizePrebuiltOutput({root,region,maximumFiles=10000,maximumBytes=256*1024**2}){
23
+ assert(typeof root==='string'&&path.isAbsolute(root)&&path.resolve(root)===fs.realpathSync(root),'PREBUILT_OUTPUT_BOUNDARY');
24
+ if(region!==undefined)requirePrebuiltFunctionRegion([region]);
25
+ assert(Number.isSafeInteger(maximumFiles)&&maximumFiles>=1&&maximumFiles<=10000,'PREBUILT_FILE_LIMIT');
26
+ assert(Number.isSafeInteger(maximumBytes)&&maximumBytes>=1&&maximumBytes<=256*1024**2,'PREBUILT_BYTE_LIMIT');
27
+ const output=path.join(root,'.vercel/output'),stage=output+'-materializing',previous=output+'-source';
28
+ for(const directory of [path.join(root,'.vercel'),output])assert(fs.lstatSync(directory).isDirectory()&&fs.realpathSync(directory)===directory,'PREBUILT_OUTPUT_BOUNDARY');
29
+ assert(!fs.lstatSync(stage,{throwIfNoEntry:false})&&!fs.lstatSync(previous,{throwIfNoEntry:false}),'PREBUILT_OUTPUT_RECOVERY_REQUIRED');
30
+ const configuration=path.join(output,'config.json'),configInfo=fs.lstatSync(configuration);assert(configInfo.isFile()&&!configInfo.isSymbolicLink()&&configInfo.size<=2097152,'PREBUILT_OUTPUT_INVALID');
31
+ assert(JSON.parse(fs.readFileSync(configuration,'utf8')).version===3,'PREBUILT_OUTPUT_INVALID');
32
+ const started=performance.now(),references=new Map(),changedLinks=new Set(),directories=[],files=[],links=[],children=new Map();let bytes=0,entries=0,regionalFunctions=0,regionChanged=false;
33
+ const check=()=>assert(performance.now()-started<=30000,'PREBUILT_FINALIZATION_TIMEOUT');
34
+ const observe=file=>{if(!references.has(file)){const info=fs.lstatSync(file),record={identity:identity(file)};if(info.isSymbolicLink())record.link=fs.readlinkSync(file);references.set(file,record);}return references.get(file);};
35
+ const resolve=file=>{
36
+ observe(file);let actual;try{actual=fs.realpathSync(file);}catch(error){if(error.code==='ELOOP')assert.fail('PREBUILT_LINK_CYCLE');throw error;}if(inside(output,actual))return actual;
37
+ assert(inside(root,actual),'PREBUILT_TRACE_MIRROR_MISSING');
38
+ let owner=path.dirname(file);while(owner!==output&&!owner.endsWith('.func'))owner=path.dirname(owner);
39
+ assert(owner!==output&&inside(output,owner),'PREBUILT_TRACE_MIRROR_MISSING');
40
+ const mirror=path.join(owner,path.relative(root,actual));
41
+ assert(fs.existsSync(mirror)&&inside(output,fs.realpathSync(mirror)),'PREBUILT_TRACE_MIRROR_MISSING');
42
+ return fs.realpathSync(mirror);
43
+ };
44
+ const walk=(file,relative)=>{
45
+ check();assert(++entries<=maximumFiles*4,'PREBUILT_ENTRY_LIMIT');assert(Buffer.byteLength(relative)<=1024,'PREBUILT_PATH_LIMIT');
46
+ observe(file);const info=fs.lstatSync(file);
47
+ if(info.isSymbolicLink()){
48
+ assert(files.length+links.length<maximumFiles,'PREBUILT_FILE_LIMIT');
49
+ const target=resolve(file),directory=fs.statSync(target).isDirectory();assert(!directory||!inside(target,path.dirname(file)),'PREBUILT_LINK_CYCLE');
50
+ const link=path.relative(path.dirname(file),target).split(path.sep).join('/');
51
+ assert(link&&!path.isAbsolute(link)&&Buffer.byteLength(link)<=1024,'PREBUILT_PATH_LIMIT');
52
+ bytes+=Buffer.byteLength(link);assert(bytes<=maximumBytes,'PREBUILT_BYTE_LIMIT');
53
+ links.push({path:relative,target,link,directory});
54
+ if(fs.readlinkSync(file).split(path.sep).join('/')!==link)changedLinks.add(file);
55
+ return;
56
+ }
57
+ const selected=file;assert(inside(output,selected),'PREBUILT_OUTPUT_BOUNDARY');
58
+ if(info.isDirectory()){
59
+ directories.push(relative);const names=fs.readdirSync(selected).sort();children.set(selected,names.map(name=>path.join(selected,name)));
60
+ for(const name of names)walk(path.join(selected,name),relative?relative+'/'+name:name);
61
+ return;
62
+ }
63
+ assert(info.isFile()&&files.length+links.length<maximumFiles,'PREBUILT_FILE_LIMIT');assert(info.size<=maximumBytes-bytes,'PREBUILT_BYTE_LIMIT');
64
+ const body=fs.readFileSync(selected);assert(body.length===info.size,'PREBUILT_SOURCE_CHANGED');
65
+ assert(!/\.(?:dll|exe|pdb|dylib)$/i.test(relative)&&(!/\.(?:node|so(?:\.[0-9]+)*)$/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),'PREBUILT_NATIVE_TARGET_INVALID');
66
+ const sha256=digest(body);observe(selected).sha256=sha256;
67
+ let replacement;
68
+ if(region!==undefined&&functionConfig.test(relative)){
69
+ assert(body.length<=65536,'PREBUILT_OUTPUT_INVALID');
70
+ const config=JSON.parse(body.toString('utf8'));
71
+ assert(config&&typeof config.runtime==='string'&&config.runtime.startsWith('nodejs'),'PREBUILT_OUTPUT_INVALID');
72
+ regionalFunctions++;
73
+ if(!Array.isArray(config.regions)||config.regions.length!==1||config.regions[0]!==region){
74
+ replacement=Buffer.from(JSON.stringify({...config,regions:[region]})+'\n');
75
+ regionChanged=true;
76
+ }
77
+ }
78
+ bytes+=(replacement??body).length;assert(bytes<=maximumBytes,'PREBUILT_BYTE_LIMIT');
79
+ files.push({path:relative,source:selected,bytes:body.length,sha256,mode:info.mode&0o777,replacement});
80
+ };
81
+ walk(output,'');
82
+ if(region!==undefined)assert(regionalFunctions>0,'PREBUILT_OUTPUT_INVALID');
83
+ const linkTargets=new Map(links.map(link=>[path.join(output,link.path),link.target])),active=new Set(),finished=new Set();
84
+ const checkCycles=file=>{check();const selected=linkTargets.get(file)??file;assert(references.has(selected),'PREBUILT_TRACE_MIRROR_MISSING');if(!children.has(selected)||finished.has(selected))return;assert(!active.has(selected),'PREBUILT_LINK_CYCLE');active.add(selected);for(const child of children.get(selected))checkCycles(child);active.delete(selected);finished.add(selected);};
85
+ checkCycles(output);
86
+ const verifySource=()=>{for(const [file,record]of references){check();assert(identity(file)===record.identity,'PREBUILT_SOURCE_CHANGED');if(record.link!==undefined)assert(fs.readlinkSync(file)===record.link,'PREBUILT_SOURCE_CHANGED');if(record.sha256)assert(digest(fs.readFileSync(file))===record.sha256,'PREBUILT_SOURCE_CHANGED');}};
87
+ verifySource();
88
+ const result={status:'PREBUILT_OUTPUT_SELF_CONTAINED',rewrittenLinks:changedLinks.size,internalLinks:links.length,files:files.length+links.length,bytes};
89
+ if(!changedLinks.size&&!regionChanged)return result;
90
+ fs.mkdirSync(stage);
91
+ for(const directory of directories)if(directory)fs.mkdirSync(path.join(stage,directory),{recursive:true});
92
+ for(const file of files){
93
+ check();const body=fs.readFileSync(file.source);assert(body.length===file.bytes&&digest(body)===file.sha256,'PREBUILT_SOURCE_CHANGED');
94
+ const destination=path.join(stage,file.path),expected=file.replacement??body;
95
+ fs.writeFileSync(destination,expected,{flag:'wx',mode:file.mode});assert(fs.readFileSync(destination).equals(expected),'PREBUILT_COPY_CHANGED');
96
+ }
97
+ for(const link of links){const destination=path.join(stage,link.path);fs.symlinkSync(link.link,destination,link.directory?'dir':'file');assert(fs.readlinkSync(destination).split(path.sep).join('/')===link.link&&fs.realpathSync(destination)===path.join(stage,path.relative(output,link.target)),'PREBUILT_COPY_CHANGED');}
98
+ verifySource();const original=fs.lstatSync(output,{bigint:true});fs.renameSync(output,previous);fs.renameSync(stage,output);
99
+ const retired=fs.lstatSync(previous,{bigint:true});assert(fs.realpathSync(previous)===previous&&retired.dev===original.dev&&retired.ino===original.ino,'PREBUILT_OUTPUT_RECOVERY_REQUIRED');
100
+ // This is only the closed producer's exact verified old output. rm does not
101
+ // follow its resolver links into formal dependencies or another workspace.
102
+ fs.rmSync(previous,{recursive:true});
103
+ return result;
104
+ }
@@ -1,38 +1,38 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import net from 'node:net';
4
- import assert from 'node:assert/strict';
5
- import {createRequire} from 'node:module';
6
- export const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
7
- export async function probeHostResponse(url,options){
8
- const response=await fetch(url,options);
9
- try{return {ok:response.ok,status:response.status,headers:response.headers};}
10
- finally{await response.body?.cancel();}
11
- }
12
- export async function availableWebPort(installationRoot){
13
- assert.ok(installationRoot,'Explicit host installation root required');
14
- const require=createRequire(path.join(installationRoot,'package.json')),{isPortIsReserved}=require('next/dist/lib/helpers/get-reserved-port.js');
15
- for(let attempt=0;attempt<100;attempt++){
16
- const port=await new Promise((resolve,reject)=>{const probe=net.createServer();probe.once('error',reject);probe.listen(0,'127.0.0.1',()=>{const number=probe.address().port;probe.close(()=>resolve(number));});});
17
- if(!isPortIsReserved(port))return port;
18
- }
19
- throw Error('No available non-reserved Web port');
20
- }
21
- export function hostEnvironment(database,config){return {...process.env,LINK_LIGHT_CONTROL_CONFIG:JSON.stringify(config),NEXT_TELEMETRY_DISABLED:'1',TEMP:database.evidence,TMP:database.evidence,TMPDIR:database.evidence};}
22
- export async function startProductionWorker(database,config){
23
- assert.ok(database.hostArtifact?.workerEntry,'Explicit built host artifact required');
24
- let output='';const handle=database.start(process.execPath,[database.hostArtifact.workerEntry],{fixtureHost:true,cwd:database.evidence,env:hostEnvironment(database,config)});
25
- handle.child.stdout.on('data',bytes=>{output+=bytes;});const deadline=Date.now()+15000;
26
- while(!output.includes('"ready":true')){assert.ok(!handle.state.closed&&Date.now()<deadline,'Independent Worker startup failed: '+output);await pause(50);}
27
- const ready=output.trim().split('\n').map(line=>{try{return JSON.parse(line);}catch{return null;}}).find(row=>row?.ready);assert.equal(ready.ready,true);
28
- fs.writeFileSync(path.join(database.evidence,'worker-ready-'+handle.state.pid+'.json'),JSON.stringify({ready,pid:handle.state.pid,entry:database.hostArtifact.workerEntry,independentProcess:true},null,2)+'\n');return handle;
29
- }
30
- export async function startProductionWeb(database,config){
31
- assert.ok(database.hostArtifact?.webRoot&&database.hostArtifact.installationRoot,'Explicit built host artifact required');
32
- const port=await availableWebPort(database.hostArtifact.installationRoot);database.registerPort(port);
33
- const require=createRequire(path.join(database.hostArtifact.installationRoot,'package.json')),next=path.join(path.dirname(require.resolve('next/package.json')),'dist/bin/next'),origin=`http://127.0.0.1:${port}`;
34
- const handle=database.start(process.execPath,[next,'start',database.hostArtifact.webRoot,'--hostname','127.0.0.1','--port',String(port)],{fixtureHost:true,cwd:database.hostArtifact.installationRoot,env:hostEnvironment(database,config)});
35
- const deadline=Date.now()+20000;let ready=false;
36
- while(!ready){assert.ok(!handle.state.closed&&Date.now()<deadline,'Production Next startup failed');try{ready=(await probeHostResponse(origin)).ok;}catch{}if(!ready)await pause(100);}
37
- fs.writeFileSync(path.join(database.evidence,'web-ready.json'),JSON.stringify({pid:handle.state.pid,origin,entry:'next start',productionBuild:true},null,2)+'\n');return {handle,origin};
38
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import net from 'node:net';
4
+ import assert from 'node:assert/strict';
5
+ import {createRequire} from 'node:module';
6
+ export const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
7
+ export async function probeHostResponse(url,options){
8
+ const response=await fetch(url,options);
9
+ try{return {ok:response.ok,status:response.status,headers:response.headers};}
10
+ finally{await response.body?.cancel();}
11
+ }
12
+ export async function availableWebPort(installationRoot){
13
+ assert.ok(installationRoot,'Explicit host installation root required');
14
+ const require=createRequire(path.join(installationRoot,'package.json')),{isPortIsReserved}=require('next/dist/lib/helpers/get-reserved-port.js');
15
+ for(let attempt=0;attempt<100;attempt++){
16
+ const port=await new Promise((resolve,reject)=>{const probe=net.createServer();probe.once('error',reject);probe.listen(0,'127.0.0.1',()=>{const number=probe.address().port;probe.close(()=>resolve(number));});});
17
+ if(!isPortIsReserved(port))return port;
18
+ }
19
+ throw Error('No available non-reserved Web port');
20
+ }
21
+ export function hostEnvironment(database,config){return {...process.env,LINK_LIGHT_CONTROL_CONFIG:JSON.stringify(config),NEXT_TELEMETRY_DISABLED:'1',TEMP:database.evidence,TMP:database.evidence,TMPDIR:database.evidence};}
22
+ export async function startProductionWorker(database,config){
23
+ assert.ok(database.hostArtifact?.workerEntry,'Explicit built host artifact required');
24
+ let output='';const handle=database.start(process.execPath,[database.hostArtifact.workerEntry],{fixtureHost:true,cwd:database.evidence,env:hostEnvironment(database,config)});
25
+ handle.child.stdout.on('data',bytes=>{output+=bytes;});const deadline=Date.now()+15000;
26
+ while(!output.includes('"ready":true')){assert.ok(!handle.state.closed&&Date.now()<deadline,'Independent Worker startup failed: '+output);await pause(50);}
27
+ const ready=output.trim().split('\n').map(line=>{try{return JSON.parse(line);}catch{return null;}}).find(row=>row?.ready);assert.equal(ready.ready,true);
28
+ fs.writeFileSync(path.join(database.evidence,'worker-ready-'+handle.state.pid+'.json'),JSON.stringify({ready,pid:handle.state.pid,entry:database.hostArtifact.workerEntry,independentProcess:true},null,2)+'\n');return handle;
29
+ }
30
+ export async function startProductionWeb(database,config){
31
+ assert.ok(database.hostArtifact?.webRoot&&database.hostArtifact.installationRoot,'Explicit built host artifact required');
32
+ const port=await availableWebPort(database.hostArtifact.installationRoot);database.registerPort(port);
33
+ const require=createRequire(path.join(database.hostArtifact.installationRoot,'package.json')),next=path.join(path.dirname(require.resolve('next/package.json')),'dist/bin/next'),origin=`http://127.0.0.1:${port}`;
34
+ const handle=database.start(process.execPath,[next,'start',database.hostArtifact.webRoot,'--hostname','127.0.0.1','--port',String(port)],{fixtureHost:true,cwd:database.hostArtifact.installationRoot,env:hostEnvironment(database,config)});
35
+ const deadline=Date.now()+20000;let ready=false;
36
+ while(!ready){assert.ok(!handle.state.closed&&Date.now()<deadline,'Production Next startup failed');try{ready=(await probeHostResponse(origin)).ok;}catch{}if(!ready)await pause(100);}
37
+ fs.writeFileSync(path.join(database.evidence,'web-ready.json'),JSON.stringify({pid:handle.state.pid,origin,entry:'next start',productionBuild:true},null,2)+'\n');return {handle,origin};
38
+ }