gencow 0.1.262 → 0.1.264

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.
@@ -21,6 +21,7 @@ export function createCloudAppIfNeeded({
21
21
  envTarget = "dev",
22
22
  gencowJsonPath,
23
23
  allowMissingAppReplacement = true,
24
+ explicitApp = false,
24
25
  }) {
25
26
  const resolvedAppId = await resolveDeployAppId({
26
27
  creds,
@@ -29,6 +30,7 @@ export function createCloudAppIfNeeded({
29
30
  environment: envTarget,
30
31
  platformFetchImpl,
31
32
  allowMissingAppReplacement,
33
+ explicitApp,
32
34
  infoImpl,
33
35
  errorImpl,
34
36
  exitImpl,
@@ -1,3 +1,5 @@
1
+ import { appNotFoundDiagnostic } from "./app-response-contract.mjs";
2
+ import { describeProdTargetFailure, resolveProdAppTarget } from "./cloud-targets.mjs";
1
3
  import { readJsonObjectResponse } from "./http-response-json.mjs";
2
4
 
3
5
  const PUBLIC_LOOKUP_ERROR_CODES = new Set([
@@ -48,6 +50,49 @@ function formatLookupFailure(failure, target) {
48
50
  return lines.join("\n");
49
51
  }
50
52
 
53
+ // Rejection for an app ID the user named explicitly with --app. Such an ID is never replaced:
54
+ // a replacement would create a different app and rewrite gencow.json without the user asking.
55
+ function explicitAppNotFoundMessage({ appId, target = "dev", correlationId = null }) {
56
+ const lines = [
57
+ ...appNotFoundDiagnostic().split("\n"),
58
+ "Stage: deploy target lookup",
59
+ `App ID: ${appId}${target === "prod" ? " (requested with --prod)" : ""}`,
60
+ "Changed: nothing. No replacement app was created, gencow.json was not modified, and app data and the serving state were not changed.",
61
+ "Retry: only after --app names an app you own. Retrying the same ID fails the same way.",
62
+ "Next: gencow app list (find the app ID you own)",
63
+ " gencow app create <name> (create a new app, then deploy to its ID)",
64
+ ];
65
+ if (typeof correlationId === "string" && SAFE_CORRELATION_ID.test(correlationId)) {
66
+ lines.push(`Correlation ID: ${correlationId}`);
67
+ }
68
+ return lines.join("\n");
69
+ }
70
+
71
+ export function rejectExplicitAppNotFound({ appId, target, correlationId, errorImpl, exitImpl }) {
72
+ errorImpl(explicitAppNotFoundMessage({ appId, target, correlationId }));
73
+ exitImpl(1);
74
+ return false;
75
+ }
76
+
77
+ // `--prod --app <id>` on a project with a prod app must name that prod app. Returns true when the
78
+ // target is accepted; otherwise prints a typed rejection and exits before any app or metadata change.
79
+ export function checkExplicitProdAppTarget({ explicitAppId, prodApp, errorImpl, exitImpl }) {
80
+ const prodTarget = resolveProdAppTarget({ explicitAppId, prodApp });
81
+ if (prodTarget.appId) return true;
82
+ errorImpl(
83
+ [
84
+ "Code: EXPLICIT_APP_NOT_PROD_APP",
85
+ "Stage: deploy target lookup",
86
+ `App ID: ${explicitAppId} (requested with --prod)`,
87
+ describeProdTargetFailure(prodTarget, "--app with --prod must name this project's prod app."),
88
+ "Changed: nothing. No app was created or deployed, gencow.json was not modified, and app data and the serving state were not changed.",
89
+ "Next: gencow deploy --prod (deploys to this project's prod app)",
90
+ ].join("\n"),
91
+ );
92
+ exitImpl(1);
93
+ return false;
94
+ }
95
+
51
96
  export async function lookupOwnedApp({ creds, appId, environment, platformFetchImpl }) {
52
97
  try {
53
98
  const response = await platformFetchImpl(
@@ -79,6 +124,7 @@ export async function resolveDeployAppId({
79
124
  environment = "dev",
80
125
  platformFetchImpl,
81
126
  allowMissingAppReplacement,
127
+ explicitApp = false,
82
128
  infoImpl,
83
129
  errorImpl,
84
130
  exitImpl,
@@ -91,6 +137,9 @@ export async function resolveDeployAppId({
91
137
  exitImpl(1);
92
138
  return false;
93
139
  }
140
+ if (explicitApp) {
141
+ return rejectExplicitAppNotFound({ appId, target: environment, errorImpl, exitImpl });
142
+ }
94
143
  if (!allowMissingAppReplacement) {
95
144
  errorImpl(
96
145
  `APP_NOT_FOUND: The existing app ID "${appId}" is unavailable. This deployment requires the original app; restore access before retrying. No replacement app was created.`,
@@ -110,6 +159,7 @@ export async function reconcileProductionAppTarget({
110
159
  gencowJsonPath,
111
160
  platformFetchImpl,
112
161
  createCloudAppIfNeeded,
162
+ explicitApp = false,
113
163
  infoImpl,
114
164
  errorImpl,
115
165
  exitImpl,
@@ -156,6 +206,9 @@ export async function reconcileProductionAppTarget({
156
206
  }
157
207
 
158
208
  if (productionParentAppId && parentState === "missing") {
209
+ if (explicitApp) {
210
+ return rejectExplicitAppNotFound({ appId: productionParentAppId, target: "prod", errorImpl, exitImpl });
211
+ }
159
212
  infoImpl(`Configured app ID is no longer available. Creating a new app named "${displayName}"...`);
160
213
  productionParentAppId = await createCloudAppIfNeeded({
161
214
  creds,
@@ -5,6 +5,8 @@ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFil
5
5
  import { dirname, resolve } from "path";
6
6
  import { fetchAppDiagnosticLogsViaRest, normalizeDiagnosticLogLines } from "./app-diagnostics.mjs";
7
7
  import { createCloudAppIfNeeded as createCloudAppIfNeededImpl } from "./deploy-app-creation.mjs";
8
+ import { rejectExplicitAppNotFound } from "./deploy-app-target.mjs";
9
+ import { loadProjectConfigForDeploy } from "./deploy-project-config-load.mjs";
8
10
  import { resolveConfiguredAuditorImplementation } from "./auditor-mode.mjs";
9
11
  import {
10
12
  loadDeployMigrationGenerationContext,
@@ -52,41 +54,9 @@ import { buildClientUserFixableDiagnostic } from "./migration-client-diagnostic.
52
54
  import { assertRuntimeAssetsWithinBackendRoot } from "./deploy-runtime-asset-audit.mjs";
53
55
  import { formatBundleSummaryLines } from "./deploy-bundle-summary.mjs";
54
56
  import { warnRuntimePathsOutsideBackendRoot } from "./deploy-runtime-path-audit.mjs";
55
- async function loadProjectConfigDefault(options) {
56
- const { loadConfig } = await import("./cli-project-runtime.mjs");
57
- return loadConfig(options);
58
- }
59
57
  export function isExplicitEmptyBackendApi(source) {
60
58
  return /\bdefineApi\s*\(\s*\{\s*procedures\s*:\s*\{\s*\}\s*,?\s*\}\s*\)\s*;?\s*$/u.test(source);
61
59
  }
62
- async function loadProjectConfigForDeploy({
63
- cwd,
64
- existsSyncImpl,
65
- readFileSyncImpl,
66
- resolvePathImpl,
67
- statSyncImpl,
68
- warnImpl,
69
- errorImpl,
70
- loadConfigImpl,
71
- throwOnInvalid = false,
72
- }) {
73
- const loadConfig = loadConfigImpl ?? loadProjectConfigDefault;
74
- try {
75
- return await loadConfig({
76
- cwd,
77
- existsSyncImpl,
78
- readFileSyncImpl,
79
- resolvePathImpl,
80
- statSyncImpl,
81
- warnImpl,
82
- errorImpl,
83
- throwOnInvalid,
84
- });
85
- } catch (caught) {
86
- if (throwOnInvalid) throw caught;
87
- return null;
88
- }
89
- }
90
60
  async function loadInternalToolingDefault() {
91
61
  return loadToolingRuntime({
92
62
  required: ["analyzerAudit"],
@@ -604,6 +574,7 @@ export function createDeployPackageRuntime({
604
574
  resumeExistingReceipt = false,
605
575
  releaseAttemptId = null,
606
576
  clientName = null,
577
+ explicitApp = false,
607
578
  }) {
608
579
  lastDeployOutcome = "pending";
609
580
  const cwd = cwdImpl();
@@ -707,6 +678,19 @@ export function createDeployPackageRuntime({
707
678
  if (!deployRes.ok && deployRes.status === 404) {
708
679
  if (preserveSavedReceiptAfterMissingApp(receipt, targetAppId, envTarget)) return null;
709
680
  if (receipt) deployReceiptStore.releaseDeployReceipt(receipt);
681
+ if (explicitApp) {
682
+ // The user named this app with --app: report it instead of creating a replacement.
683
+ const notFoundBody = await readJsonObjectResponse(deployRes);
684
+ lastDeployOutcome = "failed";
685
+ rejectExplicitAppNotFound({
686
+ appId: targetAppId,
687
+ target: envTarget,
688
+ correlationId: notFoundBody?.correlationId,
689
+ errorImpl,
690
+ exitImpl,
691
+ });
692
+ return null;
693
+ }
710
694
  warnImpl(`App "${targetAppId}" not found. Creating new one...`);
711
695
  targetAppId = await createCloudAppIfNeeded({
712
696
  creds,
@@ -27,6 +27,7 @@ export async function ensureProductionDeployTarget({
27
27
  exitImpl = (code) => process.exit(code),
28
28
  prodAppId = null,
29
29
  region = null,
30
+ explicitApp = false,
30
31
  prepareLocalSource = null,
31
32
  }) {
32
33
  const confirmMode = resolveConfirmationMode({
@@ -50,6 +51,7 @@ export async function ensureProductionDeployTarget({
50
51
  gencowJsonPath,
51
52
  platformFetchImpl,
52
53
  createCloudAppIfNeeded,
54
+ explicitApp,
53
55
  infoImpl,
54
56
  errorImpl,
55
57
  exitImpl,
@@ -0,0 +1,32 @@
1
+ async function loadProjectConfigDefault(options) {
2
+ const { loadConfig } = await import("./cli-project-runtime.mjs");
3
+ return loadConfig(options);
4
+ }
5
+ export async function loadProjectConfigForDeploy({
6
+ cwd,
7
+ existsSyncImpl,
8
+ readFileSyncImpl,
9
+ resolvePathImpl,
10
+ statSyncImpl,
11
+ warnImpl,
12
+ errorImpl,
13
+ loadConfigImpl,
14
+ throwOnInvalid = false,
15
+ }) {
16
+ const loadConfig = loadConfigImpl ?? loadProjectConfigDefault;
17
+ try {
18
+ return await loadConfig({
19
+ cwd,
20
+ existsSyncImpl,
21
+ readFileSyncImpl,
22
+ resolvePathImpl,
23
+ statSyncImpl,
24
+ warnImpl,
25
+ errorImpl,
26
+ throwOnInvalid,
27
+ });
28
+ } catch (caught) {
29
+ if (throwOnInvalid) throw caught;
30
+ return null;
31
+ }
32
+ }
@@ -24,6 +24,7 @@ import {
24
24
  releasePreparedBackendSource,
25
25
  } from "./deploy-prepared-source.mjs";
26
26
  import { resolveImplicitProdEnvironment } from "./cloud-targets.mjs";
27
+ import { checkExplicitProdAppTarget } from "./deploy-app-target.mjs";
27
28
 
28
29
  export function parseDeployArgs(deployArgs) {
29
30
  const parsed = {
@@ -438,6 +439,20 @@ export function createDeployCommand({
438
439
  prodApp: prodAppId,
439
440
  });
440
441
  const rootAppId = appId;
442
+ // Rollback resolves its own prod target below. Every other --prod --app <id> must name the prod app,
443
+ // checked before resolveEnvironmentDeployTarget would otherwise replace the explicit id with prodApp.
444
+ if (!parsed.isRollback && parsed.envTarget === "prod" && parsed.appId && prodAppId) {
445
+ if (
446
+ !checkExplicitProdAppTarget({
447
+ explicitAppId: parsed.appId,
448
+ prodApp: prodAppId,
449
+ errorImpl,
450
+ exitImpl,
451
+ })
452
+ ) {
453
+ return;
454
+ }
455
+ }
441
456
  appId = resolveEnvironmentDeployTarget({ appId, envTarget: parsed.envTarget, prodAppId });
442
457
  const backendProjectRoot = projectDir ?? projectRoot;
443
458
  const projectConfig = loadConfigImpl
@@ -527,6 +542,7 @@ export function createDeployCommand({
527
542
  exitImpl,
528
543
  prodAppId,
529
544
  region: parsed.region,
545
+ explicitApp: Boolean(parsed.appId),
530
546
  prepareLocalSource: preparesBackendSource
531
547
  ? async () => {
532
548
  preparedSource = await prepareBackendSourceForProdCreate(backendDeployRuntime, {
@@ -565,6 +581,7 @@ export function createDeployCommand({
565
581
  envTarget: parsed.envTarget,
566
582
  forceDeploy: parsed.forceDeploy,
567
583
  requestId: parsed.requestId,
584
+ explicitApp: Boolean(parsed.appId),
568
585
  resumeStaticOnly: parsed.resumeRequested,
569
586
  gencowJsonPath,
570
587
  hasDetectedBackend,
@@ -657,6 +674,7 @@ export function createDeployCommand({
657
674
  envTarget: parsed.envTarget,
658
675
  forceDeploy: parsed.forceDeploy,
659
676
  existingBundleMode: parsed.existingBundleMode,
677
+ explicitApp: Boolean(parsed.appId),
660
678
  requestId: parsed.requestId,
661
679
  resumeExistingReceipt: parsed.resumeRequested,
662
680
  gencowJsonPath: activeGencowJsonPath,
@@ -93,6 +93,8 @@ export async function deployBackendPackage({
93
93
  failReleaseAttempt,
94
94
  sourceRoot = null,
95
95
  clientName = null,
96
+ // True when the user named the app with --app. Such an ID is never replaced.
97
+ explicitApp = false,
96
98
  successImpl = success,
97
99
  }) {
98
100
  let packageResult = null;
@@ -122,6 +124,7 @@ export async function deployBackendPackage({
122
124
  envTarget,
123
125
  gencowJsonPath,
124
126
  allowMissingAppReplacement: false,
127
+ explicitApp,
125
128
  });
126
129
  if (!activeAppId) return null;
127
130
  } else {
@@ -152,7 +155,8 @@ export async function deployBackendPackage({
152
155
  displayName,
153
156
  envTarget,
154
157
  gencowJsonPath,
155
- allowMissingAppReplacement: !existingBundleMode,
158
+ allowMissingAppReplacement: !existingBundleMode && !explicitApp,
159
+ explicitApp,
156
160
  });
157
161
  if (!activeAppId) return null;
158
162
 
@@ -201,6 +205,7 @@ export async function deployBackendPackage({
201
205
  resumeExistingReceipt,
202
206
  releaseAttemptId: releaseAttempt?.attemptId ?? null,
203
207
  clientName,
208
+ explicitApp,
204
209
  });
205
210
  if (deployed && Object.hasOwn(deployed, "releaseAttemptId")) {
206
211
  releaseAttempt = deployed.releaseAttemptId ? { attemptId: deployed.releaseAttemptId } : null;
@@ -298,6 +303,7 @@ export async function runStaticDeployFlow({
298
303
  prepareReleaseAttempt,
299
304
  failReleaseAttempt,
300
305
  selectedClient = null,
306
+ explicitApp = false,
301
307
  successImpl = success,
302
308
  }) {
303
309
  if (!runStaticDeployRuntimeImpl) {
@@ -363,6 +369,7 @@ export async function runStaticDeployFlow({
363
369
  failReleaseAttempt,
364
370
  sourceRoot: backendRoot,
365
371
  clientName: selectedClient?.name ?? null,
372
+ explicitApp,
366
373
  successImpl,
367
374
  });
368
375
  if (!deployed) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gencow",
3
- "version": "0.1.262",
3
+ "version": "0.1.264",
4
4
  "description": "Gencow — AI Backend Engine",
5
5
  "type": "module",
6
6
  "bin": {
@@ -40,11 +40,11 @@
40
40
  "ai": "^6.0.314",
41
41
  "better-auth": "1.7.11",
42
42
  "postgres": "^3.4.9",
43
+ "@gencow/react": "0.2.8",
43
44
  "@gencow/client": "0.2.8",
44
45
  "@gencow/core": "0.1.47",
45
- "@gencow/shared": "0.0.0",
46
- "@gencow/react": "0.2.8",
47
- "@gencow/server": "0.1.3"
46
+ "@gencow/server": "0.1.3",
47
+ "@gencow/shared": "0.0.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "node scripts/bundle-core.mjs && node scripts/bundle-shared.mjs && node scripts/bundle-server.mjs",
@@ -10151,7 +10151,7 @@ ${fingerprintReleaseOwnedNodeModulesRoots(repoRoot2)}
10151
10151
  throw new Error("composed Core import registered " + name);
10152
10152
  }
10153
10153
  }
10154
- `;const result3=spawnSync(process.execPath,["--no-install","--eval",script],{cwd:resolve87(runtimeDir,"server"),encoding:"utf8",timeout:15e3,maxBuffer:64*1024});if(!result3.error&&result3.status===0)return;const failure2=result3.error?.message??`Bun exited with status ${result3.status??result3.signal??"unknown"}`;const detail=(result3.stderr||result3.stdout||"").trim().slice(-2048);throw new Error(`[runtime-layout] Runtime Core facade import validation failed: ${failure2}${detail?`: ${detail}`:""}`)}var RUNTIME_CORE_FACADE_RECIPE;var init_runtime_core_facade_composer=__esm({"../platform/src/runtime-core-facade-composer.ts"(){"use strict";RUNTIME_CORE_FACADE_RECIPE={version:1,backingCoreSpecifier:"./dist/index.js",compatibilitySpecifier:"../server/legacy-core/index.js",compatibilityFactory:"createLegacyCoreCompatibility",bindings:[["httpAction","legacy.httpAction"],["crud","legacy.crud"],["gencowCrud","legacy.crud"],["getRegisteredHttpActions","legacy.getRegisteredHttpActions"],["getRegisteredCrudCodegenMeta","legacy.getRegisteredCrudCodegenMeta"],["getOwnerRlsTables","legacy.getOwnerRlsTables"]]}}});import{mkdirSync as mkdirSync5,realpathSync as realpathSync5,rmSync as rmSync6,symlinkSync}from"node:fs";import{relative as relative22,resolve as resolve88}from"node:path";function safeRealpath3(path5){try{return realpathSync5(path5)}catch{return path5}}function symlinkRelativeEntry(targetPath,destinationPath,type="dir",options={}){rmSync6(destinationPath,{recursive:true,force:true});const destinationParent=resolve88(destinationPath,"..");mkdirSync5(destinationParent,{recursive:true});const fromPath=options.preserveLogicalPath?destinationParent:realpathSync5(destinationParent);const toPath3=options.preserveLogicalPath?resolve88(targetPath):safeRealpath3(targetPath);const relativeTarget=relative22(fromPath,toPath3)||".";symlinkSync(relativeTarget,destinationPath,type)}var init_runtime_generation_staging=__esm({"../platform/src/runtime-generation-staging.ts"(){"use strict"}});import{createHash as createHash75,randomUUID as randomUUID46}from"crypto";import{chmodSync,closeSync,constants as constants3,copyFileSync as copyFileSync2,existsSync as existsSync34,fsyncSync,lstatSync as lstatSync7,mkdirSync as mkdirSync6,mkdtempSync as mkdtempSync5,openSync,readFileSync as readFileSync31,readdirSync as readdirSync12,realpathSync as realpathSync6,renameSync,rmSync as rmSync7,statSync as statSync6,symlinkSync as symlinkSync2}from"fs";import{basename as basename10,dirname as dirname24,isAbsolute as isAbsolute25,join as join26,relative as relative23,resolve as resolve89,sep as sep3}from"path";function resolveRuntimeClosureNativePlanBudget(budget){const resolved={maxRecords:budget?.maxRecords??NATIVE_PLAN_MAX_RECORDS,maxEncodedBytes:budget?.maxEncodedBytes??NATIVE_PLAN_MAX_BYTES,maxPathBytes:budget?.maxPathBytes??NATIVE_PLAN_MAX_PATH_BYTES};if(!Number.isSafeInteger(resolved.maxRecords)||resolved.maxRecords<0||resolved.maxRecords>NATIVE_PLAN_MAX_RECORDS||!Number.isSafeInteger(resolved.maxEncodedBytes)||resolved.maxEncodedBytes<1||resolved.maxEncodedBytes>NATIVE_PLAN_MAX_BYTES||!Number.isSafeInteger(resolved.maxPathBytes)||resolved.maxPathBytes<1||resolved.maxPathBytes>NATIVE_PLAN_MAX_PATH_BYTES){throw new Error("runtime native closure plan budget invalid")}return resolved}function canonicalSealedRuntimeFileMode(mode){return mode&73?365:292}function packageManagerNodeModulesRoot(sourceRoot,targetPath){const targetRelativePath=ensureContainedPath(sourceRoot,targetPath,"package manager package");const parts=targetRelativePath.split(sep3);const pnpmIndex=parts.indexOf(".pnpm");if(pnpmIndex>=1&&parts[pnpmIndex-1]==="node_modules"&&parts[pnpmIndex+2]==="node_modules"){return parts.slice(0,pnpmIndex+3).join(sep3)}const bunIndex=parts.indexOf(".bun");if(bunIndex>=1&&parts[bunIndex-1]==="node_modules"&&parts[bunIndex+2]==="node_modules"){return parts.slice(0,bunIndex+3).join(sep3)}return null}function ensureContainedPath(root2,path5,label){const rel=relative23(root2,path5);if(!rel||rel===".")return".";if(isAbsolute25(rel)||rel===".."||rel.startsWith(`..${sep3}`)){throw new Error(`${label} escapes runtime root: ${path5}`)}return rel}function shouldExclude(path5,directory){const name=basename10(path5);if(name===".env"||name.startsWith(".env."))return true;if(!directory&&SECRET_FILE_PATTERN.test(name))return true;if(directory&&EXCLUDED_DIRECTORY_NAMES.has(name))return true;return!directory&&TEST_FILE_PATTERN.test(name)}function planFence(path5){const value2=lstatSync7(path5,{bigint:true});return{dev:value2.dev.toString(),ino:value2.ino.toString(),mode:value2.mode.toString(),size:value2.size.toString(),nlink:value2.nlink.toString(),mtimeNs:value2.mtimeNs.toString(),ctimeNs:value2.ctimeNs.toString()}}function planPath(path5,budget){const normalized=path5.replaceAll("\\","/");if(!normalized||normalized.startsWith("/")||normalized.includes("\0")||normalized.split("/").includes("..")){throw new Error("runtime generation plan path invalid")}if(Buffer.byteLength(normalized,"utf8")>budget.maxPathBytes){throw new RuntimeClosureNativePlanUnsupportedError}return normalized}function recordPlan(context,record3){if(!context.planRecords)return;if(context.planRecords.length>=context.planBudget.maxRecords){throw new RuntimeClosureNativePlanUnsupportedError}const encodedBytes=Buffer.byteLength(JSON.stringify(record3),"utf8")+1;const nextBytes=(context.planEncodedBytes??0)+encodedBytes;if(nextBytes>context.planBudget.maxEncodedBytes)throw new RuntimeClosureNativePlanUnsupportedError;context.planEncodedBytes=nextBytes;context.planRecords.push(record3)}function updateHash(context,value2){context.hash?.update(value2)}function copyFileWithClone(sourcePath,destinationPath){mkdirSync6(dirname24(destinationPath),{recursive:true,mode:493});copyFileSync2(sourcePath,destinationPath,constants3.COPYFILE_FICLONE);chmodSync(destinationPath,statSync6(sourcePath).mode&511)}function copyRelativeRuntimePath(context,relativePath){const sourcePath=resolve89(context.sourceRoot,relativePath);const safeRelativePath=ensureContainedPath(context.sourceRoot,sourcePath,"runtime snapshot path");if(context.visited.has(safeRelativePath)||!existsSync34(sourcePath))return;context.visited.add(safeRelativePath);const sourceStat=lstatSync7(sourcePath);if(shouldExclude(sourcePath,sourceStat.isDirectory()))return;const destinationPath=resolve89(context.stagingRoot,safeRelativePath);if(sourceStat.isSymbolicLink()){const targetPath=realpathSync6(sourcePath);const targetRelativePath=ensureContainedPath(context.sourceRoot,targetPath,"runtime symlink");const destinationTarget=resolve89(context.stagingRoot,targetRelativePath);mkdirSync6(dirname24(destinationPath),{recursive:true,mode:493});const linkTarget=relative23(dirname24(destinationPath),destinationTarget)||".";symlinkSync2(linkTarget,destinationPath,statSync6(targetPath).isDirectory()?"dir":"file");copyRelativeRuntimePath(context,targetRelativePath);const dependencyRoot=packageManagerNodeModulesRoot(context.sourceRoot,targetPath);if(dependencyRoot)copyRelativeRuntimePath(context,dependencyRoot);return}if(sourceStat.isDirectory()){mkdirSync6(destinationPath,{recursive:true,mode:sourceStat.mode&511|448});for(const entry of readdirSync12(sourcePath).sort()){copyRelativeRuntimePath(context,join26(safeRelativePath,entry))}return}if(sourceStat.isFile())copyFileWithClone(sourcePath,destinationPath)}function hashRelativeRuntimePath(context,relativePath){const sourcePath=resolve89(context.sourceRoot,relativePath);const safeRelativePath=ensureContainedPath(context.sourceRoot,sourcePath,"runtime hash path");if(context.visited.has(safeRelativePath)||!existsSync34(sourcePath))return;context.visited.add(safeRelativePath);const sourceStat=lstatSync7(sourcePath);if(shouldExclude(sourcePath,sourceStat.isDirectory()))return;if(sourceStat.isSymbolicLink()){const targetPath=realpathSync6(sourcePath);const targetRelativePath=ensureContainedPath(context.sourceRoot,targetPath,"runtime hash symlink");if(context.planRecords){recordPlan(context,{kind:"L",path:planPath(safeRelativePath,context.planBudget),target:planPath(targetRelativePath,context.planBudget),fence:planFence(sourcePath)})}updateHash(context,`L\0${safeRelativePath}\0${targetRelativePath}\0`);hashRelativeRuntimePath(context,targetRelativePath);const dependencyRoot=packageManagerNodeModulesRoot(context.sourceRoot,targetPath);if(dependencyRoot)hashRelativeRuntimePath(context,dependencyRoot);return}if(sourceStat.isDirectory()){if(context.planRecords){recordPlan(context,{kind:"D",path:planPath(safeRelativePath,context.planBudget),fence:planFence(sourcePath)})}updateHash(context,`D\0${safeRelativePath}\0`);for(const entry of readdirSync12(sourcePath).sort()){hashRelativeRuntimePath(context,join26(safeRelativePath,entry))}return}if(sourceStat.isFile()){if(context.planRecords){recordPlan(context,{kind:"F",path:planPath(safeRelativePath,context.planBudget),fence:planFence(sourcePath)})}const executeBits=canonicalSealedRuntimeFileMode(sourceStat.mode)&73;updateHash(context,`F\0${safeRelativePath}\0${executeBits}\0`);if(context.hash){context.hash.update(readFileSync31(sourcePath));context.hash.update("\0")}}}function createRuntimeClosureNativePlan(params){const sourceRoot=realpathSync6(params.runtimeRoot);const budget=resolveRuntimeClosureNativePlanBudget(params.budget);if(Buffer.byteLength(sourceRoot,"utf8")>budget.maxPathBytes){throw new RuntimeClosureNativePlanUnsupportedError}const root2={path:sourceRoot,...planFence(sourceRoot)};const initialPlanEncodedBytes=Buffer.byteLength(JSON.stringify({version:1,root:root2,records:[]}),"utf8");if(initialPlanEncodedBytes>budget.maxEncodedBytes){throw new RuntimeClosureNativePlanUnsupportedError}const context={sourceRoot,visited:new Set,planRecords:[],planEncodedBytes:initialPlanEncodedBytes,planBudget:budget};for(const seed of params.closureSeeds)hashRelativeRuntimePath(context,seed);return{version:1,root:root2,records:context.planRecords}}function createRuntimeClosureNativePlanForManifest(manifest){const sourceRoot=runtimeSnapshotSourceRoot(manifest);return createRuntimeClosureNativePlan({runtimeRoot:sourceRoot,closureSeeds:runtimeSnapshotSeeds(manifest,sourceRoot)})}function mapRuntimePath(sourceRoot,finalRoot,path5,label){const sourcePath=realpathSync6(path5);const relativePath=ensureContainedPath(sourceRoot,sourcePath,label);return resolve89(finalRoot,relativePath)}function copyBinarySnapshot(params){if(params.snapshot.status!=="present"||!params.snapshot.path)return params.snapshot;const sourcePath=realpathSync6(params.snapshot.path);const extension=process.platform==="win32"?".exe":"";const relativePath=params.layoutVersion===3?join26("runtime","bin",`${params.name}${extension}`):join26("bin",`${params.name}${extension}`);copyFileWithClone(sourcePath,resolve89(params.stagingRoot,relativePath));return{...params.snapshot,path:resolve89(params.finalRoot,relativePath)}}function runtimeSnapshotSourceRoot(manifest){const runtimeRoot=realpathSync6(manifest.runtimeRoot);return manifest.layoutVersion===3?realpathSync6(resolve89(runtimeRoot,"..")):runtimeRoot}function runtimeSnapshotSeeds(manifest,sourceRoot){const layout=detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path);const seeds=new Set(layout==="managed-release"?manifest.layoutVersion===3?["runtime/server","runtime/core","runtime/node_modules","public-node_modules","platform/src","platform/node_modules"]:["manifest.json","server","core","node_modules"]:["package.json","pnpm-workspace.yaml","packages/server/src","packages/server/package.json","packages/server/node_modules","packages/core/src","packages/core/dist","packages/core/package.json","packages/core/node_modules","packages/client/src","packages/client/dist","packages/client/package.json","packages/client/node_modules","packages/shared/dist","packages/shared/package.json","packages/shared/node_modules","packages/internal/dist","packages/internal/package.json","packages/internal/node_modules","packages/platform/src","packages/platform/package.json","packages/platform/node_modules","packages/cli/server","packages/cli/core"]);for(const lockfile of manifest.packageManager.lockfiles)seeds.add(lockfile.file);for(const snapshot of Object.values(manifest.packages)){if(snapshot.status!=="present"||!snapshot.packageJsonPath)continue;const packagePath=realpathSync6(dirname24(snapshot.packageJsonPath));seeds.add(ensureContainedPath(sourceRoot,packagePath,"runtime package"))}return[...seeds].sort()}function sha256RuntimePaths(sourceRoot,seeds){const canonicalRoot=realpathSync6(sourceRoot);const context={sourceRoot:canonicalRoot,visited:new Set,hash:createHash75("sha256")};for(const seed of seeds)hashRelativeRuntimePath(context,seed);return`sha256:${context.hash.digest("hex")}`}function assertRuntimeClosureMatchesAtRoot(params){const actualClosureSha256=sha256RuntimePaths(params.runtimeRoot,params.closureSeeds);if(actualClosureSha256!==params.expectedClosureSha256){throw new Error(`runtime generation closure hash mismatch: expected ${params.expectedClosureSha256}, got ${actualClosureSha256}`)}}function sha256RuntimeSnapshot(manifest){const sourceRoot=runtimeSnapshotSourceRoot(manifest);return sha256RuntimePaths(sourceRoot,runtimeSnapshotSeeds(manifest,sourceRoot))}function runtimeReleaseId(manifestHash,runtimeClosureSha256){return`sha256:${createHash75("sha256").update(`${manifestHash}\0${runtimeClosureSha256}`).digest("hex")}`}function prepareRuntimeGenerationManifest(manifest){const runtimeClosureSha256=sha256RuntimeSnapshot(manifest);return{...manifest,releaseId:runtimeReleaseId(deploymentRuntimeManifestHash(manifest),runtimeClosureSha256),runtimeClosureSha256}}function runtimeGenerationDirectorySuffix(generationId){if(!RUNTIME_GENERATION_ID_PATTERN.test(generationId)){throw new Error(`invalid runtime generation id: ${generationId}`)}return generationId.replace("sha256:","sha256-")}function formatRuntimeGenerationDirectoryTimestamp(generatedAt){const parsed=new Date(generatedAt);if(Number.isNaN(parsed.getTime())){throw new Error(`invalid runtime generation timestamp: ${generatedAt}`)}return parsed.toISOString().replace(/[-:.]/g,"")}function runtimeGenerationDirectoryName(generationId,generatedAt){return`${formatRuntimeGenerationDirectoryTimestamp(generatedAt)}-${runtimeGenerationDirectorySuffix(generationId)}`}function resolveRuntimeGenerationDirectoryPath(baseDir,generationId){const suffix=runtimeGenerationDirectorySuffix(generationId);const timestampedMatches=[];if(!existsSync34(baseDir))return null;for(const entry of readdirSync12(baseDir,{withFileTypes:true})){if(!entry.isDirectory())continue;if(entry.name.endsWith(`-${suffix}`)&&COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN.test(entry.name)){const timestampSource=entry.name.slice(0,-`-${suffix}`.length);const parsedTimestamp=new Date(timestampSource.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\d{3})Z$/,"$1-$2-$3T$4:$5:$6.$7Z")).getTime();if(!Number.isNaN(parsedTimestamp)){timestampedMatches.push({entryName:entry.name,timestamp:parsedTimestamp})}}}const selected=timestampedMatches.sort((a,b2)=>a.timestamp-b2.timestamp||a.entryName.localeCompare(b2.entryName)).at(-1);if(selected)return resolve89(baseDir,selected.entryName);const legacyGenerationDir=resolve89(baseDir,suffix);return existsSync34(legacyGenerationDir)?legacyGenerationDir:null}function runtimeGenerationDirectoryPath(baseDir,generationId,generatedAt){return resolve89(baseDir,runtimeGenerationDirectoryName(generationId,generatedAt))}function stageRuntimeGeneration(params){const sourceRoot=runtimeSnapshotSourceRoot(params.manifest);if(!params.manifest.releaseId||!params.manifest.runtimeClosureSha256){throw new Error("runtime generation manifest is missing its release content identity")}const finalGenerationDir=runtimeGenerationDirectoryPath(params.baseDir,params.manifest.releaseId,params.manifest.generatedAt);const finalRoot=params.manifest.layoutVersion===3?finalGenerationDir:resolve89(finalGenerationDir,"runtime");mkdirSync6(params.baseDir,{recursive:true,mode:493});const publicationOwner=/^[a-f0-9]{32}$/.test(process.env.GENCOW_RUNTIME_PUBLICATION_OWNER??"")?`-${process.env.GENCOW_RUNTIME_PUBLICATION_OWNER}`:"";const stagedGenerationDir=mkdtempSync5(resolve89(params.baseDir,`.tmp-${params.manifestHash.replace(":","-")}-${process.pid}${publicationOwner}-${randomUUID46()}-`));const stagingRoot=params.manifest.layoutVersion===3?stagedGenerationDir:resolve89(stagedGenerationDir,"runtime");try{const context={sourceRoot,stagingRoot,visited:new Set};const seeds=runtimeSnapshotSeeds(params.manifest,sourceRoot);for(const seed of seeds){copyRelativeRuntimePath(context,seed)}assertRuntimeClosureMatchesAtRoot({runtimeRoot:params.manifest.layoutVersion===3?stagedGenerationDir:stagingRoot,closureSeeds:seeds,expectedClosureSha256:params.manifest.runtimeClosureSha256});const packages=Object.fromEntries(Object.entries(params.manifest.packages).map(([name,snapshot])=>[name,snapshot.status==="present"&&snapshot.packageJsonPath?{...snapshot,packageJsonPath:mapRuntimePath(sourceRoot,finalRoot,snapshot.packageJsonPath,`package ${name}`)}:snapshot]));const binaries=Object.fromEntries(Object.entries(params.manifest.binaries).map(([name,snapshot])=>[name,copyBinarySnapshot({name,snapshot,stagingRoot,finalRoot,layoutVersion:params.manifest.layoutVersion})]));return{stagedGenerationDir,finalGenerationDir,closureSeeds:seeds,publishedManifest:{...params.manifest,runtimeRoot:params.manifest.layoutVersion===3?resolve89(finalGenerationDir,"runtime"):finalRoot,serverEntry:{...params.manifest.serverEntry,path:mapRuntimePath(sourceRoot,finalRoot,params.manifest.serverEntry.path,"server entry")},packages,binaries}}}catch(error62){discardStagedRuntimeGeneration(stagedGenerationDir);throw error62}}function makePathWritable(path5){if(!existsSync34(path5))return;const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){chmodSync(path5,493);for(const entry of readdirSync12(path5))makePathWritable(resolve89(path5,entry))}else if(pathStat.isFile()){chmodSync(path5,pathStat.mode|384)}}function discardStagedRuntimeGeneration(stagedGenerationDir){if(!existsSync34(stagedGenerationDir))return;makePathWritable(stagedGenerationDir);rmSync7(stagedGenerationDir,{recursive:true,force:true})}function commitStagedRuntimeGeneration(stagedGenerationDir,finalGenerationDir){try{renameSync(stagedGenerationDir,finalGenerationDir);return"published"}catch(error62){if(existsSync34(finalGenerationDir)){discardStagedRuntimeGeneration(stagedGenerationDir);return"existing"}discardStagedRuntimeGeneration(stagedGenerationDir);throw error62}}function sealPathReadOnly(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){for(const entry of readdirSync12(path5))sealPathReadOnly(resolve89(path5,entry));chmodSync(path5,365);return}if(pathStat.isFile())chmodSync(path5,canonicalSealedRuntimeFileMode(pathStat.mode))}function sealStagedRuntimeGeneration(stagedGenerationDir){if(existsSync34(resolve89(stagedGenerationDir,"runtime"))){sealPathReadOnly(resolve89(stagedGenerationDir,"runtime"))}if(existsSync34(resolve89(stagedGenerationDir,"public-node_modules"))){sealPathReadOnly(resolve89(stagedGenerationDir,"public-node_modules"))}if(existsSync34(resolve89(stagedGenerationDir,"platform"))){sealPathReadOnly(resolve89(stagedGenerationDir,"platform"))}if(existsSync34(resolve89(stagedGenerationDir,"scripts"))){sealPathReadOnly(resolve89(stagedGenerationDir,"scripts"))}chmodSync(resolve89(stagedGenerationDir,"runtime-manifest.json"),292);chmodSync(stagedGenerationDir,365)}function assertPathReadOnly(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;const mode=pathStat.mode&511;if(pathStat.isDirectory()){if(mode!==365){throw new Error("runtime generation permission invalid")}for(const entry of readdirSync12(path5))assertPathReadOnly(resolve89(path5,entry));return}if(pathStat.isFile()&&mode!==292&&mode!==365){throw new Error("runtime generation permission invalid")}if(!pathStat.isFile()){throw new Error("runtime generation permission invalid")}}function assertRuntimeGenerationSealed(generationDir){assertPathReadOnly(generationDir);if((lstatSync7(resolve89(generationDir,"runtime-manifest.json")).mode&511)!==292){throw new Error("runtime generation permission invalid")}}function fsyncPathTree(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){for(const entry of readdirSync12(path5))fsyncPathTree(resolve89(path5,entry))}const fd=openSync(path5,"r");try{fsyncSync(fd)}finally{closeSync(fd)}}function fsyncStagedRuntimeGeneration(stagedGenerationDir){fsyncPathTree(stagedGenerationDir)}var EXCLUDED_DIRECTORY_NAMES,TEST_FILE_PATTERN,SECRET_FILE_PATTERN,RUNTIME_GENERATION_ID_PATTERN,COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN,RuntimeClosureNativePlanUnsupportedError,NATIVE_PLAN_MAX_RECORDS,NATIVE_PLAN_MAX_BYTES,NATIVE_PLAN_MAX_PATH_BYTES;var init_runtime_generation_publisher=__esm({"../platform/src/runtime-generation-publisher.ts"(){"use strict";init_deployment_runtime_manifest();EXCLUDED_DIRECTORY_NAMES=new Set([".git",".gencow","__tests__"]);TEST_FILE_PATTERN=/\.(?:test|spec)\.[cm]?[jt]sx?$/;SECRET_FILE_PATTERN=/^(?:\.npmrc|\.yarnrc|\.netrc|\.pypirc|id_rsa|id_ed25519)$|(?:private|secret|credential).*\.(?:key|pem|p12|pfx)$|\.(?:key|p12|pfx)$/i;RUNTIME_GENERATION_ID_PATTERN=/^sha256:[a-f0-9]{64}$/;COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN=/^\d{8}T\d{9}Z-sha256-[a-f0-9]{64}$/;RuntimeClosureNativePlanUnsupportedError=class extends Error{constructor(){super("runtime native closure backend unsupported");this.name="RuntimeClosureNativePlanUnsupportedError"}};NATIVE_PLAN_MAX_RECORDS=1e5;NATIVE_PLAN_MAX_BYTES=32*1024*1024;NATIVE_PLAN_MAX_PATH_BYTES=4096}});import{existsSync as existsSync35,statfsSync}from"fs";import{dirname as dirname25}from"path";function requiredRuntimeGenerationFreeBytes(probe={}){const watermark=probe.watermarkBytes??RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES;const closure=probe.expectedClosureBytes??RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES;const withHeadroom=Math.ceil(closure*RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR/RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR);return Math.max(watermark,withHeadroom)}function defaultAvailableBytes(path5){let candidate=path5;while(!existsSync35(candidate)){const parent=dirname25(candidate);if(parent===candidate)return null;candidate=parent}try{const stat13=statfsSync(candidate);return Number(stat13.bavail)*Number(stat13.bsize)}catch{return null}}function assertRuntimeGenerationCapacityPreflight(baseDir,probe={}){const available=(probe.availableBytes??defaultAvailableBytes)(baseDir);if(available===null||!Number.isFinite(available))return;if(available<requiredRuntimeGenerationFreeBytes(probe)){throw new RuntimeGenerationCapacityPreflightError}}var GIB,RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES,RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES,RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR,RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR,RuntimeGenerationCapacityPreflightError;var init_runtime_generation_capacity=__esm({"../platform/src/runtime-generation-capacity.ts"(){"use strict";GIB=1024*1024*1024;RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES=10*GIB;RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES=2*GIB;RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR=3;RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR=2;RuntimeGenerationCapacityPreflightError=class extends Error{reasonCode="runtime_generation_capacity_preflight_failed";constructor(){super("runtime generation capacity preflight failed");this.name="RuntimeGenerationCapacityPreflightError"}}}});import{spawnSync as spawnSync2}from"node:child_process";import{createHash as createHash76}from"node:crypto";import{lstatSync as lstatSync8,readFileSync as readFileSync32}from"node:fs";function tagRuntimeNativeClosureBackendStage(error62,stage){if((typeof error62!=="object"||error62===null)&&typeof error62!=="function")return error62;try{Object.defineProperty(error62,"runtimeNativeClosureBackendStage",{configurable:true,value:stage})}catch{}return error62}function nativeFailure(message,code,runtimeNativeClosureBackendStage="none"){const error62=new Error(message);if(code)error62.code=code;return tagRuntimeNativeClosureBackendStage(error62,runtimeNativeClosureBackendStage)}function isTrustedNativeBinary(dependencies){let stat13;try{stat13=dependencies.lstat(RUNTIME_NATIVE_CLOSURE_BINARY)}catch(error62){const code=error62&&typeof error62==="object"&&"code"in error62?String(error62.code):"";if(code==="ENOENT")return false;if(code==="EACCES"||code==="EPERM"){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_PERMISSION_INVALID","binary_identity")}throw nativeFailure("runtime generation verification failed","RUNTIME_NATIVE_CLOSURE_BINARY_UNREADABLE","binary_identity")}if(!stat13.isFile()||stat13.isSymbolicLink()||stat13.uid!==0||stat13.gid!==0||(stat13.mode&511)!==365){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_PERMISSION_INVALID","binary_identity")}let fingerprintStat;try{fingerprintStat=dependencies.lstat(RUNTIME_NATIVE_CLOSURE_FINGERPRINT)}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_UNREADABLE","binary_identity")}if(!fingerprintStat.isFile()||fingerprintStat.isSymbolicLink()||fingerprintStat.uid!==0||fingerprintStat.gid!==0||(fingerprintStat.mode&511)!==320){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_PERMISSION_INVALID","binary_identity")}let expected;try{expected=dependencies.readFile(RUNTIME_NATIVE_CLOSURE_FINGERPRINT,"utf8").trim()}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_UNREADABLE","binary_identity")}if(!SHA25615.test(expected)){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_INVALID","binary_identity")}let actual;try{actual=createHash76("sha256").update(dependencies.readFile(RUNTIME_NATIVE_CLOSURE_BINARY)).digest("hex")}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_UNREADABLE","binary_identity")}if(actual!==expected){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_MISMATCH","binary_identity")}return true}function execute(dependencies,args,input2){return dependencies.spawn(TIMEOUT_BINARY,["--signal=TERM","--kill-after=250ms",NATIVE_TIMEOUT_SECONDS,RUNTIME_NATIVE_CLOSURE_BINARY,...args],{input:input2,encoding:"utf8",timeout:HOST_TIMEOUT_MS,maxBuffer:NATIVE_MAX_BUFFER_BYTES})}function assertCapability(dependencies){const result3=execute(dependencies,["--capability"]);if(result3.error?.code==="ETIMEDOUT"||result3.status===124||result3.status===137){throw nativeFailure("runtime generation native verifier timeout","ETIMEDOUT","capability")}if(result3.status===77)throw nativeFailure("runtime generation permission invalid",void 0,"capability");if(result3.status===69&&result3.stdout===""&&result3.stderr===""){return false}if(result3.status===70||result3.status===78)throw nativeFailure("runtime generation verification failed",void 0,"capability");if(result3.error||result3.signal||result3.status!==0)throw nativeFailure("runtime generation verification failed",void 0,"capability");if(result3.stdout!==`${RUNTIME_NATIVE_CLOSURE_CAPABILITY}
10154
+ `;const result3=spawnSync(process.execPath,["--no-install","--eval",script],{cwd:resolve87(runtimeDir,"server"),encoding:"utf8",timeout:15e3,maxBuffer:64*1024});if(!result3.error&&result3.status===0)return;const failure2=result3.error?.message??`Bun exited with status ${result3.status??result3.signal??"unknown"}`;const detail=(result3.stderr||result3.stdout||"").trim().slice(-2048);throw new Error(`[runtime-layout] Runtime Core facade import validation failed: ${failure2}${detail?`: ${detail}`:""}`)}var RUNTIME_CORE_FACADE_RECIPE;var init_runtime_core_facade_composer=__esm({"../platform/src/runtime-core-facade-composer.ts"(){"use strict";RUNTIME_CORE_FACADE_RECIPE={version:1,backingCoreSpecifier:"./dist/index.js",compatibilitySpecifier:"../server/legacy-core/index.js",compatibilityFactory:"createLegacyCoreCompatibility",bindings:[["httpAction","legacy.httpAction"],["crud","legacy.crud"],["gencowCrud","legacy.crud"],["getRegisteredHttpActions","legacy.getRegisteredHttpActions"],["getRegisteredCrudCodegenMeta","legacy.getRegisteredCrudCodegenMeta"],["getOwnerRlsTables","legacy.getOwnerRlsTables"]]}}});import{mkdirSync as mkdirSync5,realpathSync as realpathSync5,rmSync as rmSync6,symlinkSync}from"node:fs";import{relative as relative22,resolve as resolve88}from"node:path";function safeRealpath3(path5){try{return realpathSync5(path5)}catch{return path5}}function symlinkRelativeEntry(targetPath,destinationPath,type="dir",options={}){rmSync6(destinationPath,{recursive:true,force:true});const destinationParent=resolve88(destinationPath,"..");mkdirSync5(destinationParent,{recursive:true});const fromPath=options.preserveLogicalPath?destinationParent:realpathSync5(destinationParent);const toPath3=options.preserveLogicalPath?resolve88(targetPath):safeRealpath3(targetPath);const relativeTarget=relative22(fromPath,toPath3)||".";symlinkSync(relativeTarget,destinationPath,type)}var init_runtime_generation_staging=__esm({"../platform/src/runtime-generation-staging.ts"(){"use strict"}});import{createHash as createHash75,randomUUID as randomUUID46}from"crypto";import{chmodSync,closeSync,constants as constants3,copyFileSync as copyFileSync2,existsSync as existsSync34,fsyncSync,lstatSync as lstatSync7,mkdirSync as mkdirSync6,mkdtempSync as mkdtempSync5,openSync,readFileSync as readFileSync31,readdirSync as readdirSync12,realpathSync as realpathSync6,renameSync,rmSync as rmSync7,statSync as statSync6,symlinkSync as symlinkSync2}from"fs";import{basename as basename10,dirname as dirname24,isAbsolute as isAbsolute25,join as join26,relative as relative23,resolve as resolve89,sep as sep3}from"path";function resolveRuntimeClosureNativePlanBudget(budget){const resolved={maxRecords:budget?.maxRecords??NATIVE_PLAN_MAX_RECORDS,maxEncodedBytes:budget?.maxEncodedBytes??NATIVE_PLAN_MAX_BYTES,maxPathBytes:budget?.maxPathBytes??NATIVE_PLAN_MAX_PATH_BYTES};if(!Number.isSafeInteger(resolved.maxRecords)||resolved.maxRecords<0||resolved.maxRecords>NATIVE_PLAN_MAX_RECORDS||!Number.isSafeInteger(resolved.maxEncodedBytes)||resolved.maxEncodedBytes<1||resolved.maxEncodedBytes>NATIVE_PLAN_MAX_BYTES||!Number.isSafeInteger(resolved.maxPathBytes)||resolved.maxPathBytes<1||resolved.maxPathBytes>NATIVE_PLAN_MAX_PATH_BYTES){throw new Error("runtime native closure plan budget invalid")}return resolved}function canonicalSealedRuntimeFileMode(mode){return mode&73?365:292}function packageManagerNodeModulesRoot(sourceRoot,targetPath){const targetRelativePath=ensureContainedPath(sourceRoot,targetPath,"package manager package");const parts=targetRelativePath.split(sep3);const pnpmIndex=parts.indexOf(".pnpm");if(pnpmIndex>=1&&parts[pnpmIndex-1]==="node_modules"&&parts[pnpmIndex+2]==="node_modules"){return parts.slice(0,pnpmIndex+3).join(sep3)}const bunIndex=parts.indexOf(".bun");if(bunIndex>=1&&parts[bunIndex-1]==="node_modules"&&parts[bunIndex+2]==="node_modules"){return parts.slice(0,bunIndex+3).join(sep3)}return null}function ensureContainedPath(root2,path5,label){const rel=relative23(root2,path5);if(!rel||rel===".")return".";if(isAbsolute25(rel)||rel===".."||rel.startsWith(`..${sep3}`)){throw new Error(`${label} escapes runtime root: ${path5}`)}return rel}function shouldExclude(path5,directory){const name=basename10(path5);if(name===".env"||name.startsWith(".env."))return true;if(!directory&&SECRET_FILE_PATTERN.test(name))return true;if(directory&&EXCLUDED_DIRECTORY_NAMES.has(name))return true;return!directory&&TEST_FILE_PATTERN.test(name)}function planFence(path5){const value2=lstatSync7(path5,{bigint:true});return{dev:value2.dev.toString(),ino:value2.ino.toString(),mode:value2.mode.toString(),size:value2.size.toString(),nlink:value2.nlink.toString(),mtimeNs:value2.mtimeNs.toString(),ctimeNs:value2.ctimeNs.toString()}}function planPath(path5,budget){const normalized=path5.replaceAll("\\","/");if(!normalized||normalized.startsWith("/")||normalized.includes("\0")||normalized.split("/").includes("..")){throw new Error("runtime generation plan path invalid")}if(Buffer.byteLength(normalized,"utf8")>budget.maxPathBytes){throw new RuntimeClosureNativePlanUnsupportedError}return normalized}function recordPlan(context,record3){if(!context.planRecords)return;if(context.planRecords.length>=context.planBudget.maxRecords){throw new RuntimeClosureNativePlanUnsupportedError}const encodedBytes=Buffer.byteLength(JSON.stringify(record3),"utf8")+1;const nextBytes=(context.planEncodedBytes??0)+encodedBytes;if(nextBytes>context.planBudget.maxEncodedBytes)throw new RuntimeClosureNativePlanUnsupportedError;context.planEncodedBytes=nextBytes;context.planRecords.push(record3)}function updateHash(context,value2){context.hash?.update(value2)}function copyFileWithClone(sourcePath,destinationPath){mkdirSync6(dirname24(destinationPath),{recursive:true,mode:493});copyFileSync2(sourcePath,destinationPath,constants3.COPYFILE_FICLONE);chmodSync(destinationPath,statSync6(sourcePath).mode&511)}function copyRelativeRuntimePath(context,relativePath){const sourcePath=resolve89(context.sourceRoot,relativePath);const safeRelativePath=ensureContainedPath(context.sourceRoot,sourcePath,"runtime snapshot path");if(context.visited.has(safeRelativePath)||!existsSync34(sourcePath))return;context.visited.add(safeRelativePath);const sourceStat=lstatSync7(sourcePath);if(shouldExclude(sourcePath,sourceStat.isDirectory()))return;const destinationPath=resolve89(context.stagingRoot,safeRelativePath);if(sourceStat.isSymbolicLink()){const targetPath=realpathSync6(sourcePath);const targetRelativePath=ensureContainedPath(context.sourceRoot,targetPath,"runtime symlink");const destinationTarget=resolve89(context.stagingRoot,targetRelativePath);mkdirSync6(dirname24(destinationPath),{recursive:true,mode:493});const linkTarget=relative23(dirname24(destinationPath),destinationTarget)||".";symlinkSync2(linkTarget,destinationPath,statSync6(targetPath).isDirectory()?"dir":"file");copyRelativeRuntimePath(context,targetRelativePath);const dependencyRoot=packageManagerNodeModulesRoot(context.sourceRoot,targetPath);if(dependencyRoot)copyRelativeRuntimePath(context,dependencyRoot);return}if(sourceStat.isDirectory()){mkdirSync6(destinationPath,{recursive:true,mode:sourceStat.mode&511|448});for(const entry of readdirSync12(sourcePath).sort()){copyRelativeRuntimePath(context,join26(safeRelativePath,entry))}return}if(sourceStat.isFile())copyFileWithClone(sourcePath,destinationPath)}function hashRelativeRuntimePath(context,relativePath){const sourcePath=resolve89(context.sourceRoot,relativePath);const safeRelativePath=ensureContainedPath(context.sourceRoot,sourcePath,"runtime hash path");if(context.visited.has(safeRelativePath)||!existsSync34(sourcePath))return;context.visited.add(safeRelativePath);const sourceStat=lstatSync7(sourcePath);if(shouldExclude(sourcePath,sourceStat.isDirectory()))return;if(sourceStat.isSymbolicLink()){const targetPath=realpathSync6(sourcePath);const targetRelativePath=ensureContainedPath(context.sourceRoot,targetPath,"runtime hash symlink");if(context.planRecords){recordPlan(context,{kind:"L",path:planPath(safeRelativePath,context.planBudget),target:planPath(targetRelativePath,context.planBudget),fence:planFence(sourcePath)})}updateHash(context,`L\0${safeRelativePath}\0${targetRelativePath}\0`);hashRelativeRuntimePath(context,targetRelativePath);const dependencyRoot=packageManagerNodeModulesRoot(context.sourceRoot,targetPath);if(dependencyRoot)hashRelativeRuntimePath(context,dependencyRoot);return}if(sourceStat.isDirectory()){if(context.planRecords){recordPlan(context,{kind:"D",path:planPath(safeRelativePath,context.planBudget),fence:planFence(sourcePath)})}updateHash(context,`D\0${safeRelativePath}\0`);for(const entry of readdirSync12(sourcePath).sort()){hashRelativeRuntimePath(context,join26(safeRelativePath,entry))}return}if(sourceStat.isFile()){if(context.planRecords){recordPlan(context,{kind:"F",path:planPath(safeRelativePath,context.planBudget),fence:planFence(sourcePath)})}const executeBits=canonicalSealedRuntimeFileMode(sourceStat.mode)&73;updateHash(context,`F\0${safeRelativePath}\0${executeBits}\0`);if(context.hash){context.hash.update(readFileSync31(sourcePath));context.hash.update("\0")}}}function createRuntimeClosureNativePlan(params){const sourceRoot=realpathSync6(params.runtimeRoot);const budget=resolveRuntimeClosureNativePlanBudget(params.budget);if(Buffer.byteLength(sourceRoot,"utf8")>budget.maxPathBytes){throw new RuntimeClosureNativePlanUnsupportedError}const root2={path:sourceRoot,...planFence(sourceRoot)};const initialPlanEncodedBytes=Buffer.byteLength(JSON.stringify({version:1,root:root2,records:[]}),"utf8");if(initialPlanEncodedBytes>budget.maxEncodedBytes){throw new RuntimeClosureNativePlanUnsupportedError}const context={sourceRoot,visited:new Set,planRecords:[],planEncodedBytes:initialPlanEncodedBytes,planBudget:budget};for(const seed of params.closureSeeds)hashRelativeRuntimePath(context,seed);return{version:1,root:root2,records:context.planRecords}}function createRuntimeClosureNativePlanForManifest(manifest){const sourceRoot=runtimeSnapshotSourceRoot(manifest);return createRuntimeClosureNativePlan({runtimeRoot:sourceRoot,closureSeeds:runtimeSnapshotSeeds(manifest,sourceRoot)})}function mapRuntimePath(sourceRoot,finalRoot,path5,label){const sourcePath=realpathSync6(path5);const relativePath=ensureContainedPath(sourceRoot,sourcePath,label);return resolve89(finalRoot,relativePath)}function copyBinarySnapshot(params){if(params.snapshot.status!=="present"||!params.snapshot.path)return params.snapshot;const sourcePath=realpathSync6(params.snapshot.path);const extension=process.platform==="win32"?".exe":"";const relativePath=params.layoutVersion===3?join26("runtime","bin",`${params.name}${extension}`):join26("bin",`${params.name}${extension}`);copyFileWithClone(sourcePath,resolve89(params.stagingRoot,relativePath));return{...params.snapshot,path:resolve89(params.finalRoot,relativePath)}}function runtimeSnapshotSourceRoot(manifest){const runtimeRoot=realpathSync6(manifest.runtimeRoot);return manifest.layoutVersion===3?realpathSync6(resolve89(runtimeRoot,"..")):runtimeRoot}function runtimeSnapshotSeeds(manifest,sourceRoot){const layout=detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path);const seeds=new Set(layout==="managed-release"?manifest.layoutVersion===3?["runtime/server","runtime/core","runtime/node_modules","public-node_modules","platform/src","platform/node_modules"]:["manifest.json","server","core","node_modules"]:["package.json","pnpm-workspace.yaml","packages/server/src","packages/server/package.json","packages/server/node_modules","packages/core/src","packages/core/dist","packages/core/package.json","packages/core/node_modules","packages/client/src","packages/client/dist","packages/client/package.json","packages/client/node_modules","packages/shared/dist","packages/shared/package.json","packages/shared/node_modules","packages/internal/dist","packages/internal/package.json","packages/internal/node_modules","packages/platform/src","packages/platform/package.json","packages/platform/node_modules","packages/cli/server","packages/cli/core"]);for(const lockfile of manifest.packageManager.lockfiles)seeds.add(lockfile.file);for(const snapshot of Object.values(manifest.packages)){if(snapshot.status!=="present"||!snapshot.packageJsonPath)continue;const packagePath=realpathSync6(dirname24(snapshot.packageJsonPath));seeds.add(ensureContainedPath(sourceRoot,packagePath,"runtime package"))}return[...seeds].sort()}function sha256RuntimePaths(sourceRoot,seeds){const canonicalRoot=realpathSync6(sourceRoot);const context={sourceRoot:canonicalRoot,visited:new Set,hash:createHash75("sha256")};for(const seed of seeds)hashRelativeRuntimePath(context,seed);return`sha256:${context.hash.digest("hex")}`}function assertRuntimeClosureMatchesAtRoot(params){const actualClosureSha256=sha256RuntimePaths(params.runtimeRoot,params.closureSeeds);if(actualClosureSha256!==params.expectedClosureSha256){throw new Error(`runtime generation closure hash mismatch: expected ${params.expectedClosureSha256}, got ${actualClosureSha256}`)}}function sha256RuntimeSnapshot(manifest){const sourceRoot=runtimeSnapshotSourceRoot(manifest);return sha256RuntimePaths(sourceRoot,runtimeSnapshotSeeds(manifest,sourceRoot))}function runtimeReleaseId(manifestHash,runtimeClosureSha256){return`sha256:${createHash75("sha256").update(`${manifestHash}\0${runtimeClosureSha256}`).digest("hex")}`}function prepareRuntimeGenerationManifest(manifest){const runtimeClosureSha256=sha256RuntimeSnapshot(manifest);return{...manifest,releaseId:runtimeReleaseId(deploymentRuntimeManifestHash(manifest),runtimeClosureSha256),runtimeClosureSha256}}function runtimeGenerationDirectorySuffix(generationId){if(!RUNTIME_GENERATION_ID_PATTERN.test(generationId)){throw new Error(`invalid runtime generation id: ${generationId}`)}return generationId.replace("sha256:","sha256-")}function formatRuntimeGenerationDirectoryTimestamp(generatedAt){const parsed=new Date(generatedAt);if(Number.isNaN(parsed.getTime())){throw new Error(`invalid runtime generation timestamp: ${generatedAt}`)}return parsed.toISOString().replace(/[-:.]/g,"")}function runtimeGenerationDirectoryName(generationId,generatedAt){return`${formatRuntimeGenerationDirectoryTimestamp(generatedAt)}-${runtimeGenerationDirectorySuffix(generationId)}`}function resolveRuntimeGenerationDirectoryPath(baseDir,generationId){const suffix=runtimeGenerationDirectorySuffix(generationId);const timestampedMatches=[];if(!existsSync34(baseDir))return null;for(const entry of readdirSync12(baseDir,{withFileTypes:true})){if(!entry.isDirectory())continue;if(entry.name.endsWith(`-${suffix}`)&&COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN.test(entry.name)){const timestampSource=entry.name.slice(0,-`-${suffix}`.length);const parsedTimestamp=new Date(timestampSource.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\d{3})Z$/,"$1-$2-$3T$4:$5:$6.$7Z")).getTime();if(!Number.isNaN(parsedTimestamp)){timestampedMatches.push({entryName:entry.name,timestamp:parsedTimestamp})}}}const selected=timestampedMatches.sort((a,b2)=>a.timestamp-b2.timestamp||a.entryName.localeCompare(b2.entryName)).at(-1);if(selected)return resolve89(baseDir,selected.entryName);const legacyGenerationDir=resolve89(baseDir,suffix);return existsSync34(legacyGenerationDir)?legacyGenerationDir:null}function runtimeGenerationDirectoryPath(baseDir,generationId,generatedAt){return resolve89(baseDir,runtimeGenerationDirectoryName(generationId,generatedAt))}function stageRuntimeGeneration(params){const sourceRoot=runtimeSnapshotSourceRoot(params.manifest);if(!params.manifest.releaseId||!params.manifest.runtimeClosureSha256){throw new Error("runtime generation manifest is missing its release content identity")}const finalGenerationDir=runtimeGenerationDirectoryPath(params.baseDir,params.manifest.releaseId,params.manifest.generatedAt);const finalRoot=params.manifest.layoutVersion===3?finalGenerationDir:resolve89(finalGenerationDir,"runtime");mkdirSync6(params.baseDir,{recursive:true,mode:493});const publicationOwner=/^[a-f0-9]{32}$/.test(process.env.GENCOW_RUNTIME_PUBLICATION_OWNER??"")?`-${process.env.GENCOW_RUNTIME_PUBLICATION_OWNER}`:"";const stagedGenerationDir=mkdtempSync5(resolve89(params.baseDir,`.tmp-${params.manifestHash.replace(":","-")}-${process.pid}${publicationOwner}-${randomUUID46()}-`));const stagingRoot=params.manifest.layoutVersion===3?stagedGenerationDir:resolve89(stagedGenerationDir,"runtime");try{const context={sourceRoot,stagingRoot,visited:new Set};const seeds=runtimeSnapshotSeeds(params.manifest,sourceRoot);for(const seed of seeds){copyRelativeRuntimePath(context,seed)}assertRuntimeClosureMatchesAtRoot({runtimeRoot:params.manifest.layoutVersion===3?stagedGenerationDir:stagingRoot,closureSeeds:seeds,expectedClosureSha256:params.manifest.runtimeClosureSha256});const packages=Object.fromEntries(Object.entries(params.manifest.packages).map(([name,snapshot])=>[name,snapshot.status==="present"&&snapshot.packageJsonPath?{...snapshot,packageJsonPath:mapRuntimePath(sourceRoot,finalRoot,snapshot.packageJsonPath,`package ${name}`)}:snapshot]));const binaries=Object.fromEntries(Object.entries(params.manifest.binaries).map(([name,snapshot])=>[name,copyBinarySnapshot({name,snapshot,stagingRoot,finalRoot,layoutVersion:params.manifest.layoutVersion})]));return{stagedGenerationDir,finalGenerationDir,closureSeeds:seeds,publishedManifest:{...params.manifest,runtimeRoot:params.manifest.layoutVersion===3?resolve89(finalGenerationDir,"runtime"):finalRoot,serverEntry:{...params.manifest.serverEntry,path:mapRuntimePath(sourceRoot,finalRoot,params.manifest.serverEntry.path,"server entry")},packages,binaries}}}catch(error62){discardStagedRuntimeGeneration(stagedGenerationDir);throw error62}}function makePathWritable(path5){if(!existsSync34(path5))return;const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){chmodSync(path5,493);for(const entry of readdirSync12(path5))makePathWritable(resolve89(path5,entry))}else if(pathStat.isFile()){chmodSync(path5,pathStat.mode|384)}}function discardStagedRuntimeGeneration(stagedGenerationDir){if(!existsSync34(stagedGenerationDir))return;makePathWritable(stagedGenerationDir);rmSync7(stagedGenerationDir,{recursive:true,force:true})}function commitStagedRuntimeGeneration(stagedGenerationDir,finalGenerationDir){try{renameSync(stagedGenerationDir,finalGenerationDir);return"published"}catch(error62){if(existsSync34(finalGenerationDir)){discardStagedRuntimeGeneration(stagedGenerationDir);return"existing"}discardStagedRuntimeGeneration(stagedGenerationDir);throw error62}}function sealPathReadOnly(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){for(const entry of readdirSync12(path5))sealPathReadOnly(resolve89(path5,entry));chmodSync(path5,365);return}if(pathStat.isFile())chmodSync(path5,canonicalSealedRuntimeFileMode(pathStat.mode))}function sealStagedRuntimeGeneration(stagedGenerationDir){if(existsSync34(resolve89(stagedGenerationDir,"runtime"))){sealPathReadOnly(resolve89(stagedGenerationDir,"runtime"))}if(existsSync34(resolve89(stagedGenerationDir,"public-node_modules"))){sealPathReadOnly(resolve89(stagedGenerationDir,"public-node_modules"))}if(existsSync34(resolve89(stagedGenerationDir,"platform"))){sealPathReadOnly(resolve89(stagedGenerationDir,"platform"))}if(existsSync34(resolve89(stagedGenerationDir,"scripts"))){sealPathReadOnly(resolve89(stagedGenerationDir,"scripts"))}chmodSync(resolve89(stagedGenerationDir,"runtime-manifest.json"),292);chmodSync(stagedGenerationDir,365)}function assertPathReadOnly(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;const mode=pathStat.mode&511;if(pathStat.isDirectory()){if(mode!==365){throw new Error("runtime generation permission invalid")}for(const entry of readdirSync12(path5))assertPathReadOnly(resolve89(path5,entry));return}if(pathStat.isFile()&&mode!==292&&mode!==365){throw new Error("runtime generation permission invalid")}if(!pathStat.isFile()){throw new Error("runtime generation permission invalid")}}function assertRuntimeGenerationSealed(generationDir){assertPathReadOnly(generationDir);if((lstatSync7(resolve89(generationDir,"runtime-manifest.json")).mode&511)!==292){throw new Error("runtime generation permission invalid")}}function fsyncPathTree(path5){const pathStat=lstatSync7(path5);if(pathStat.isSymbolicLink())return;if(pathStat.isDirectory()){for(const entry of readdirSync12(path5))fsyncPathTree(resolve89(path5,entry))}const fd=openSync(path5,"r");try{fsyncSync(fd)}finally{closeSync(fd)}}function fsyncStagedRuntimeGeneration(stagedGenerationDir){fsyncPathTree(stagedGenerationDir)}var EXCLUDED_DIRECTORY_NAMES,TEST_FILE_PATTERN,SECRET_FILE_PATTERN,RUNTIME_GENERATION_ID_PATTERN,COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN,RuntimeClosureNativePlanUnsupportedError,NATIVE_PLAN_MAX_RECORDS,NATIVE_PLAN_MAX_BYTES,NATIVE_PLAN_MAX_PATH_BYTES;var init_runtime_generation_publisher=__esm({"../platform/src/runtime-generation-publisher.ts"(){"use strict";init_deployment_runtime_manifest();EXCLUDED_DIRECTORY_NAMES=new Set([".git",".gencow","__tests__"]);TEST_FILE_PATTERN=/\.(?:test|spec)\.[cm]?[jt]sx?$/;SECRET_FILE_PATTERN=/^(?:\.npmrc|\.yarnrc|\.netrc|\.pypirc|id_rsa|id_ed25519)$|(?:private|secret|credential).*\.(?:key|pem|p12|pfx)$|\.(?:key|p12|pfx)$/i;RUNTIME_GENERATION_ID_PATTERN=/^sha256:[a-f0-9]{64}$/;COMPACT_TIMESTAMPED_RUNTIME_GENERATION_DIRECTORY_PATTERN=/^\d{8}T\d{9}Z-sha256-[a-f0-9]{64}$/;RuntimeClosureNativePlanUnsupportedError=class extends Error{constructor(){super("runtime native closure backend unsupported");this.name="RuntimeClosureNativePlanUnsupportedError"}};NATIVE_PLAN_MAX_RECORDS=1e5;NATIVE_PLAN_MAX_BYTES=32*1024*1024;NATIVE_PLAN_MAX_PATH_BYTES=4096}});import{existsSync as existsSync35,statfsSync}from"fs";import{dirname as dirname25}from"path";function requiredRuntimeGenerationFreeBytes(probe={}){const watermark=probe.watermarkBytes??RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES;const closure=probe.expectedClosureBytes??RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES;const withHeadroom=Math.ceil(closure*RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR/RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR);return Math.max(watermark,withHeadroom)}function defaultAvailableBytes(path5){let candidate=path5;while(!existsSync35(candidate)){const parent=dirname25(candidate);if(parent===candidate)return null;candidate=parent}try{const stat13=statfsSync(candidate);return Number(stat13.bavail)*Number(stat13.bsize)}catch{return null}}function formatGiB(bytes2,rounding){const hundredths=bytes2/GIB*100;const rounded=rounding==="floor"?Math.floor(hundredths):Math.ceil(hundredths);return(rounded/100).toFixed(2)}function assertRuntimeGenerationCapacityPreflight(baseDir,probe={}){const available=(probe.availableBytes??defaultAvailableBytes)(baseDir);if(available===null||!Number.isFinite(available))return;const required3=requiredRuntimeGenerationFreeBytes(probe);if(available<required3){throw new RuntimeGenerationCapacityPreflightError(available,required3)}}var GIB,RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES,RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES,RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR,RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR,RuntimeGenerationCapacityPreflightError;var init_runtime_generation_capacity=__esm({"../platform/src/runtime-generation-capacity.ts"(){"use strict";GIB=1024*1024*1024;RUNTIME_GENERATION_CAPACITY_WATERMARK_BYTES=10*GIB;RUNTIME_GENERATION_CAPACITY_UNKNOWN_CLOSURE_BYTES=2*GIB;RUNTIME_GENERATION_CAPACITY_HEADROOM_NUMERATOR=3;RUNTIME_GENERATION_CAPACITY_HEADROOM_DENOMINATOR=2;RuntimeGenerationCapacityPreflightError=class extends Error{constructor(availableBytes,requiredBytes){const shortfall=formatGiB(requiredBytes-availableBytes,"ceil");super(`runtime generation capacity preflight failed: available ${formatGiB(availableBytes,"floor")} GiB, required ${formatGiB(requiredBytes,"ceil")} GiB. Free at least ${shortfall} GiB on the filesystem that holds the runtime generation store on this node or worker, then retry the same operation. No runtime generation or serving state was changed.`);this.availableBytes=availableBytes;this.requiredBytes=requiredBytes;this.name="RuntimeGenerationCapacityPreflightError"}availableBytes;requiredBytes;reasonCode="runtime_generation_capacity_preflight_failed"}}});import{spawnSync as spawnSync2}from"node:child_process";import{createHash as createHash76}from"node:crypto";import{lstatSync as lstatSync8,readFileSync as readFileSync32}from"node:fs";function tagRuntimeNativeClosureBackendStage(error62,stage){if((typeof error62!=="object"||error62===null)&&typeof error62!=="function")return error62;try{Object.defineProperty(error62,"runtimeNativeClosureBackendStage",{configurable:true,value:stage})}catch{}return error62}function nativeFailure(message,code,runtimeNativeClosureBackendStage="none"){const error62=new Error(message);if(code)error62.code=code;return tagRuntimeNativeClosureBackendStage(error62,runtimeNativeClosureBackendStage)}function isTrustedNativeBinary(dependencies){let stat13;try{stat13=dependencies.lstat(RUNTIME_NATIVE_CLOSURE_BINARY)}catch(error62){const code=error62&&typeof error62==="object"&&"code"in error62?String(error62.code):"";if(code==="ENOENT")return false;if(code==="EACCES"||code==="EPERM"){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_PERMISSION_INVALID","binary_identity")}throw nativeFailure("runtime generation verification failed","RUNTIME_NATIVE_CLOSURE_BINARY_UNREADABLE","binary_identity")}if(!stat13.isFile()||stat13.isSymbolicLink()||stat13.uid!==0||stat13.gid!==0||(stat13.mode&511)!==365){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_PERMISSION_INVALID","binary_identity")}let fingerprintStat;try{fingerprintStat=dependencies.lstat(RUNTIME_NATIVE_CLOSURE_FINGERPRINT)}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_UNREADABLE","binary_identity")}if(!fingerprintStat.isFile()||fingerprintStat.isSymbolicLink()||fingerprintStat.uid!==0||fingerprintStat.gid!==0||(fingerprintStat.mode&511)!==320){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_PERMISSION_INVALID","binary_identity")}let expected;try{expected=dependencies.readFile(RUNTIME_NATIVE_CLOSURE_FINGERPRINT,"utf8").trim()}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_UNREADABLE","binary_identity")}if(!SHA25615.test(expected)){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_INVALID","binary_identity")}let actual;try{actual=createHash76("sha256").update(dependencies.readFile(RUNTIME_NATIVE_CLOSURE_BINARY)).digest("hex")}catch{throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_BINARY_UNREADABLE","binary_identity")}if(actual!==expected){throw nativeFailure("runtime generation permission invalid","RUNTIME_NATIVE_CLOSURE_FINGERPRINT_MISMATCH","binary_identity")}return true}function execute(dependencies,args,input2){return dependencies.spawn(TIMEOUT_BINARY,["--signal=TERM","--kill-after=250ms",NATIVE_TIMEOUT_SECONDS,RUNTIME_NATIVE_CLOSURE_BINARY,...args],{input:input2,encoding:"utf8",timeout:HOST_TIMEOUT_MS,maxBuffer:NATIVE_MAX_BUFFER_BYTES})}function assertCapability(dependencies){const result3=execute(dependencies,["--capability"]);if(result3.error?.code==="ETIMEDOUT"||result3.status===124||result3.status===137){throw nativeFailure("runtime generation native verifier timeout","ETIMEDOUT","capability")}if(result3.status===77)throw nativeFailure("runtime generation permission invalid",void 0,"capability");if(result3.status===69&&result3.stdout===""&&result3.stderr===""){return false}if(result3.status===70||result3.status===78)throw nativeFailure("runtime generation verification failed",void 0,"capability");if(result3.error||result3.signal||result3.status!==0)throw nativeFailure("runtime generation verification failed",void 0,"capability");if(result3.stdout!==`${RUNTIME_NATIVE_CLOSURE_CAPABILITY}
10155
10155
  `||result3.stderr){throw nativeFailure("runtime generation verification failed",void 0,"capability")}return true}function encodePlan(plan2,budget){if(plan2.records.length>budget.maxRecords)throw new RuntimeClosureNativePlanUnsupportedError;const encoded=JSON.stringify(plan2);if(Buffer.byteLength(encoded,"utf8")>budget.maxEncodedBytes){throw new RuntimeClosureNativePlanUnsupportedError}return encoded}function plannedFileBytes(plan2){const total=plan2.records.filter(entry=>entry.kind==="F").reduce((sum,entry)=>sum+BigInt(entry.fence.size),0n);if(total>BigInt(Number.MAX_SAFE_INTEGER))throw new RuntimeClosureNativePlanUnsupportedError;return Number(total)}function parseNativeOutput(result3,plan2,expectedByteCount){if(result3.error?.code==="ETIMEDOUT"||result3.status===124||result3.status===137){throw nativeFailure("runtime generation native verifier timeout","ETIMEDOUT","execute")}if(result3.status===77)throw nativeFailure("runtime generation permission invalid",void 0,"execute");if(result3.status===78)throw nativeFailure("runtime generation closure hash mismatch",void 0,"execute");if(result3.status!==0)throw nativeFailure("runtime generation verification failed",void 0,"output");if(result3.error||result3.signal||result3.stderr)throw nativeFailure("runtime generation verification failed",void 0,result3.stderr?"output":"execute");let output2;try{output2=JSON.parse(result3.stdout)}catch{throw nativeFailure("runtime generation verification failed",void 0,"output")}if(!output2||typeof output2!=="object"||Array.isArray(output2)){throw nativeFailure("runtime generation verification failed",void 0,"output")}const record3=output2;if(Object.keys(record3).sort().join("\0")!=="byteCount\0digest\0recordCount\0version"||record3.version!==1||typeof record3.digest!=="string"||!DIGEST.test(record3.digest)||record3.recordCount!==plan2.records.length||typeof record3.byteCount!=="number"||!Number.isSafeInteger(record3.byteCount)||record3.byteCount<0||record3.byteCount!==expectedByteCount){throw nativeFailure("runtime generation verification failed",void 0,"output")}return record3}function configured(dependencies){return dependencies.env.GENCOW_PROD_SIM_RUNTIME_NATIVE_CLOSURE_BACKEND==="cowbox-v1"}function selectTrustedRuntimeNativeClosureBackend(partial3={}){const{planBudget,...partialDependencies}=partial3;const budget={maxRecords:planBudget?.maxRecords??MAX_PLAN_RECORDS,maxEncodedBytes:planBudget?.maxEncodedBytes??MAX_PLAN_BYTES};if(!Number.isSafeInteger(budget.maxRecords)||budget.maxRecords<0||budget.maxRecords>MAX_PLAN_RECORDS||!Number.isSafeInteger(budget.maxEncodedBytes)||budget.maxEncodedBytes<1||budget.maxEncodedBytes>MAX_PLAN_BYTES){throw new Error("runtime native closure plan budget invalid")}const dependencies={platform:process.platform,env:process.env,lstat:lstatSync8,readFile:readFileSync32,spawn:spawnSync2,...partialDependencies};if(!configured(dependencies)||dependencies.platform!=="linux")return null;if(!isTrustedNativeBinary(dependencies)||!assertCapability(dependencies))return null;return{capability:RUNTIME_NATIVE_CLOSURE_CAPABILITY,verify(manifest){let plan2;let encoded;let expectedByteCount;try{plan2=createRuntimeClosureNativePlanForManifest(manifest);encoded=encodePlan(plan2,budget);expectedByteCount=plannedFileBytes(plan2)}catch(error62){if(error62 instanceof RuntimeClosureNativePlanUnsupportedError)return{kind:"unsupported"};throw tagRuntimeNativeClosureBackendStage(error62,"plan")}return{kind:"verified",output:parseNativeOutput(execute(dependencies,[],encoded),plan2,expectedByteCount)}}}}var RUNTIME_NATIVE_CLOSURE_CAPABILITY,RUNTIME_NATIVE_CLOSURE_BINARY,RUNTIME_NATIVE_CLOSURE_FINGERPRINT,TIMEOUT_BINARY,NATIVE_TIMEOUT_SECONDS,HOST_TIMEOUT_MS,NATIVE_MAX_BUFFER_BYTES,MAX_PLAN_BYTES,MAX_PLAN_RECORDS,SHA25615,DIGEST;var init_runtime_native_closure_backend=__esm({"../platform/src/runtime-native-closure-backend.ts"(){"use strict";init_runtime_generation_publisher();RUNTIME_NATIVE_CLOSURE_CAPABILITY="gencow_runtime_closure_plan_v1";RUNTIME_NATIVE_CLOSURE_BINARY="/usr/local/bin/runtime-closure-plan-v1";RUNTIME_NATIVE_CLOSURE_FINGERPRINT="/opt/gencow/prod-sim-runtime-integrity/runtime-closure-plan-v1.sha256";TIMEOUT_BINARY="/usr/bin/timeout";NATIVE_TIMEOUT_SECONDS="3s";HOST_TIMEOUT_MS=3e3;NATIVE_MAX_BUFFER_BYTES=4096;MAX_PLAN_BYTES=32*1024*1024;MAX_PLAN_RECORDS=1e5;SHA25615=/^[a-f0-9]{64}$/u;DIGEST=/^sha256:[a-f0-9]{64}$/u}});function readNow(clock){try{const value2=clock();return Number.isFinite(value2)&&value2>=0?value2:null}catch{return null}}function createRuntimeGenerationVerificationContext(observer,options={}){if(!observer)return void 0;const clock=options.now??(()=>performance.now());const origin=readNow(clock);if(origin===null)return void 0;return{observe(phase,work,reason=()=>"runtime_generation_verification_failed"){const startedAt=readNow(clock);if(startedAt!==null&&startedAt>=origin){try{observer.observe({phase,outcome:"started",elapsedMs:startedAt-origin})}catch{}}try{const result3=work();const endedAt=readNow(clock);if(startedAt!==null&&endedAt!==null&&endedAt>=startedAt&&endedAt>=origin){try{observer.observe({phase,outcome:"completed",elapsedMs:endedAt-origin,durationMs:endedAt-startedAt})}catch{}}return result3}catch(error62){const endedAt=readNow(clock);if(startedAt!==null&&endedAt!==null&&endedAt>=startedAt&&endedAt>=origin){try{observer.observe({phase,outcome:"failed",elapsedMs:endedAt-origin,durationMs:endedAt-startedAt,reasonCode:reason(error62)})}catch{}}throw error62}}}}var init_runtime_generation_verification_observer=__esm({"../platform/src/runtime-generation-verification-observer.ts"(){"use strict"}});import{createHash as createHash77}from"crypto";import{closeSync as closeSync2,existsSync as existsSync36,fsyncSync as fsyncSync2,openSync as openSync2,readFileSync as readFileSync33,writeFileSync as writeFileSync5}from"fs";import{resolve as resolve90}from"path";function runtimeGenerationFailureReason(error62){if(error62 instanceof RuntimeGenerationPublishError)return error62.reasonCode;if(error62 instanceof RuntimeGenerationCapacityPreflightError)return error62.reasonCode;const errno=error62&&typeof error62==="object"&&"code"in error62?String(error62.code):"";if(errno==="ENOSPC"||errno==="EDQUOT")return"runtime_generation_capacity_exhausted";if(errno==="ETIMEDOUT"||errno==="ETIME")return"runtime_generation_timeout";const message=error62 instanceof Error?error62.message:String(error62);if(message.includes("runtime generation incomplete"))return"runtime_generation_incomplete";if(message.includes("closure hash mismatch"))return"runtime_closure_mismatch";if(message.includes("permission")||message.includes("EACCES")||message.includes("EPERM")){return"runtime_generation_permission_invalid"}if(message.includes("manifest")||message.includes("identity")||message.includes("catalog")||message.includes("invalid runtime generation id")){return"runtime_manifest_invalid"}if(message.includes("hash mismatch")||message.includes("content hash mismatch")){return"runtime_artifact_hash_mismatch"}if(message.includes("missing"))return"runtime_generation_missing";return"runtime_generation_verification_failed"}function asRuntimeGenerationPublicationError(error62,stage){return runtimeGenerationFailureReason(error62)==="runtime_generation_verification_failed"?new RuntimeGenerationPublishError(stage):error62}function isRuntimeGenerationFullyVerifiedInCurrentProcess(value2){return typeof value2==="object"&&value2!==null&&fullyVerifiedRuntimeReferences.has(value2)}function markRuntimeGenerationFullyVerified(reference){fullyVerifiedRuntimeReferences.add(reference);return reference}function observeRuntimeClosureVerification(observer,stats){if(!observer)return;try{observer.observe(stats)}catch{}}function observed(observer,phase,work){return observer?observer.observe(phase,work,runtimeGenerationFailureReason):work()}function assertRuntimeClosureMatches(manifest,expectedRoot,releaseId,forceVerification=false,observer,closureVerificationBackend,closureVerificationObserver){if(!manifest.runtimeClosureSha256){throw new Error(`runtime generation closure identity missing: ${releaseId}`)}const verificationRoot=manifest.layoutVersion===3?resolve90(expectedRoot,".."):expectedRoot;const closureCacheKey=`${verificationRoot}\0${manifest.runtimeClosureSha256}`;if(!forceVerification&&verifiedRuntimeClosures.has(closureCacheKey))return;if(forceVerification)verifiedRuntimeClosures.delete(closureCacheKey);observed(observer,"generation_seal_traversal",()=>assertRuntimeGenerationSealed(resolve90(expectedRoot,"..")));observed(observer,"runtime_closure_hash",()=>{const nativeResult=closureVerificationBackend==="trusted-native-if-supported"?selectTrustedRuntimeNativeClosureBackend()?.verify(manifest):void 0;const actualClosureSha256=nativeResult?.kind==="verified"?nativeResult.output.digest:sha256RuntimeSnapshot(manifest);if(actualClosureSha256!==manifest.runtimeClosureSha256){verifiedRuntimeClosures.delete(closureCacheKey);const mismatch=new Error(`runtime generation closure hash mismatch: ${releaseId} expected ${manifest.runtimeClosureSha256}, got ${actualClosureSha256}`);throw nativeResult?.kind==="verified"?tagRuntimeNativeClosureBackendStage(mismatch,"digest_compare"):mismatch}const stats=Object.freeze(nativeResult?.kind==="verified"?{backend:"gencow_runtime_closure_plan_v1",recordCount:nativeResult.output.recordCount,byteCount:nativeResult.output.byteCount}:{backend:"typescript",recordCount:null,byteCount:null});observeRuntimeClosureVerification(closureVerificationObserver,stats)});verifiedRuntimeClosures.add(closureCacheKey)}function getRuntimeGenerationsDir(env=process.env){if(env.GENCOW_RUNTIME_GENERATIONS_DIR)return env.GENCOW_RUNTIME_GENERATIONS_DIR;if(env.IS_PLATFORM==="true"||env.NODE_ENV==="production")return DEFAULT_GENERATIONS_DIR;return resolve90(process.cwd(),".gencow-runtime","runtime-generations")}function generationManifestPath(generationId,baseDir=getRuntimeGenerationsDir()){const generationDir=resolveRuntimeGenerationDirectoryPath(baseDir,generationId)||resolve90(baseDir,generationId);return resolve90(generationDir,"runtime-manifest.json")}function readPublishedRuntimeManifest(releaseId,baseDir){try{return parseDeploymentRuntimeManifest(readFileSync33(generationManifestPath(releaseId,baseDir),"utf-8"))}catch(error62){const code=error62.code;if(code==="EACCES"||code==="EPERM"){throw new Error(`runtime generation permission invalid: ${releaseId}`)}if(code==="ENOENT"){throw new Error(`runtime generation missing: ${releaseId}`)}throw new Error(`runtime generation manifest invalid: ${releaseId}`)}}function normalizeRuntimeManifestHash(manifestHash){if(/^sha256:[a-f0-9]{64}$/.test(manifestHash)){return manifestHash}if(/^[a-f0-9]{64}$/.test(manifestHash)){return`sha256:${manifestHash}`}throw new Error(`invalid runtime manifest hash: ${manifestHash}`)}function ensureSafeManifestHash(manifestHash){normalizeRuntimeManifestHash(manifestHash)}function hasRuntimeContentIdentity(manifest){return Boolean(manifest.releaseId&&manifest.runtimeClosureSha256)}function assertLegacyIdentityFieldsAreAbsent(manifest,releaseId,manifestHash){if(manifest.releaseId||manifest.runtimeClosureSha256){throw new Error(`runtime generation release identity mismatch: ${releaseId}`)}if(releaseId!==manifestHash){throw new Error(`runtime generation content identity mismatch: ${releaseId}`)}}function sha256File2(path5){return`sha256:${createHash77("sha256").update(readFileSync33(path5)).digest("hex")}`}function assertFileHashMatches(path5,expectedSha256,label,manifestHash){if(!existsSync36(path5)){throw new Error(`runtime generation ${label} missing: ${manifestHash}`)}const actualSha256=sha256File2(path5);if(actualSha256!==expectedSha256){throw new Error(`runtime generation ${label} hash mismatch: ${manifestHash} expected ${expectedSha256}, got ${actualSha256}`)}}function assertRuntimeArtifactsMatchManifest(manifest,manifestHash,verifyContent,observer){observed(observer,"scalar_artifact_verification",()=>assertFileHashMatches(manifest.serverEntry.path,manifest.serverEntry.sha256,"server entry",manifestHash));for(const lockfile of manifest.packageManager.lockfiles){observed(observer,"scalar_artifact_verification",()=>assertFileHashMatches(resolve90(manifest.runtimeRoot,lockfile.file),lockfile.sha256,lockfile.file,manifestHash))}for(const[packageName,snapshot]of Object.entries(manifest.packages)){if(snapshot.status!=="present"||!snapshot.packageJsonPath)continue;observed(observer,"scalar_artifact_verification",()=>{const parsed=JSON.parse(readFileSync33(snapshot.packageJsonPath,"utf-8"));const actualVersion=typeof parsed.version==="string"?parsed.version:"";if(actualVersion!==snapshot.version){throw new Error(`runtime generation package ${packageName} version mismatch: ${manifestHash} expected ${snapshot.version}, got ${actualVersion}`)}});if(verifyContent&&snapshot.treeSha256){observed(observer,"package_tree_hashes",()=>{if(sha256RuntimeTree(resolve90(snapshot.packageJsonPath,".."))!==snapshot.treeSha256){throw new Error(`runtime generation package ${packageName} content hash mismatch: ${manifestHash}`)}})}}for(const[binaryName,snapshot]of Object.entries(manifest.binaries)){if(snapshot.status!=="present"||!snapshot.path||!snapshot.sha256)continue;observed(observer,"scalar_artifact_verification",()=>assertFileHashMatches(snapshot.path,snapshot.sha256,`binary ${binaryName}`,manifestHash))}if(!verifyContent)return;const layout=detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path);const artifactPaths=runtimeArtifactPathsForLayout(layout);observed(observer,"managed_artifact_hashes",()=>{const managedArtifactHashes=layout==="managed-release"?hashManagedRuntimeArtifacts(manifest.runtimeRoot):null;for(const[artifactName,expectedSha256]of Object.entries(manifest.runtimeArtifacts??{})){const actualSha256=artifactName==="publicNodeModules"?sha256RuntimeTree(resolve90(manifest.runtimeRoot,"..","public-node_modules")):managedArtifactHashes&&artifactName in managedArtifactHashes?managedArtifactHashes[artifactName]:artifactPaths[artifactName]?sha256RuntimeTree(resolve90(manifest.runtimeRoot,artifactPaths[artifactName])):"";if(actualSha256!==expectedSha256){throw new Error(`runtime generation artifact ${artifactName} hash mismatch: ${manifestHash} expected ${expectedSha256}, got ${actualSha256}`)}}})}function assertManagedRuntimePackageContract(manifest,manifestHash){if(detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path)!=="managed-release"){return}for(const packageName of manifest.requiredPackages??[]){const parts=packageName.split("/");const validName=packageName.startsWith("@")?parts.length===2&&/^@[a-z0-9][a-z0-9._-]*$/.test(parts[0])&&/^[a-z0-9][a-z0-9._-]*$/.test(parts[1]):parts.length===1&&/^[a-z0-9][a-z0-9._-]*$/.test(parts[0]);if(!validName){throw new Error(`runtime generation manifest invalid: required package name: ${manifestHash}`)}const packageJsonPath=resolve90(manifest.runtimeRoot,"node_modules",...packageName.split("/"),"package.json");if(!existsSync36(packageJsonPath)){throw new Error(`runtime generation incomplete: required package ${packageName} missing: ${manifestHash}`)}let parsed;try{parsed=JSON.parse(readFileSync33(packageJsonPath,"utf-8"))}catch{throw new Error(`runtime generation incomplete: required package ${packageName} catalog invalid: ${manifestHash}`)}const version3=typeof parsed.version==="string"?parsed.version:"";if(!version3||manifest.releaseOwnedPackages?.[packageName]!==version3){throw new Error(`runtime generation incomplete: required package ${packageName} catalog mismatch: ${manifestHash}`)}}if(manifest.layoutVersion===3){const publicPackages=manifest.managedDependencyContract?.publicPackages??[];const publicNodeModulesRoot=resolve90(manifest.runtimeRoot,"..","public-node_modules");if(!manifest.managedDependencyContract||publicPackages.length===0){throw new Error(`runtime generation incomplete: managed dependency contract missing: ${manifestHash}`)}if(!existsSync36(publicNodeModulesRoot)){throw new Error(`runtime generation incomplete: public node_modules missing: ${manifestHash}`)}for(const packageName of publicPackages){const releasePackageJsonPath=resolve90(manifest.runtimeRoot,"node_modules",...packageName.split("/"),"package.json");const publicPackageJsonPath=resolve90(publicNodeModulesRoot,...packageName.split("/"),"package.json");if(!existsSync36(releasePackageJsonPath)||!existsSync36(publicPackageJsonPath)){throw new Error(`runtime generation incomplete: public package ${packageName} missing: ${manifestHash}`)}}}}function assertGenerationUsable(manifest,manifestHash,verification2="full",observer){const calculated=deploymentRuntimeManifestHash(manifest);if(calculated!==manifestHash){throw new Error(`runtime generation hash mismatch: expected ${manifestHash}, got ${calculated}`)}if(!existsSync36(manifest.runtimeRoot))throw new Error(`runtime generation root missing: ${manifestHash}`);if(!existsSync36(manifest.serverEntry.path)){throw new Error(`runtime generation server entry missing: ${manifestHash}`)}if(verification2==="full"){assertRuntimeArtifactsMatchManifest(manifest,manifestHash,true,observer);observed(observer,"managed_package_contract",()=>assertManagedRuntimePackageContract(manifest,manifestHash))}const executionSource={kind:"verified-generation",layout:detectRuntimeManifestLayout(manifest.runtimeRoot,manifest.serverEntry.path),layoutVersion:manifest.layoutVersion??1,manifestHash,releaseId:manifest.releaseId||manifestHash,generationRoot:resolve90(manifest.runtimeRoot,".."),runtimeRoot:manifest.runtimeRoot,serverEntry:manifest.serverEntry.path,generationNodeModules:resolve90(manifest.runtimeRoot,"node_modules"),publicNodeModules:manifest.layoutVersion===3?resolve90(manifest.runtimeRoot,"..","public-node_modules"):void 0,runtimeContractPath:resolve90(manifest.runtimeRoot,"..","runtime-manifest.json"),managedDependencyContract:manifest.managedDependencyContract,bunBinary:manifest.binaries.bun?.status==="present"?manifest.binaries.bun.path:void 0,cowboxBinary:manifest.binaries.cowbox?.status==="present"?manifest.binaries.cowbox.path:void 0};return{...executionSource,source:"deployment-manifest"}}function loadPublishedRuntimeGeneration(releaseId,manifestHash,baseDir,runtimeChannel,forceClosureVerification=false){const generationDir=resolveRuntimeGenerationDirectoryPath(baseDir,releaseId);if(!generationDir)return null;const manifestPath=resolve90(generationDir,"runtime-manifest.json");if(!existsSync36(manifestPath))return null;const manifest=readPublishedRuntimeManifest(releaseId,baseDir);assertDeploymentRuntimeManifestSecretFree(manifest);const expectedRoot=resolve90(generationDir,"runtime");if(hasRuntimeContentIdentity(manifest)){if(manifest.releaseId!==releaseId){throw new Error(`runtime generation release identity mismatch: ${releaseId}`)}const expectedReleaseId=runtimeReleaseId(manifestHash,manifest.runtimeClosureSha256);if(expectedReleaseId!==releaseId){throw new Error(`runtime generation content identity mismatch: ${releaseId}`)}}else{assertLegacyIdentityFieldsAreAbsent(manifest,releaseId,manifestHash)}if(resolve90(manifest.runtimeRoot)!==expectedRoot){throw new Error(`runtime generation catalog is not immutable: ${releaseId}`)}assertGenerationUsable(manifest,manifestHash);if(manifest.runtimeClosureSha256){assertRuntimeClosureMatches(manifest,expectedRoot,releaseId,forceClosureVerification)}return buildDeploymentRuntimeRecord(manifest,runtimeChannel)}function writeStagedManifest(path5,manifest){writeFileSync5(path5,`${JSON.stringify(manifest,null,2)}
10156
10156
  `,{mode:420});const fd=openSync2(path5,"r");try{fsyncSync2(fd)}finally{closeSync2(fd)}}function fsyncDirectory(path5){const fd=openSync2(path5,"r");try{fsyncSync2(fd)}finally{closeSync2(fd)}}function persistRuntimeGeneration(record3,baseDir=getRuntimeGenerationsDir(),overrides={}){ensureSafeManifestHash(record3.runtimeManifestHash);const sourceManifest=parseDeploymentRuntimeManifest(record3.runtimeManifestJson);assertGenerationUsable(sourceManifest,record3.runtimeManifestHash);const publishableManifest=prepareRuntimeGenerationManifest(sourceManifest);const releaseId=publishableManifest.releaseId;const published=loadPublishedRuntimeGeneration(releaseId,record3.runtimeManifestHash,baseDir,record3.runtimeChannel,true);if(published)return published;assertRuntimeGenerationCapacityPreflight(baseDir,overrides.capacity);const operations={sealStaged:sealStagedRuntimeGeneration,assertSealed:assertRuntimeGenerationSealed,assertClosure:assertRuntimeClosureMatchesAtRoot,fsyncStaged:fsyncStagedRuntimeGeneration,commitStaged:commitStagedRuntimeGeneration,...overrides};let staged;let publicationStage="staging";try{staged=stageRuntimeGeneration({manifest:publishableManifest,manifestHash:record3.runtimeManifestHash,baseDir});publicationStage="manifest_write";writeStagedManifest(resolve90(staged.stagedGenerationDir,"runtime-manifest.json"),staged.publishedManifest);publicationStage="seal";operations.sealStaged(staged.stagedGenerationDir);publicationStage="sealed_permission_verification";operations.assertSealed(staged.stagedGenerationDir);publicationStage="sealed_closure_verification";operations.assertClosure({runtimeRoot:publishableManifest.layoutVersion===3?staged.stagedGenerationDir:resolve90(staged.stagedGenerationDir,"runtime"),closureSeeds:staged.closureSeeds,expectedClosureSha256:publishableManifest.runtimeClosureSha256});publicationStage="fsync";operations.fsyncStaged(staged.stagedGenerationDir);publicationStage="rename";operations.commitStaged(staged.stagedGenerationDir,staged.finalGenerationDir);publicationStage="parent_fsync";fsyncDirectory(baseDir);publicationStage="final_verification";const committed=loadPublishedRuntimeGeneration(releaseId,record3.runtimeManifestHash,baseDir,record3.runtimeChannel,true);if(!committed)throw new Error(`runtime generation publication failed: ${record3.runtimeManifestHash}`);return committed}catch(error62){if(staged)discardStagedRuntimeGeneration(staged.stagedGenerationDir);throw asRuntimeGenerationPublicationError(error62,publicationStage)}}function resolveRuntimeGenerationRef(params){if(!params.deploymentManifestJson||!params.deploymentManifestHash)return null;const deploymentManifestHash=normalizeRuntimeManifestHash(params.deploymentManifestHash);const deploymentManifest=parseDeploymentRuntimeManifest(params.deploymentManifestJson);assertDeploymentRuntimeManifestSecretFree(deploymentManifest);const deploymentManifestReference=resolveDeploymentRuntimeManifestHashReference(deploymentManifest,deploymentManifestHash);const releaseManifestHash=deploymentManifestReference.usesLegacyReference?deploymentManifestReference.referenceHash:deploymentManifestReference.manifestHash;const releaseId=normalizeRuntimeManifestHash(deploymentManifest.releaseId||deploymentManifestReference.referenceHash);const baseDir=params.baseDir||getRuntimeGenerationsDir();const generationDir=resolveRuntimeGenerationDirectoryPath(baseDir,releaseId);if(!generationDir){throw new Error(`runtime generation missing: ${releaseId}`)}const catalogManifest=readPublishedRuntimeManifest(releaseId,baseDir);assertDeploymentRuntimeManifestSecretFree(catalogManifest);const expectedRoot=resolve90(generationDir,"runtime");if(hasRuntimeContentIdentity(catalogManifest)){if(catalogManifest.releaseId!==releaseId){throw new Error(`runtime generation release identity mismatch: ${releaseId}`)}}else{assertLegacyIdentityFieldsAreAbsent(catalogManifest,releaseId,deploymentManifestHash)}if(resolve90(catalogManifest.runtimeRoot)!==expectedRoot){throw new Error(`runtime generation catalog is not immutable: ${releaseId}`)}const integrity=params.integrity==="sealed"&&hasRuntimeContentIdentity(catalogManifest)?"sealed":"full";if(catalogManifest.runtimeClosureSha256){const expectedReleaseId=runtimeReleaseId(releaseManifestHash,catalogManifest.runtimeClosureSha256);if(expectedReleaseId!==releaseId){throw new Error(`runtime generation content identity mismatch: ${releaseId}`)}if(integrity==="full"){assertRuntimeClosureMatches(catalogManifest,expectedRoot,releaseId)}}const reference={...assertGenerationUsable(catalogManifest,deploymentManifestReference.manifestHash,integrity),source:"catalog"};return integrity==="full"?markRuntimeGenerationFullyVerified(reference):reference}function resolvePublishedRuntimeGenerationRef(params){const observer=createRuntimeGenerationVerificationContext(params.verificationObserver);const catalog=observed(observer,"catalog_manifest_identity",()=>{const releaseId=normalizeRuntimeManifestHash(params.releaseId);const baseDir=params.baseDir||getRuntimeGenerationsDir();const generationDir=resolveRuntimeGenerationDirectoryPath(baseDir,releaseId);if(!generationDir){throw new Error(`runtime generation missing: ${releaseId}`)}const manifestPath=resolve90(generationDir,"runtime-manifest.json");const catalogManifest=parseDeploymentRuntimeManifest(readFileSync33(manifestPath,"utf-8"));assertDeploymentRuntimeManifestSecretFree(catalogManifest);const expectedRoot=resolve90(generationDir,"runtime");const manifestHash=deploymentRuntimeManifestHash(catalogManifest);if(hasRuntimeContentIdentity(catalogManifest)){if(catalogManifest.releaseId!==releaseId){throw new Error(`runtime generation release identity mismatch: ${releaseId}`)}const expectedReleaseId=runtimeReleaseId(manifestHash,catalogManifest.runtimeClosureSha256);if(expectedReleaseId!==releaseId){throw new Error(`runtime generation content identity mismatch: ${releaseId}`)}}else{assertLegacyIdentityFieldsAreAbsent(catalogManifest,releaseId,manifestHash)}if(resolve90(catalogManifest.runtimeRoot)!==expectedRoot){throw new Error(`runtime generation catalog is not immutable: ${releaseId}`)}return{releaseId,catalogManifest,expectedRoot,manifestHash}});const integrity=params.integrity==="sealed"?"sealed":"full";if(catalog.catalogManifest.runtimeClosureSha256&&integrity==="full"){assertRuntimeClosureMatches(catalog.catalogManifest,catalog.expectedRoot,catalog.releaseId,false,observer,params.closureVerificationBackend,params.closureVerificationObserver)}const reference={...assertGenerationUsable(catalog.catalogManifest,catalog.manifestHash,integrity,observer),source:"catalog"};return integrity==="full"?markRuntimeGenerationFullyVerified(reference):reference}var DEFAULT_GENERATIONS_DIR,RuntimeGenerationPublishError,verifiedRuntimeClosures,fullyVerifiedRuntimeReferences;var init_runtime_generation_store=__esm({"../platform/src/runtime-generation-store.ts"(){"use strict";init_deployment_runtime_manifest();init_runtime_generation_publisher();init_runtime_generation_capacity();init_runtime_native_closure_backend();init_runtime_generation_verification_observer();DEFAULT_GENERATIONS_DIR="/opt/gencow/shared/runtime-generations";RuntimeGenerationPublishError=class extends Error{reasonCode="runtime_generation_publish_io_failed";constructor(stage){super(`runtime generation publication I/O failed at ${stage}`);this.name="RuntimeGenerationPublishError"}};verifiedRuntimeClosures=new Set;fullyVerifiedRuntimeReferences=new WeakSet}});import{existsSync as existsSync37}from"fs";import{resolve as resolve91}from"path";function isPublishedRuntimeRootUsable(path5){return existsSync37(resolve91(path5,"..","runtime-manifest.json"))&&existsSync37(resolve91(path5,"server","index.js"))&&existsSync37(resolve91(path5,"core","index.js"))&&existsSync37(resolve91(path5,"node_modules"))}function getAppRuntimeMetadataPath(dataDir){return resolve91(dataDir,APP_RUNTIME_METADATA_RELATIVE_PATH)}function getAppOwnedDepsDir(dataDir){return resolve91(dataDir,APP_OWNED_DEPS_DIRNAME)}function getAppOwnedDepsPackageJsonPath(dataDir){return resolve91(getAppOwnedDepsDir(dataDir),"package.json")}function getAppOwnedNodeModulesPath(dataDir){return resolve91(getAppOwnedDepsDir(dataDir),"node_modules")}function getManagedRuntimeDir(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_DIRNAME)}function getManagedRuntimeGenerationDir(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_GENERATION_RELATIVE_PATH)}function getManagedRuntimeRuntimeDir(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_RUNTIME_RELATIVE_PATH)}function getManagedRuntimeNodeModulesPath(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_NODE_MODULES_RELATIVE_PATH)}function getManagedRuntimeReleaseDir(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_RELEASE_RELATIVE_PATH)}function getManagedRuntimeReleaseManifestPath(dataDir){return resolve91(dataDir,MANAGED_RUNTIME_RELEASE_MANIFEST_RELATIVE_PATH)}function getManagedRuntimeServerEntryPath(dataDir){return resolve91(getManagedRuntimeReleaseDir(dataDir),"server","index.js")}function getManagedRuntimeCoreDir(dataDir){return resolve91(getManagedRuntimeReleaseDir(dataDir),"core")}function getManagedRuntimePublicNodeModulesPath(dataDir){return resolve91(getManagedRuntimeGenerationDir(dataDir),"public-node_modules")}var APP_RUNTIME_METADATA_RELATIVE_PATH,APP_OWNED_DEPS_DIRNAME,MANAGED_RUNTIME_DIRNAME,MANAGED_RUNTIME_GENERATION_DIRNAME,MANAGED_RUNTIME_RUNTIME_DIRNAME,MANAGED_RUNTIME_RELEASE_DIRNAME,MANAGED_RUNTIME_NODE_MODULES_RELATIVE_PATH,MANAGED_RUNTIME_GENERATION_RELATIVE_PATH,MANAGED_RUNTIME_RUNTIME_RELATIVE_PATH,MANAGED_RUNTIME_RELEASE_RELATIVE_PATH,MANAGED_RUNTIME_RELEASE_MANIFEST_RELATIVE_PATH,MANAGED_RUNTIME_NODE_MODULES_MARKER,RUNTIME_RELEASE_LAYOUT_VERSION;var init_provisioner_runtime_paths=__esm({"../platform/src/provisioner-runtime-paths.ts"(){"use strict";APP_RUNTIME_METADATA_RELATIVE_PATH=".gencow-runtime.json";APP_OWNED_DEPS_DIRNAME=".gencow-app-deps";MANAGED_RUNTIME_DIRNAME=".gencow-runtime";MANAGED_RUNTIME_GENERATION_DIRNAME="generation";MANAGED_RUNTIME_RUNTIME_DIRNAME="runtime";MANAGED_RUNTIME_RELEASE_DIRNAME="release";MANAGED_RUNTIME_NODE_MODULES_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/node_modules`;MANAGED_RUNTIME_GENERATION_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/${MANAGED_RUNTIME_GENERATION_DIRNAME}`;MANAGED_RUNTIME_RUNTIME_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/${MANAGED_RUNTIME_RUNTIME_DIRNAME}`;MANAGED_RUNTIME_RELEASE_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/${MANAGED_RUNTIME_RELEASE_DIRNAME}`;MANAGED_RUNTIME_RELEASE_MANIFEST_RELATIVE_PATH=`${MANAGED_RUNTIME_DIRNAME}/runtime-manifest.json`;MANAGED_RUNTIME_NODE_MODULES_MARKER=".gencow-managed-runtime.json";RUNTIME_RELEASE_LAYOUT_VERSION=3}});import{copyFileSync as copyFileSync3,cpSync,existsSync as existsSync38,lstatSync as lstatSync9,mkdirSync as mkdirSync7,mkdtempSync as mkdtempSync6,readFileSync as readFileSync34,readdirSync as readdirSync13,realpathSync as realpathSync7,rmSync as rmSync8,writeFileSync as writeFileSync6}from"fs";import{tmpdir as tmpdir6}from"os";import{dirname as dirname26,relative as relative24,resolve as resolve92}from"path";function getRuntimeCompatibilityResolver(runtimeCompatibility){const resolver=RUNTIME_COMPATIBILITY_RESOLVERS.find(candidate=>candidate.matches(runtimeCompatibility));if(resolver)return resolver;throw new Error(`[runtime-layout] No runtime compatibility resolver for selector: ${runtimeCompatibility}`)}function readManagedRuntimeManifestForApp(dataDir){return readManagedRuntimeManifest(getManagedRuntimeReleaseManifestPath(dataDir))}function readManagedRuntimeManifest(manifestPath){if(!existsSync38(manifestPath))return null;try{return parseDeploymentRuntimeManifest(readFileSync34(manifestPath,"utf-8"))}catch{return null}}function prepareManagedRuntimePointers(dataDir,publishedReleaseDir,manifest){const generationDir=dirname26(publishedReleaseDir);const managedRuntimeDir=getManagedRuntimeDir(dataDir);mkdirSync7(managedRuntimeDir,{recursive:true});symlinkRelativeEntry(generationDir,getManagedRuntimeGenerationDir(dataDir),"dir");symlinkRelativeEntry(publishedReleaseDir,getManagedRuntimeRuntimeDir(dataDir),"dir");symlinkRelativeEntry(publishedReleaseDir,getManagedRuntimeReleaseDir(dataDir),"dir");const manifestPath=getManagedRuntimeReleaseManifestPath(dataDir);rmSync8(manifestPath,{force:true});if(manifest){writeFileSync6(manifestPath,`${JSON.stringify(manifest,null,2)}
10157
10157
  `)}else{copyFileSync3(resolve92(generationDir,"runtime-manifest.json"),manifestPath)}return managedRuntimeDir}function collectPnpmVirtualStoreResolutionRoots2(repoRoot2){const pnpmStoreDir=resolve92(repoRoot2,"node_modules/.pnpm");if(!existsSync38(pnpmStoreDir))return[];const roots=[];for(const entry of readdirSync13(pnpmStoreDir,{withFileTypes:true})){if(!entry.isDirectory()||entry.name.startsWith("."))continue;roots.push(resolve92(pnpmStoreDir,entry.name,"node_modules"))}return roots}function buildResolvedRuntimeReleaseId(repoRoot2){return buildRuntimeReleaseId(repoRoot2,RUNTIME_RELEASE_LAYOUT_VERSION)}function readAppRuntimeMetadata(dataDir){const metadataPath=getAppRuntimeMetadataPath(dataDir);if(!existsSync38(metadataPath))return null;try{const parsed=JSON.parse(readFileSync34(metadataPath,"utf-8"));if(typeof parsed.runtimeCompatibility==="string"&&parsed.runtimeCompatibility.trim()&&typeof parsed.resolvedReleaseId==="string"&&parsed.resolvedReleaseId.trim()){return{runtimeCompatibility:parsed.runtimeCompatibility.trim(),resolvedReleaseId:parsed.resolvedReleaseId.trim()}}}catch{}return null}function resolveAppRuntimeMetadata(dataDir,repoRoot2){const existing=readAppRuntimeMetadata(dataDir);const runtimeCompatibility=existing?.runtimeCompatibility||DEFAULT_RUNTIME_COMPATIBILITY;const resolver=getRuntimeCompatibilityResolver(runtimeCompatibility);return{...resolver.resolve({repoRoot:repoRoot2,runtimeCompatibility}),resolutionStrategy:resolver.strategy,publicationPolicy:resolver.publicationPolicy}}function writeAppRuntimeMetadata(dataDir,metadata){const runtimeDir=getManagedRuntimeDir(dataDir);mkdirSync7(runtimeDir,{recursive:true});const{runtimeCompatibility,resolvedReleaseId}=metadata;writeFileSync6(getAppRuntimeMetadataPath(dataDir),`${JSON.stringify({runtimeCompatibility,resolvedReleaseId},null,2)}