gencow 0.1.275 → 0.1.277

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.
@@ -56,10 +56,14 @@ function isSelectedArchivePath(path) {
56
56
  return CANONICAL_PROJECT_AUTH_PATTERN.test(path) || CANONICAL_LEGACY_AUTH_PATTERN.test(path);
57
57
  }
58
58
 
59
- function findRuntimeEntry(allFiles) {
60
- return [...allFiles].filter((path) => CANONICAL_RUNTIME_ENTRY_PATTERN.test(path)).sort()[0] ?? null;
59
+ // Sorted so the reported files are deterministic regardless of archive entry order.
60
+ function findRuntimeEntries(allFiles) {
61
+ return [...allFiles].filter((path) => CANONICAL_RUNTIME_ENTRY_PATTERN.test(path)).sort();
61
62
  }
62
63
 
64
+ // A static deploy may list only a few entries; the rest are counted, not sent to the user.
65
+ const SERVER_ENTRY_LISTING_LIMIT = 10;
66
+
63
67
  function findAuthSchemaFiles(allFiles, pattern) {
64
68
  return [...allFiles].filter((path) => pattern.test(path)).sort();
65
69
  }
@@ -113,11 +117,16 @@ export async function buildDeployClaimFromArchive({
113
117
  requestId = createDeployRequestId(),
114
118
  }) {
115
119
  const { selected, allFiles } = await selectedArchiveFiles(bundleBuffer);
116
- const runtimeEntry = findRuntimeEntry(allFiles);
117
- if (declaredRuntime === "server" && !runtimeEntry)
120
+ const runtimeEntries = findRuntimeEntries(allFiles);
121
+ if (declaredRuntime === "server" && runtimeEntries.length === 0)
118
122
  throw new Error("Server deploy runtime entry is required");
119
- if (declaredRuntime === "none" && runtimeEntry)
120
- throw new Error("Static deploy contains a server runtime entry");
123
+ if (declaredRuntime === "none" && runtimeEntries.length > 0) {
124
+ const error = new Error("Static deploy contains a server runtime entry");
125
+ error.code = "STATIC_DEPLOY_SERVER_ENTRY_PRESENT";
126
+ error.files = runtimeEntries.slice(0, SERVER_ENTRY_LISTING_LIMIT);
127
+ error.totalFiles = runtimeEntries.length;
128
+ throw error;
129
+ }
121
130
 
122
131
  const lockfiles = [...LOCKFILES].filter(([path]) => selected.has(path));
123
132
  const unsupportedLockfiles = UNSUPPORTED_DEPLOY_LOCKFILES.filter((path) => selected.has(path));
@@ -342,9 +342,10 @@ export function renderMigrationDiagnosticLines(diagnostic) {
342
342
  lines.push(`Correlation: ${diagnostic.correlationId}`);
343
343
  return lines.map((line) => escapeTerminalControls(line));
344
344
  }
345
- // Without a verified local span, the server's "exact statement" wording would overclaim.
345
+ // Without a verified statement span, the server's "exact statement" wording would overclaim. A verified
346
+ // file without a statement index is still unlocated; its path is shown once, in the location line.
346
347
  const unlocatedRollback =
347
- isUserFixableRolledBackDiagnostic(diagnostic) && !diagnostic.localSource?.projectRelativePath;
348
+ isUserFixableRolledBackDiagnostic(diagnostic) && !diagnostic.localSource?.statementIndex;
348
349
  const retryCondition = unlocatedRollback
349
350
  ? UNLOCATED_ROLLBACK_RETRY_CONDITION
350
351
  : diagnostic.retryCondition;
@@ -358,7 +359,7 @@ export function renderMigrationDiagnosticLines(diagnostic) {
358
359
  `Retry policy: ${diagnostic.retryPolicy}${retryCondition ? ` — ${retryCondition}` : ""}`,
359
360
  ];
360
361
  const source = diagnostic.localSource;
361
- if (source?.projectRelativePath) {
362
+ if (source?.projectRelativePath && !unlocatedRollback) {
362
363
  lines.push("", `File: ${source.projectRelativePath}`);
363
364
  if (source.statementIndex) {
364
365
  const span = source.lineStart
@@ -367,13 +368,10 @@ export function renderMigrationDiagnosticLines(diagnostic) {
367
368
  lines.push(`Statement: ${source.statementIndex}${span}`);
368
369
  }
369
370
  if (source.excerpt) lines.push("Local SQL context (literals redacted):", source.excerpt);
370
- } else if (diagnostic.migration?.name) {
371
+ } else if (!source?.projectRelativePath && diagnostic.migration?.name) {
371
372
  lines.push("", `Migration: ${diagnostic.migration.name}`);
372
373
  }
373
- if (unlocatedRollback) {
374
- if (diagnostic.migration?.name) lines.push(renderUnlocatedRollbackLocation(diagnostic));
375
- else lines.push("", renderUnlocatedRollbackLocation(diagnostic));
376
- }
374
+ if (unlocatedRollback) lines.push("", renderUnlocatedRollbackLocation(diagnostic));
377
375
  if (diagnostic.operation?.kind) {
378
376
  lines.push(
379
377
  `Operation: ${diagnostic.operation.kind}${diagnostic.operation.objectName ? ` ${diagnostic.operation.objectName}` : ""}`,
@@ -30,34 +30,42 @@ const NOT_NULL_REPAIR_HINT =
30
30
  "For a NOT NULL failure, give the new column a DEFAULT or make it nullable, or split the change into forward migrations (expand → backfill → contract).";
31
31
 
32
32
  // Type/data repair hints for the unlocated fallback. Mirrors the server's suggested-fix text in
33
- // migration-rollback-diagnostic.ts; both must name only the column DEFAULT or literal in schema.ts.
34
- const TYPE_REPAIR_HINTS = new Map([
33
+ // migration-rollback-diagnostic.ts (SHARED_REPAIR_PATH and USER_REASON_CAUSES); the driver-chain test
34
+ // asserts the two stay equal. Static text only.
35
+ const SHARED_REPAIR_PATH =
36
+ 'Correct the cause in gencow/schema.ts first, because db:generate rebuilds an unapplied folder from that file. Then run `gencow db:check --inspect-state` (for a PROD target add `--prod --app <id>`). If it lists pending folders under "Pending migrations that may be regenerated", back up or commit the project, remove every folder it lists, and run `gencow db:generate`. If it lists nothing, correct the failing statement in its unapplied migration file in place. Then run `gencow db:check` and `gencow db:push`. Applied migrations and the Drizzle journal are never changed.';
37
+
38
+ const TYPE_REASON_CAUSES = new Map([
35
39
  [
36
40
  "invalid_text_representation",
37
- "For a value that does not match its column type, change the column DEFAULT or inserted literal in gencow/schema.ts to a value valid for the declared type (for example, a whole number for an integer column), then run db:generate to replace only this unapplied migration.",
41
+ "A value does not match its column type: use a value valid for the declared type (for example, a whole number for an integer column) in the DEFAULT or inserted literal.",
38
42
  ],
39
43
  [
40
44
  "string_data_right_truncation",
41
- "For a value longer than its column allows, shorten the literal or change the column length in gencow/schema.ts, then run db:generate to replace only this unapplied migration.",
45
+ "A value is longer than its column allows: shorten the literal or change the column length.",
42
46
  ],
43
47
  [
44
48
  "feature_not_supported_in_statement",
45
- "For a DEFAULT PostgreSQL does not accept (a bare word, a subquery, or a column reference), change the DEFAULT in gencow/schema.ts to a literal valid for the column type: a quoted string for text columns, a number for integer columns, true or false for boolean columns. Then run db:generate to replace only this unapplied migration.",
49
+ "A DEFAULT PostgreSQL does not accept (a bare word, a subquery, or a column reference): use a literal valid for the column type (a quoted string for text, a number for integer, true or false for boolean).",
46
50
  ],
47
51
  [
48
52
  "datatype_mismatch",
49
- "For a DEFAULT whose value type does not match its column, change the DEFAULT in gencow/schema.ts to a value of the column's declared type, then run db:generate to replace only this unapplied migration.",
53
+ "A DEFAULT value type does not match its column: use a value of the column's declared type.",
50
54
  ],
51
55
  [
52
56
  "undefined_function",
53
- "The statement calls a function that does not exist in this database. Correct the function name or remove it from the DEFAULT in gencow/schema.ts, then run db:generate to replace only this unapplied migration.",
57
+ "The statement calls a function that does not exist in this database: correct the function name or remove it from the DEFAULT.",
54
58
  ],
55
59
  [
56
60
  "undefined_object",
57
- "The statement uses a type name that does not exist in this database. Correct the column type in gencow/schema.ts, then run db:generate to replace only this unapplied migration.",
61
+ "The statement uses a type name that does not exist in this database: correct the column type.",
58
62
  ],
59
63
  ]);
60
64
 
65
+ const TYPE_REPAIR_HINTS = new Map(
66
+ [...TYPE_REASON_CAUSES].map(([reason, cause]) => [reason, `${cause} ${SHARED_REPAIR_PATH}`]),
67
+ );
68
+
61
69
  const SAFE_REASON_CODE = /^[a-z0-9_]{1,80}$/u;
62
70
 
63
71
  export function isUserFixableRolledBackDiagnostic(diagnostic) {
@@ -84,24 +92,36 @@ export function renderRollbackCauseLine(diagnostic) {
84
92
 
85
93
  // Honest replacement for the server's "exact statement" wording when the CLI could not
86
94
  // verify a local source span. Only the already-safe migration name is shown.
95
+ // The file to inspect: the verified project-relative path when the CLI could check it, otherwise the
96
+ // migration folder name. Never raw SQL.
97
+ export function unappliedMigrationLabel(diagnostic) {
98
+ return diagnostic?.localSource?.projectRelativePath ?? diagnostic?.migration?.name ?? null;
99
+ }
100
+
101
+ const PENDING_LIST_COMMAND = "gencow db:check --inspect-state";
102
+
87
103
  export function renderUnlocatedRollbackFix(diagnostic) {
88
- const name = diagnostic?.migration?.name;
104
+ const label = unappliedMigrationLabel(diagnostic);
89
105
  const code = safeRollbackReasonCode(diagnostic);
90
106
  const typeHint = code ? TYPE_REPAIR_HINTS.get(code) : undefined;
91
- const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : typeHint ? ` ${typeHint}` : "";
107
+ const detail =
108
+ code === "not_null_violation"
109
+ ? `Repair only the unapplied migration source for the cause above, review the generated diff, and create a fresh plan. Applied migrations and the journal are not edited. ${NOT_NULL_REPAIR_HINT}`
110
+ : (typeHint ??
111
+ "Repair only the unapplied migration source for the cause above, review the generated diff, and create a fresh plan. Applied migrations and the journal are not edited.");
92
112
  return {
93
- title: name
94
- ? `Inspect the unapplied migration file ${name}`
95
- : "Inspect the pending migrations listed by db:check",
96
- detail: `Repair only the unapplied migration source for the cause above, review the generated diff, and create a fresh plan. Applied migrations and the journal are not edited.${hint}`,
113
+ title: label
114
+ ? `Inspect the unapplied migration file ${label}`
115
+ : `Inspect the pending migrations listed by ${PENDING_LIST_COMMAND}`,
116
+ detail,
97
117
  };
98
118
  }
99
119
 
100
120
  export function renderUnlocatedRollbackLocation(diagnostic) {
101
- const name = diagnostic?.migration?.name;
102
- return name
103
- ? `Statement location: unavailable — inspect the unapplied migration file ${name}`
104
- : "Statement location: unavailable — inspect the pending migrations listed by db:check";
121
+ const label = unappliedMigrationLabel(diagnostic);
122
+ return label
123
+ ? `Statement location: unavailable — inspect the unapplied migration file ${label}`
124
+ : `Statement location: unavailable — inspect the pending migrations listed by ${PENDING_LIST_COMMAND}`;
105
125
  }
106
126
 
107
127
  export const UNLOCATED_ROLLBACK_SUMMARY =
@@ -8,7 +8,7 @@ import {
8
8
  unlinkSync,
9
9
  writeFileSync,
10
10
  } from "fs";
11
- import { relative, resolve } from "path";
11
+ import { isAbsolute, relative, resolve } from "path";
12
12
  import { BOLD, CYAN, DIM, RESET, YELLOW, error, info, log, success, warn } from "./output.mjs";
13
13
  import { resolveCreatedAppResponse } from "./app-create-response.mjs";
14
14
  import { readJsonObjectResponse } from "./http-response-json.mjs";
@@ -176,6 +176,30 @@ function localPackagingNextAction(causeCode, retryPhrase) {
176
176
  return `${fix}, then ${retryPhrase}.`;
177
177
  }
178
178
 
179
+ const SERVER_ENTRY_CODE = "STATIC_DEPLOY_SERVER_ENTRY_PRESENT";
180
+
181
+ // Paths are archive-relative; the static directory argument is prefixed only when the user gave a
182
+ // relative one, so no absolute local path is ever printed.
183
+ function serverEntryDiagnosticLines({ caught, targetDir, localStateLine, backendAlreadyDeployed, envTarget }) {
184
+ const files = (caught.files ?? []).filter((file) => typeof file === "string");
185
+ const prefix = targetDir && !isAbsolute(targetDir) ? `${targetDir.replace(/[\\/]+$/, "")}/` : "";
186
+ const shown = files.map((file) => `${prefix}${file}`).join(", ");
187
+ const hidden = Number.isInteger(caught.totalFiles) ? caught.totalFiles - files.length : 0;
188
+ const more = hidden > 0 ? ` (+${hidden} more)` : "";
189
+ const prodFlag = envTarget === "prod" ? " --prod" : "";
190
+ const backendNote = backendAlreadyDeployed
191
+ ? "the backend is already deployed, so only the static step needs retrying; "
192
+ : "";
193
+ return [
194
+ "Static deploy stopped before the deployment request was sent: the static directory contains a server runtime entry.",
195
+ `Code: ${SERVER_ENTRY_CODE}`,
196
+ "Stage: package",
197
+ localStateLine,
198
+ `Files: ${shown}${more}`,
199
+ `Next: ${backendNote}move the server code (gencow/) out of the static directory so it holds only static output, then run \`gencow static${prodFlag} <static-output-dir>\` from this app directory. Pass the build output directory (for example \`dist\`), not the project root (\`.\`). Retry only after that directory has no gencow/index.ts or gencow/index.js.`,
200
+ ];
201
+ }
202
+
179
203
  export function createStaticDeployRuntime({
180
204
  buildDeployClaimFromArchiveImpl = buildDeployClaimFromArchive,
181
205
  cliVersion = "0.0.0",
@@ -489,14 +513,28 @@ export function createStaticDeployRuntime({
489
513
  ...(opts.requestId ? { requestId: opts.requestId } : {}),
490
514
  });
491
515
  } catch (caught) {
492
- await markAttemptFailed("package", "DEPLOY_CONTRACT_FAILED");
516
+ // The typed server-entry failure follows the backend-owned attempt rule (see markLocalFailure).
517
+ if (caught?.code === SERVER_ENTRY_CODE) await markLocalFailure("package", "DEPLOY_CONTRACT_FAILED");
518
+ else await markAttemptFailed("package", "DEPLOY_CONTRACT_FAILED");
493
519
  await localWindow.holdIfInterrupted();
494
520
  try {
495
521
  unlinkSyncImpl(tmpBundle);
496
522
  } catch {
497
523
  /* ignore */
498
524
  }
499
- errorImpl(`Deploy contract generation failed: ${caught.message}`);
525
+ if (caught?.code === SERVER_ENTRY_CODE) {
526
+ const lines = serverEntryDiagnosticLines({
527
+ caught,
528
+ targetDir,
529
+ localStateLine,
530
+ backendAlreadyDeployed,
531
+ envTarget: opts.envTarget,
532
+ });
533
+ errorImpl(lines[0]);
534
+ for (const line of lines.slice(1)) infoImpl(line);
535
+ } else {
536
+ errorImpl(`Deploy contract generation failed: ${caught.message}`);
537
+ }
500
538
  exitLocally(1);
501
539
  return;
502
540
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gencow",
3
- "version": "0.1.275",
3
+ "version": "0.1.277",
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/client": "0.2.8",
44
- "@gencow/react": "0.2.8",
45
43
  "@gencow/core": "0.1.47",
44
+ "@gencow/shared": "0.0.0",
46
45
  "@gencow/server": "0.1.3",
47
- "@gencow/shared": "0.0.0"
46
+ "@gencow/client": "0.2.8",
47
+ "@gencow/react": "0.2.8"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "node scripts/bundle-core.mjs && node scripts/bundle-shared.mjs && node scripts/bundle-server.mjs",
@@ -8980,7 +8980,7 @@ ${argsDigest}`;const signature=sign3(null,Buffer.from(payload),scheduledJobDeliv
8980
8980
  AND attribute.attnum > 0
8981
8981
  AND NOT attribute.attisdropped
8982
8982
  ORDER BY attribute.attnum
8983
- `):[];const database=databaseRows[0]??{};const schema=schemaRows[0]??{};const journalSecurity=journalSecurityRows[0]??{};const drizzleSchemaExists=schemaRows.length>0;return{databaseCanConnect:toBoolean(database.database_can_connect),databaseCanCreate:toBoolean(database.database_can_create),publicSchemaUsage:toBoolean(database.public_usage),publicSchemaCreate:toBoolean(database.public_create),drizzleSchemaExists,drizzleSchemaOwner:drizzleSchemaExists?toNullableString(schema.owner):null,drizzleSchemaOwnedByDatabaseOwner:drizzleSchemaExists?toBoolean(schema.owned_by_database_owner):false,drizzleSchemaUsage:drizzleSchemaExists?toBoolean(schema.drizzle_usage):false,drizzleSchemaCreate:drizzleSchemaExists?toBoolean(schema.drizzle_create):false,journalTableExists:toBoolean(journalRows[0]?.journal_exists),journalTableOwner:toNullableString(journalSecurity.owner),journalTableOwnedByDatabaseOwner:toBoolean(journalSecurity.owned_by_database_owner),journalColumns:columnRows.map(row=>toNullableString(row.column_name)).filter(isString),journalCanSelect:toBoolean(journalSecurity.can_select),journalCanInsert:toBoolean(journalSecurity.can_insert),journalCanUpdate:toBoolean(journalSecurity.can_update),journalCanDelete:toBoolean(journalSecurity.can_delete),journalCanTruncate:toBoolean(journalSecurity.can_truncate),journalPlanGuardInstalled:toBoolean(journalSecurity.guard_installed)}}async function assertDrizzleMigrationStoreReadyForPrimaryMigrate(params){const snapshot=await collectDrizzleMigrationStoreSnapshot(params.sql,{roleName:params.roleName});const state2=classifyDrizzleMigrationStoreState(snapshot,params.roleName);if(isDrizzleMigrationStoreStateAllowedForPrimaryMigrate(state2)){return snapshot}const code=getDrizzleMigrationStorePreflightErrorCode(state2)??"DB_MIGRATION_STORE_UNSAFE";throw new DrizzleMigrationStorePreflightError({appName:params.appName,state:state2,code})}function hasCompatibleJournalShape(columns){const present=new Set(columns);for(const required3 of REQUIRED_JOURNAL_COLUMNS){if(!present.has(required3))return false}return true}function toBoolean(value2){return value2===true||value2==="true"||value2===1||value2==="1"}function toNullableString(value2){return typeof value2==="string"&&value2.length>0?value2:null}function isString(value2){return typeof value2==="string"}var REQUIRED_JOURNAL_COLUMNS,DrizzleMigrationStorePreflightError;var init_drizzle_migration_store=__esm({"../platform/src/drizzle-migration-store.ts"(){"use strict";REQUIRED_JOURNAL_COLUMNS=new Set(["id","hash","created_at","name"]);DrizzleMigrationStorePreflightError=class extends Error{code;state;constructor(params){super(`${params.code}: ${params.appName} migration store state=${params.state}; run the Drizzle migration store reconciler before deploy.`);this.name="DrizzleMigrationStorePreflightError";this.code=params.code;this.state=params.state}}}});import{createHash as createHash50}from"node:crypto";import{getMigrationsToRun}from"drizzle-orm/migrator.utils";function fingerprint3(value2){return createHash50("sha256").update(JSON.stringify(value2)).digest("hex")}function localFingerprint(migrations){return fingerprint3(migrations.map(migration=>[migration.name,migration.hash,migration.folderMillis,migration.bps]))}function journalFingerprint(rows8){return fingerprint3([...rows8].sort((left,right)=>left.id-right.id).map(row=>[row.id,row.name,row.hash,row.createdAt]))}function safeMigrationName(name){return JSON.stringify(name)}function indexLocalMigrations(migrations){const byName=new Map;for(const migration of migrations){if(!migration.name||byName.has(migration.name)){throw new MigrationExecutionPlanError("MIGRATION_LOCAL_HISTORY_AMBIGUOUS",migration.name?`duplicate local migration name ${safeMigrationName(migration.name)}`:"a local migration has no stable name",{migrationName:migration.name||void 0,migrationHash:migration.hash})}byName.set(migration.name,migration)}return byName}function indexJournalRows(rows8){const byName=new Map;for(const row of rows8){if(!row.name){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HISTORY_AMBIGUOUS","the Drizzle journal contains an applied row without a stable migration name")}if(byName.has(row.name)){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HISTORY_AMBIGUOUS",`the Drizzle journal contains duplicate migration name ${safeMigrationName(row.name)}`)}byName.set(row.name,row)}return byName}function buildMigrationExecutionPlan(input2){const localMigrations=[...input2.localMigrations];const journalRows=[...input2.journalRows];const localByName=indexLocalMigrations(localMigrations);const journalByName=indexJournalRows(journalRows);for(const[name,row]of journalByName){const local=localByName.get(name);if(!local){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_FILE_MISSING",`applied migration ${safeMigrationName(name)} is absent from the deployment bundle`,{migrationName:name,migrationHash:row.hash})}if(local.hash!==row.hash){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HASH_DRIFT",`applied migration ${safeMigrationName(name)} no longer matches its immutable local file`,{migrationName:name,migrationHash:local.hash})}}const pending=getMigrationsToRun({localMigrations,dbMigrations:journalRows.map(row=>({id:row.id,hash:row.hash,created_at:row.createdAt,name:row.name}))});const pendingNames=new Set(pending.map(migration=>migration.name));const appliedVerified=localMigrations.filter(migration=>!pendingNames.has(migration.name));return{appliedVerified,pending,localFingerprint:localFingerprint(localMigrations),journalFingerprint:journalFingerprint(journalRows),planId:`mig_${fingerprint3([localFingerprint(localMigrations),journalFingerprint(journalRows)]).slice(0,24)}`}}function assertMigrationExecutionPlanUnchanged(planned,current){if(localFingerprint(current.localMigrations)!==planned.localFingerprint||journalFingerprint(current.journalRows)!==planned.journalFingerprint){throw new MigrationExecutionPlanError("MIGRATION_PLAN_CHANGED","local migration files or the database journal changed after audit; retry from a fresh plan",{planId:planned.planId})}}function assertMigrationExecutionPostcondition(planned,current){let isSatisfied=localFingerprint(current.localMigrations)===planned.localFingerprint;if(isSatisfied){try{isSatisfied=buildMigrationExecutionPlan(current).pending.length===0}catch{isSatisfied=false}}if(!isSatisfied){throw new MigrationExecutionPlanError("MIGRATION_POSTCONDITION_FAILED","not every audited migration was recorded with its exact immutable hash",{planId:planned.planId})}}var MigrationExecutionPlanError;var init_migration_execution_plan=__esm({"../platform/src/migration-execution-plan.ts"(){"use strict";MigrationExecutionPlanError=class extends Error{code;migrationName;migrationHash;planId;constructor(code,detail,metadata={}){super(`${code}: ${detail}`);this.name="MigrationExecutionPlanError";this.code=code;this.migrationName=metadata.migrationName;this.migrationHash=metadata.migrationHash;this.planId=metadata.planId}}}});function isWordStart(char){return!!char&&/[A-Za-z_\u0080-\uFFFF]/u.test(char)}function isWordPart(char){return!!char&&/[A-Za-z0-9_$\u0080-\uFFFF]/u.test(char)}function readQuotedToken(sql217,start2,quote2,options={}){let index27=start2+1;while(index27<sql217.length){if(options.backslashEscapes&&sql217[index27]==="\\"&&index27+1<sql217.length){index27+=2;continue}if(sql217[index27]!==quote2){index27+=1;continue}if(sql217[index27+1]===quote2){index27+=2;continue}const end=index27+1;const tokenStart=options.tokenStart??start2;const raw2=sql217.slice(tokenStart,end);const quotedValue=sql217.slice(start2+1,index27);return{token:{kind:quote2==="'"?"string":"identifier",value:quote2==="'"?options.backslashEscapes?quotedValue.replace(/''/g,"'").replace(/\\(.)/gsu,"$1"):quotedValue.replace(/''/g,"'"):quotedValue.replace(/""/g,'"'),raw:raw2,start:tokenStart,end},next:end}}return{next:sql217.length,error:quote2==="'"?"unterminated SQL string":"unterminated identifier"}}function readDollarString(sql217,start2){const opener=sql217.slice(start2).match(/^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/)?.[0];if(!opener)return null;const closeIndex=sql217.indexOf(opener,start2+opener.length);if(closeIndex<0)return{next:sql217.length,error:"unterminated dollar-quoted SQL body"};const end=closeIndex+opener.length;const raw2=sql217.slice(start2,end);return{token:{kind:"dollar-string",value:raw2.slice(opener.length,-opener.length),raw:raw2,start:start2,end},next:end}}function skipBlockComment(sql217,start2){let depth=1;let index27=start2+2;while(index27<sql217.length){if(sql217.startsWith("/*",index27)){depth+=1;index27+=2;continue}if(sql217.startsWith("*/",index27)){depth-=1;index27+=2;if(depth===0)return{next:index27};continue}index27+=1}return{next:sql217.length,error:"unterminated SQL block comment"}}function buildStatement(sql217,tokens,end){if(tokens.length===0)return null;return{text:sql217.slice(tokens[0].start,tokens[tokens.length-1].end).trim(),tokens,start:tokens[0].start,end}}function lexSqlStatements(sql217){const statements=[];let statementTokens=[];let index27=0;while(index27<sql217.length){const char=sql217[index27];if(/\s/u.test(char)){index27+=1;continue}if(sql217.startsWith("--",index27)){const newline=sql217.indexOf("\n",index27+2);index27=newline<0?sql217.length:newline+1;continue}if(sql217.startsWith("/*",index27)){const block=skipBlockComment(sql217,index27);if(block.error)return{statements,error:block.error};index27=block.next;continue}if((char==="E"||char==="e")&&sql217[index27+1]==="'"){const quoted=readQuotedToken(sql217,index27+1,"'",{tokenStart:index27,backslashEscapes:true});if(quoted.error||!quoted.token){return{statements,error:quoted.error??"invalid escape string"}}statementTokens.push(quoted.token);index27=quoted.next;continue}if(char==="'"||char==='"'){const quoted=readQuotedToken(sql217,index27,char);if(quoted.error||!quoted.token)return{statements,error:quoted.error??"invalid quoted token"};statementTokens.push(quoted.token);index27=quoted.next;continue}if(char==="$"){const dollar=readDollarString(sql217,index27);if(dollar){if(dollar.error||!dollar.token)return{statements,error:dollar.error??"invalid dollar string"};statementTokens.push(dollar.token);index27=dollar.next;continue}}if(isWordStart(char)){let end=index27+1;while(isWordPart(sql217[end]))end+=1;const raw2=sql217.slice(index27,end);statementTokens.push({kind:"word",value:raw2.toLowerCase(),raw:raw2,start:index27,end});index27=end;continue}if(char===";"){const statement=buildStatement(sql217,statementTokens,index27+1);if(statement)statements.push(statement);statementTokens=[];index27+=1;continue}statementTokens.push({kind:"symbol",value:char,raw:char,start:index27,end:index27+1});index27+=1}const tail=buildStatement(sql217,statementTokens,statementTokens.at(-1)?.end??sql217.length);if(tail)statements.push(tail);return{statements}}function createSqlLineNumberResolver(sql217){const lineStarts=[0];for(let offset=0;offset<sql217.length;offset+=1){if(sql217[offset]==="\n")lineStarts.push(offset+1)}return offset=>{let low=0;let high=lineStarts.length;while(low<high){const middle=Math.floor((low+high)/2);if(lineStarts[middle]<=offset)low=middle+1;else high=middle}return low}}var init_migration_sql_lexer=__esm({"../platform/src/migration-sql-lexer.ts"(){"use strict"}});async function readMigrationPostExecutionSnapshot(params){let lastError;for(const delayMs of POST_EXECUTION_READ_RETRY_DELAYS_MS){if(delayMs>0)await Bun.sleep(delayMs);try{return{local:await params.readLocal(),journal:await params.readJournal()}}catch(error62){lastError=error62}}throw lastError}function safeObjectField(value2,key2){try{return value2[key2]}catch{return void 0}}function collectFailureFacts(error62){const sqlStates=new Set;const errorCodes=new Set;const queries=new Set;const visited=new Set;const pending=[error62];let extensionUnavailable=false;for(let inspected=0;inspected<64&&pending.length>0;inspected+=1){const current=pending.shift();if(!current||typeof current!=="object")continue;if(visited.has(current))continue;visited.add(current);const ownSqlStates=[];for(const key2 of["code","errno"]){const value2=safeObjectField(current,key2);if(typeof value2==="string"&&/^[a-zA-Z0-9_:-]{1,80}$/u.test(value2)){errorCodes.add(value2);if(/^(?=.*[0-9])[0-9A-Z]{5}$/u.test(value2)){sqlStates.add(value2);ownSqlStates.push(value2)}}}if(ownSqlStates.includes("0A000")){const message=safeObjectField(current,"message");if(typeof message==="string"&&EXTENSION_UNAVAILABLE_MESSAGE.test(message.slice(0,EXTENSION_MESSAGE_MAX_LENGTH))){extensionUnavailable=true}}const query2=safeObjectField(current,"query");if(typeof query2==="string")queries.add(query2);const cause=safeObjectField(current,"cause");if(cause&&typeof cause==="object")pending.push(cause);const errors=safeObjectField(current,"errors");if(Array.isArray(errors)){pending.push(...errors.slice(0,16))}}return{sqlStates:[...sqlStates],errorCodes:[...errorCodes],queries:[...queries],extensionUnavailable}}function isExactPostgresSqlStateFailure(error62,sqlState){if(!/^[0-9A-Z]{5}$/u.test(sqlState))return false;const sqlStates=collectFailureFacts(error62).sqlStates;return sqlStates.length>0&&sqlStates.every(observed2=>observed2===sqlState)}function canonicalStatement(statement){return statement.trim().replace(/;\s*$/u,"").trim()}function statementLocation(source,statement,statementIndex){const lexed=lexSqlStatements(source.sqlContent);if(lexed.error)return void 0;const canonical=canonicalStatement(statement);const matches=lexed.statements.filter(candidate=>canonicalStatement(candidate.text)===canonical);if(matches.length!==1)return void 0;const[match2]=matches;const lineAt=createSqlLineNumberResolver(source.sqlContent);return{name:source.metadata.name,sqlSha256:source.metadata.hash,statementIndex,lineStart:lineAt(match2.start),lineEnd:lineAt(Math.max(match2.end-1,match2.start))}}function findExactFailureLocation(queries,pendingSources){const querySet=new Set(queries);const matches=[];for(const source of pendingSources){for(const[index27,statement]of source.metadata.sql.entries()){if(!querySet.has(statement))continue;const location=statementLocation(source,statement,index27+1);if(location)matches.push(location)}}return matches.length===1?matches[0]:void 0}function retryableReason(sqlStates){for(const state2 of sqlStates){const exact=RETRYABLE_SQLSTATES.get(state2);if(exact)return exact;if(state2.startsWith("08"))return"database_connection_lost"}return void 0}function userReason(sqlStates){for(const state2 of sqlStates){const exact=USER_SQLSTATE_REASONS.get(state2);if(exact)return exact;if(/^(22|23|42)/u.test(state2)||state2==="P0001"){return`postgres_sqlstate_${state2.toLowerCase()}`}}return void 0}function platformReason(facts){for(const state2 of facts.sqlStates){if(state2==="0A000"){if(facts.extensionUnavailable)return EXTENSION_UNAVAILABLE_REASON;continue}const exact=PLATFORM_SQLSTATE_REASONS.get(state2);if(exact)return exact}return void 0}function buildMigrationTransactionRolledBackError(params){const facts=collectFailureFacts(params.cause);const platformFailure=platformReason(facts);if(platformFailure){return new MigrationTransactionRolledBackError({failureClass:"PLATFORM_ACTION_REQUIRED",reasonCode:platformFailure,planId:params.planId})}const transient=retryableReason(facts.sqlStates);if(transient){return new MigrationTransactionRolledBackError({failureClass:"RETRYABLE_INFRA",reasonCode:transient,planId:params.planId})}const migration=findExactFailureLocation(facts.queries,params.pendingSources);const userFailure=userReason(facts.sqlStates);if(userFailure){return new MigrationTransactionRolledBackError({failureClass:"USER_FIXABLE",reasonCode:userFailure,planId:params.planId,...migration?{migration}:{}})}if(facts.sqlStates.length===0){console.warn(`[migration] execution failure had no PostgreSQL SQLSTATE in the redacted cause chain codes=${facts.errorCodes.join(",")||"none"}`)}return new MigrationTransactionRolledBackError({failureClass:"UNCLASSIFIED",reasonCode:"execution_failure_unclassified",planId:params.planId})}var RETRYABLE_SQLSTATES,USER_SQLSTATE_REASONS,EXTENSION_UNAVAILABLE_REASON,EXTENSION_UNAVAILABLE_MESSAGE,EXTENSION_MESSAGE_MAX_LENGTH,PLATFORM_SQLSTATE_REASONS,POST_EXECUTION_READ_RETRY_DELAYS_MS,MigrationTransactionRolledBackError;var init_migration_execution_outcome=__esm({"../platform/src/migration-execution-outcome.ts"(){"use strict";init_migration_sql_lexer();RETRYABLE_SQLSTATES=new Map([["40001","serialization_failure"],["40P01","deadlock_detected"],["55P03","lock_not_available"],["57014","statement_timeout_or_cancelled"],["53300","too_many_connections"],["53400","configuration_limit_exceeded"],["57P01","database_admin_shutdown"],["57P02","database_crash_shutdown"],["57P03","database_starting_up"]]);USER_SQLSTATE_REASONS=new Map([["22001","string_data_right_truncation"],["22P02","invalid_text_representation"],["25001","active_sql_transaction"],["23502","not_null_violation"],["23503","foreign_key_violation"],["23505","unique_violation"],["42601","syntax_error"],["42701","duplicate_column"],["42703","undefined_column"],["42704","undefined_object"],["42804","datatype_mismatch"],["42883","undefined_function"],["42P01","undefined_table"],["42P07","duplicate_table"],["0A000","feature_not_supported_in_statement"]]);EXTENSION_UNAVAILABLE_REASON="feature_not_supported";EXTENSION_UNAVAILABLE_MESSAGE=/extension\s+\S.*?\s+is not (?:available|allowed)/iu;EXTENSION_MESSAGE_MAX_LENGTH=512;PLATFORM_SQLSTATE_REASONS=new Map([["42501","insufficient_privilege"],["28000","invalid_authorization_specification"],["28P01","invalid_password"]]);POST_EXECUTION_READ_RETRY_DELAYS_MS=[0,25,100,250];MigrationTransactionRolledBackError=class extends Error{code="MIGRATION_TRANSACTION_ROLLED_BACK";failureClass;reasonCode;planId;migration;constructor(params){super("MIGRATION_TRANSACTION_ROLLED_BACK: the PostgreSQL transaction was rolled back");this.name="MigrationTransactionRolledBackError";this.failureClass=params.failureClass;this.reasonCode=params.reasonCode;this.planId=params.planId;this.migration=params.migration}}}});function base(error62,correlationId){return{code:error62.code,phase:"EXECUTE",databaseState:"ROLLED_BACK",correlationId}}function buildRolledBackDiagnostic(params){const{error:error62,correlationId,migration}=params;if(error62.failureClass==="RETRYABLE_INFRA"){return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryCondition:"Retry the same immutable bundle after the temporary PostgreSQL condition clears.",retryAfterSeconds:5,reason:{code:error62.reasonCode,summary:"The migration transaction was rolled back after a temporary database failure.",detail:"PostgreSQL confirmed that the transaction and its journal writes did not commit. No source edit is recommended."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}if(error62.failureClass==="USER_FIXABLE"){const hasExactLocation=migration!==void 0;const repairHint=USER_REASON_REPAIR_HINTS.get(error62.reasonCode);const suggestedFixes=[{id:"repair-pending-migration",title:hasExactLocation?"Repair the exact unapplied migration statement":"Inspect the pending migration candidates",detail:[hasExactLocation?"Update the schema source or this unapplied statement, review the generated diff, and create a fresh immutable plan.":"Run db:check to list the pending migrations, locate the statement matching this PostgreSQL reason, then update only unapplied source and create a fresh plan.",repairHint].filter(Boolean).join(" "),target:"PENDING_MIGRATION",confidence:hasExactLocation?"HIGH":"MEDIUM"}];return userFixableDiagnostic({...base(error62,correlationId),retryCondition:"Fix only the exact unapplied statement, then create and check a fresh plan.",...migration?{migration}:{},reason:{code:error62.reasonCode,summary:hasExactLocation?"PostgreSQL rejected an exact pending migration statement and rolled back the transaction.":"PostgreSQL rejected a pending migration, but the exact source span was not unique.",detail:hasExactLocation?"Review the identified statement against the current schema and data. The failed transaction did not commit any migration or journal change.":"Use the stable PostgreSQL reason and the pending list from db:check to identify the customer-owned statement. The transaction and journal did not commit."},suggestedFixes,forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"REDACTED_LITERALS"}})}if(error62.failureClass==="PLATFORM_ACTION_REQUIRED"){return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryAfterSeconds:30,retryCondition:"View the operation receipt and retry only after the Platform DDL permission or runner health has recovered.",reason:{code:error62.reasonCode,summary:"PostgreSQL rolled back because the managed DDL execution boundary was unavailable.",detail:"The transaction and journal did not commit. This is not fixed by editing applied migrations or the journal; use the receipt status before another attempt."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}return platformActionDiagnostic({...base(error62,correlationId),nextAction:"INSPECT_STATE",retryCondition:"Check the operation receipt status before any new mutation request. Do not retry blindly.",reason:{code:error62.reasonCode,summary:"The transaction rolled back, but its cause could not be classified automatically.",detail:"PostgreSQL did not return a recognized error code for this failure. The transaction and journal did not commit. Do not edit applied migrations or the journal."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}var USER_REASON_REPAIR_HINTS;var init_migration_rollback_diagnostic=__esm({"../platform/src/migration-rollback-diagnostic.ts"(){"use strict";init_dist();USER_REASON_REPAIR_HINTS=new Map([["invalid_text_representation","For a value that does not match its column type, change the column DEFAULT or inserted literal in gencow/schema.ts to a value valid for the declared type (for example, a whole number for an integer column), then run db:generate to replace only this unapplied migration."],["string_data_right_truncation","For a value longer than its column allows, shorten the literal or change the column length in gencow/schema.ts, then run db:generate to replace only this unapplied migration."],["feature_not_supported_in_statement","For a DEFAULT PostgreSQL does not accept (a bare word, a subquery, or a column reference), change the DEFAULT in gencow/schema.ts to a literal valid for the column type: a quoted string for text columns, a number for integer columns, true or false for boolean columns. Then run db:generate to replace only this unapplied migration."],["datatype_mismatch","For a DEFAULT whose value type does not match its column, change the DEFAULT in gencow/schema.ts to a value of the column's declared type, then run db:generate to replace only this unapplied migration."],["undefined_function","The statement calls a function that does not exist in this database. Correct the function name or remove it from the DEFAULT in gencow/schema.ts, then run db:generate to replace only this unapplied migration."],["undefined_object","The statement uses a type name that does not exist in this database. Correct the column type in gencow/schema.ts, then run db:generate to replace only this unapplied migration."]])}});function toJournalRow(row){const id=row.id;const hash9=row.hash;const createdAt=row.created_at;const name=row.name;if(typeof id!=="number"||!Number.isSafeInteger(id)||id<1||typeof hash9!=="string"||hash9.length===0||typeof createdAt!=="string"&&typeof createdAt!=="number"&&typeof createdAt!=="bigint"||name!==null&&(typeof name!=="string"||name.length===0)){throw new MigrationJournalReadError("a journal row has an invalid id, name, hash, or timestamp")}return{id,hash:hash9,createdAt:String(createdAt),name}}async function readDrizzleMigrationJournal(params){if(!params.snapshot.journalTableExists)return[];const rows8=await params.sql.unsafe(`
8983
+ `):[];const database=databaseRows[0]??{};const schema=schemaRows[0]??{};const journalSecurity=journalSecurityRows[0]??{};const drizzleSchemaExists=schemaRows.length>0;return{databaseCanConnect:toBoolean(database.database_can_connect),databaseCanCreate:toBoolean(database.database_can_create),publicSchemaUsage:toBoolean(database.public_usage),publicSchemaCreate:toBoolean(database.public_create),drizzleSchemaExists,drizzleSchemaOwner:drizzleSchemaExists?toNullableString(schema.owner):null,drizzleSchemaOwnedByDatabaseOwner:drizzleSchemaExists?toBoolean(schema.owned_by_database_owner):false,drizzleSchemaUsage:drizzleSchemaExists?toBoolean(schema.drizzle_usage):false,drizzleSchemaCreate:drizzleSchemaExists?toBoolean(schema.drizzle_create):false,journalTableExists:toBoolean(journalRows[0]?.journal_exists),journalTableOwner:toNullableString(journalSecurity.owner),journalTableOwnedByDatabaseOwner:toBoolean(journalSecurity.owned_by_database_owner),journalColumns:columnRows.map(row=>toNullableString(row.column_name)).filter(isString),journalCanSelect:toBoolean(journalSecurity.can_select),journalCanInsert:toBoolean(journalSecurity.can_insert),journalCanUpdate:toBoolean(journalSecurity.can_update),journalCanDelete:toBoolean(journalSecurity.can_delete),journalCanTruncate:toBoolean(journalSecurity.can_truncate),journalPlanGuardInstalled:toBoolean(journalSecurity.guard_installed)}}async function assertDrizzleMigrationStoreReadyForPrimaryMigrate(params){const snapshot=await collectDrizzleMigrationStoreSnapshot(params.sql,{roleName:params.roleName});const state2=classifyDrizzleMigrationStoreState(snapshot,params.roleName);if(isDrizzleMigrationStoreStateAllowedForPrimaryMigrate(state2)){return snapshot}const code=getDrizzleMigrationStorePreflightErrorCode(state2)??"DB_MIGRATION_STORE_UNSAFE";throw new DrizzleMigrationStorePreflightError({appName:params.appName,state:state2,code})}function hasCompatibleJournalShape(columns){const present=new Set(columns);for(const required3 of REQUIRED_JOURNAL_COLUMNS){if(!present.has(required3))return false}return true}function toBoolean(value2){return value2===true||value2==="true"||value2===1||value2==="1"}function toNullableString(value2){return typeof value2==="string"&&value2.length>0?value2:null}function isString(value2){return typeof value2==="string"}var REQUIRED_JOURNAL_COLUMNS,DrizzleMigrationStorePreflightError;var init_drizzle_migration_store=__esm({"../platform/src/drizzle-migration-store.ts"(){"use strict";REQUIRED_JOURNAL_COLUMNS=new Set(["id","hash","created_at","name"]);DrizzleMigrationStorePreflightError=class extends Error{code;state;constructor(params){super(`${params.code}: ${params.appName} migration store state=${params.state}; run the Drizzle migration store reconciler before deploy.`);this.name="DrizzleMigrationStorePreflightError";this.code=params.code;this.state=params.state}}}});import{createHash as createHash50}from"node:crypto";import{getMigrationsToRun}from"drizzle-orm/migrator.utils";function fingerprint3(value2){return createHash50("sha256").update(JSON.stringify(value2)).digest("hex")}function localFingerprint(migrations){return fingerprint3(migrations.map(migration=>[migration.name,migration.hash,migration.folderMillis,migration.bps]))}function journalFingerprint(rows8){return fingerprint3([...rows8].sort((left,right)=>left.id-right.id).map(row=>[row.id,row.name,row.hash,row.createdAt]))}function safeMigrationName(name){return JSON.stringify(name)}function indexLocalMigrations(migrations){const byName=new Map;for(const migration of migrations){if(!migration.name||byName.has(migration.name)){throw new MigrationExecutionPlanError("MIGRATION_LOCAL_HISTORY_AMBIGUOUS",migration.name?`duplicate local migration name ${safeMigrationName(migration.name)}`:"a local migration has no stable name",{migrationName:migration.name||void 0,migrationHash:migration.hash})}byName.set(migration.name,migration)}return byName}function indexJournalRows(rows8){const byName=new Map;for(const row of rows8){if(!row.name){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HISTORY_AMBIGUOUS","the Drizzle journal contains an applied row without a stable migration name")}if(byName.has(row.name)){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HISTORY_AMBIGUOUS",`the Drizzle journal contains duplicate migration name ${safeMigrationName(row.name)}`)}byName.set(row.name,row)}return byName}function buildMigrationExecutionPlan(input2){const localMigrations=[...input2.localMigrations];const journalRows=[...input2.journalRows];const localByName=indexLocalMigrations(localMigrations);const journalByName=indexJournalRows(journalRows);for(const[name,row]of journalByName){const local=localByName.get(name);if(!local){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_FILE_MISSING",`applied migration ${safeMigrationName(name)} is absent from the deployment bundle`,{migrationName:name,migrationHash:row.hash})}if(local.hash!==row.hash){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HASH_DRIFT",`applied migration ${safeMigrationName(name)} no longer matches its immutable local file`,{migrationName:name,migrationHash:local.hash})}}const pending=getMigrationsToRun({localMigrations,dbMigrations:journalRows.map(row=>({id:row.id,hash:row.hash,created_at:row.createdAt,name:row.name}))});const pendingNames=new Set(pending.map(migration=>migration.name));const appliedVerified=localMigrations.filter(migration=>!pendingNames.has(migration.name));return{appliedVerified,pending,localFingerprint:localFingerprint(localMigrations),journalFingerprint:journalFingerprint(journalRows),planId:`mig_${fingerprint3([localFingerprint(localMigrations),journalFingerprint(journalRows)]).slice(0,24)}`}}function assertMigrationExecutionPlanUnchanged(planned,current){if(localFingerprint(current.localMigrations)!==planned.localFingerprint||journalFingerprint(current.journalRows)!==planned.journalFingerprint){throw new MigrationExecutionPlanError("MIGRATION_PLAN_CHANGED","local migration files or the database journal changed after audit; retry from a fresh plan",{planId:planned.planId})}}function assertMigrationExecutionPostcondition(planned,current){let isSatisfied=localFingerprint(current.localMigrations)===planned.localFingerprint;if(isSatisfied){try{isSatisfied=buildMigrationExecutionPlan(current).pending.length===0}catch{isSatisfied=false}}if(!isSatisfied){throw new MigrationExecutionPlanError("MIGRATION_POSTCONDITION_FAILED","not every audited migration was recorded with its exact immutable hash",{planId:planned.planId})}}var MigrationExecutionPlanError;var init_migration_execution_plan=__esm({"../platform/src/migration-execution-plan.ts"(){"use strict";MigrationExecutionPlanError=class extends Error{code;migrationName;migrationHash;planId;constructor(code,detail,metadata={}){super(`${code}: ${detail}`);this.name="MigrationExecutionPlanError";this.code=code;this.migrationName=metadata.migrationName;this.migrationHash=metadata.migrationHash;this.planId=metadata.planId}}}});function isWordStart(char){return!!char&&/[A-Za-z_\u0080-\uFFFF]/u.test(char)}function isWordPart(char){return!!char&&/[A-Za-z0-9_$\u0080-\uFFFF]/u.test(char)}function readQuotedToken(sql217,start2,quote2,options={}){let index27=start2+1;while(index27<sql217.length){if(options.backslashEscapes&&sql217[index27]==="\\"&&index27+1<sql217.length){index27+=2;continue}if(sql217[index27]!==quote2){index27+=1;continue}if(sql217[index27+1]===quote2){index27+=2;continue}const end=index27+1;const tokenStart=options.tokenStart??start2;const raw2=sql217.slice(tokenStart,end);const quotedValue=sql217.slice(start2+1,index27);return{token:{kind:quote2==="'"?"string":"identifier",value:quote2==="'"?options.backslashEscapes?quotedValue.replace(/''/g,"'").replace(/\\(.)/gsu,"$1"):quotedValue.replace(/''/g,"'"):quotedValue.replace(/""/g,'"'),raw:raw2,start:tokenStart,end},next:end}}return{next:sql217.length,error:quote2==="'"?"unterminated SQL string":"unterminated identifier"}}function readDollarString(sql217,start2){const opener=sql217.slice(start2).match(/^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/)?.[0];if(!opener)return null;const closeIndex=sql217.indexOf(opener,start2+opener.length);if(closeIndex<0)return{next:sql217.length,error:"unterminated dollar-quoted SQL body"};const end=closeIndex+opener.length;const raw2=sql217.slice(start2,end);return{token:{kind:"dollar-string",value:raw2.slice(opener.length,-opener.length),raw:raw2,start:start2,end},next:end}}function skipBlockComment(sql217,start2){let depth=1;let index27=start2+2;while(index27<sql217.length){if(sql217.startsWith("/*",index27)){depth+=1;index27+=2;continue}if(sql217.startsWith("*/",index27)){depth-=1;index27+=2;if(depth===0)return{next:index27};continue}index27+=1}return{next:sql217.length,error:"unterminated SQL block comment"}}function buildStatement(sql217,tokens,end){if(tokens.length===0)return null;return{text:sql217.slice(tokens[0].start,tokens[tokens.length-1].end).trim(),tokens,start:tokens[0].start,end}}function lexSqlStatements(sql217){const statements=[];let statementTokens=[];let index27=0;while(index27<sql217.length){const char=sql217[index27];if(/\s/u.test(char)){index27+=1;continue}if(sql217.startsWith("--",index27)){const newline=sql217.indexOf("\n",index27+2);index27=newline<0?sql217.length:newline+1;continue}if(sql217.startsWith("/*",index27)){const block=skipBlockComment(sql217,index27);if(block.error)return{statements,error:block.error};index27=block.next;continue}if((char==="E"||char==="e")&&sql217[index27+1]==="'"){const quoted=readQuotedToken(sql217,index27+1,"'",{tokenStart:index27,backslashEscapes:true});if(quoted.error||!quoted.token){return{statements,error:quoted.error??"invalid escape string"}}statementTokens.push(quoted.token);index27=quoted.next;continue}if(char==="'"||char==='"'){const quoted=readQuotedToken(sql217,index27,char);if(quoted.error||!quoted.token)return{statements,error:quoted.error??"invalid quoted token"};statementTokens.push(quoted.token);index27=quoted.next;continue}if(char==="$"){const dollar=readDollarString(sql217,index27);if(dollar){if(dollar.error||!dollar.token)return{statements,error:dollar.error??"invalid dollar string"};statementTokens.push(dollar.token);index27=dollar.next;continue}}if(isWordStart(char)){let end=index27+1;while(isWordPart(sql217[end]))end+=1;const raw2=sql217.slice(index27,end);statementTokens.push({kind:"word",value:raw2.toLowerCase(),raw:raw2,start:index27,end});index27=end;continue}if(char===";"){const statement=buildStatement(sql217,statementTokens,index27+1);if(statement)statements.push(statement);statementTokens=[];index27+=1;continue}statementTokens.push({kind:"symbol",value:char,raw:char,start:index27,end:index27+1});index27+=1}const tail=buildStatement(sql217,statementTokens,statementTokens.at(-1)?.end??sql217.length);if(tail)statements.push(tail);return{statements}}function createSqlLineNumberResolver(sql217){const lineStarts=[0];for(let offset=0;offset<sql217.length;offset+=1){if(sql217[offset]==="\n")lineStarts.push(offset+1)}return offset=>{let low=0;let high=lineStarts.length;while(low<high){const middle=Math.floor((low+high)/2);if(lineStarts[middle]<=offset)low=middle+1;else high=middle}return low}}var init_migration_sql_lexer=__esm({"../platform/src/migration-sql-lexer.ts"(){"use strict"}});async function readMigrationPostExecutionSnapshot(params){let lastError;for(const delayMs of POST_EXECUTION_READ_RETRY_DELAYS_MS){if(delayMs>0)await Bun.sleep(delayMs);try{return{local:await params.readLocal(),journal:await params.readJournal()}}catch(error62){lastError=error62}}throw lastError}function safeObjectField(value2,key2){try{return value2[key2]}catch{return void 0}}function collectFailureFacts(error62){const sqlStates=new Set;const errorCodes=new Set;const queries=new Set;const visited=new Set;const pending=[error62];let extensionUnavailable=false;for(let inspected=0;inspected<64&&pending.length>0;inspected+=1){const current=pending.shift();if(!current||typeof current!=="object")continue;if(visited.has(current))continue;visited.add(current);const ownSqlStates=[];for(const key2 of["code","errno"]){const value2=safeObjectField(current,key2);if(typeof value2==="string"&&/^[a-zA-Z0-9_:-]{1,80}$/u.test(value2)){errorCodes.add(value2);if(/^(?=.*[0-9])[0-9A-Z]{5}$/u.test(value2)){sqlStates.add(value2);ownSqlStates.push(value2)}}}if(ownSqlStates.includes("0A000")){const message=safeObjectField(current,"message");if(typeof message==="string"&&EXTENSION_UNAVAILABLE_MESSAGE.test(message.slice(0,EXTENSION_MESSAGE_MAX_LENGTH))){extensionUnavailable=true}}const query2=safeObjectField(current,"query");if(typeof query2==="string")queries.add(query2);const cause=safeObjectField(current,"cause");if(cause&&typeof cause==="object")pending.push(cause);const errors=safeObjectField(current,"errors");if(Array.isArray(errors)){pending.push(...errors.slice(0,16))}}return{sqlStates:[...sqlStates],errorCodes:[...errorCodes],queries:[...queries],extensionUnavailable}}function isExactPostgresSqlStateFailure(error62,sqlState){if(!/^[0-9A-Z]{5}$/u.test(sqlState))return false;const sqlStates=collectFailureFacts(error62).sqlStates;return sqlStates.length>0&&sqlStates.every(observed2=>observed2===sqlState)}function canonicalStatement(statement){return statement.trim().replace(/;\s*$/u,"").trim()}function statementLocation(source,statement,statementIndex){const lexed=lexSqlStatements(source.sqlContent);if(lexed.error)return void 0;const canonical=canonicalStatement(statement);const matches=lexed.statements.filter(candidate=>canonicalStatement(candidate.text)===canonical);if(matches.length!==1)return void 0;const[match2]=matches;const lineAt=createSqlLineNumberResolver(source.sqlContent);return{name:source.metadata.name,sqlSha256:source.metadata.hash,statementIndex,lineStart:lineAt(match2.start),lineEnd:lineAt(Math.max(match2.end-1,match2.start))}}function findExactFailureLocation(queries,pendingSources){const querySet=new Set(queries);const matches=[];for(const source of pendingSources){for(const[index27,statement]of source.metadata.sql.entries()){if(!querySet.has(statement))continue;const location=statementLocation(source,statement,index27+1);if(location)matches.push(location)}}return matches.length===1?matches[0]:void 0}function singlePendingFileLocation(queries,pendingSources){if(pendingSources.length!==1)return void 0;const[source]=pendingSources;const segments=source.metadata.sql;if(!queries.some(query2=>segments.includes(query2)))return void 0;return{name:source.metadata.name,sqlSha256:source.metadata.hash}}function retryableReason(sqlStates){for(const state2 of sqlStates){const exact=RETRYABLE_SQLSTATES.get(state2);if(exact)return exact;if(state2.startsWith("08"))return"database_connection_lost"}return void 0}function userReason(sqlStates){for(const state2 of sqlStates){const exact=USER_SQLSTATE_REASONS.get(state2);if(exact)return exact;if(/^(22|23|42)/u.test(state2)||state2==="P0001"){return`postgres_sqlstate_${state2.toLowerCase()}`}}return void 0}function platformReason(facts){for(const state2 of facts.sqlStates){if(state2==="0A000"){if(facts.extensionUnavailable)return EXTENSION_UNAVAILABLE_REASON;continue}const exact=PLATFORM_SQLSTATE_REASONS.get(state2);if(exact)return exact}return void 0}function buildMigrationTransactionRolledBackError(params){const facts=collectFailureFacts(params.cause);const platformFailure=platformReason(facts);if(platformFailure){return new MigrationTransactionRolledBackError({failureClass:"PLATFORM_ACTION_REQUIRED",reasonCode:platformFailure,planId:params.planId})}const transient=retryableReason(facts.sqlStates);if(transient){return new MigrationTransactionRolledBackError({failureClass:"RETRYABLE_INFRA",reasonCode:transient,planId:params.planId})}const migration=findExactFailureLocation(facts.queries,params.pendingSources)??singlePendingFileLocation(facts.queries,params.pendingSources);const userFailure=userReason(facts.sqlStates);if(userFailure){return new MigrationTransactionRolledBackError({failureClass:"USER_FIXABLE",reasonCode:userFailure,planId:params.planId,...migration?{migration}:{}})}if(facts.sqlStates.length===0){console.warn(`[migration] execution failure had no PostgreSQL SQLSTATE in the redacted cause chain codes=${facts.errorCodes.join(",")||"none"}`)}return new MigrationTransactionRolledBackError({failureClass:"UNCLASSIFIED",reasonCode:"execution_failure_unclassified",planId:params.planId})}var RETRYABLE_SQLSTATES,USER_SQLSTATE_REASONS,EXTENSION_UNAVAILABLE_REASON,EXTENSION_UNAVAILABLE_MESSAGE,EXTENSION_MESSAGE_MAX_LENGTH,PLATFORM_SQLSTATE_REASONS,POST_EXECUTION_READ_RETRY_DELAYS_MS,MigrationTransactionRolledBackError;var init_migration_execution_outcome=__esm({"../platform/src/migration-execution-outcome.ts"(){"use strict";init_migration_sql_lexer();RETRYABLE_SQLSTATES=new Map([["40001","serialization_failure"],["40P01","deadlock_detected"],["55P03","lock_not_available"],["57014","statement_timeout_or_cancelled"],["53300","too_many_connections"],["53400","configuration_limit_exceeded"],["57P01","database_admin_shutdown"],["57P02","database_crash_shutdown"],["57P03","database_starting_up"]]);USER_SQLSTATE_REASONS=new Map([["22001","string_data_right_truncation"],["22P02","invalid_text_representation"],["25001","active_sql_transaction"],["23502","not_null_violation"],["23503","foreign_key_violation"],["23505","unique_violation"],["42601","syntax_error"],["42701","duplicate_column"],["42703","undefined_column"],["42704","undefined_object"],["42804","datatype_mismatch"],["42883","undefined_function"],["42P01","undefined_table"],["42P07","duplicate_table"],["0A000","feature_not_supported_in_statement"]]);EXTENSION_UNAVAILABLE_REASON="feature_not_supported";EXTENSION_UNAVAILABLE_MESSAGE=/extension\s+\S.*?\s+is not (?:available|allowed)/iu;EXTENSION_MESSAGE_MAX_LENGTH=512;PLATFORM_SQLSTATE_REASONS=new Map([["42501","insufficient_privilege"],["28000","invalid_authorization_specification"],["28P01","invalid_password"]]);POST_EXECUTION_READ_RETRY_DELAYS_MS=[0,25,100,250];MigrationTransactionRolledBackError=class extends Error{code="MIGRATION_TRANSACTION_ROLLED_BACK";failureClass;reasonCode;planId;migration;constructor(params){super("MIGRATION_TRANSACTION_ROLLED_BACK: the PostgreSQL transaction was rolled back");this.name="MigrationTransactionRolledBackError";this.failureClass=params.failureClass;this.reasonCode=params.reasonCode;this.planId=params.planId;this.migration=params.migration}}}});function base(error62,correlationId){return{code:error62.code,phase:"EXECUTE",databaseState:"ROLLED_BACK",correlationId}}function buildRolledBackDiagnostic(params){const{error:error62,correlationId,migration}=params;if(error62.failureClass==="RETRYABLE_INFRA"){return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryCondition:"Retry the same immutable bundle after the temporary PostgreSQL condition clears.",retryAfterSeconds:5,reason:{code:error62.reasonCode,summary:"The migration transaction was rolled back after a temporary database failure.",detail:"PostgreSQL confirmed that the transaction and its journal writes did not commit. No source edit is recommended."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}if(error62.failureClass==="USER_FIXABLE"){const hasExactStatement=migration?.statementIndex!==void 0;const hasPendingFile=migration!==void 0&&!hasExactStatement;const repairHint=USER_REASON_REPAIR_HINTS.get(error62.reasonCode);const suggestedFixes=[{id:"repair-pending-migration",title:hasExactStatement?"Repair the exact unapplied migration statement":hasPendingFile?"Repair the unapplied migration file":"Inspect the pending migration candidates",detail:repairHint??(hasExactStatement?"Update the schema source or this unapplied statement, review the generated diff, and create a fresh immutable plan.":"Run db:check to list the pending migrations, locate the statement matching this PostgreSQL reason, then update only unapplied source and create a fresh plan."),target:"PENDING_MIGRATION",confidence:hasExactStatement?"HIGH":"MEDIUM"}];return userFixableDiagnostic({...base(error62,correlationId),retryCondition:hasExactStatement?"Fix only the exact unapplied statement, then create and check a fresh plan.":"Fix only the unapplied migration source for the cause above, then create and check a fresh plan.",...migration?{migration}:{},reason:{code:error62.reasonCode,summary:hasExactStatement?"PostgreSQL rejected an exact pending migration statement and rolled back the transaction.":hasPendingFile?"PostgreSQL rejected a statement in the only pending migration and rolled back the transaction.":"PostgreSQL rejected a pending migration, but the exact source span was not unique.",detail:hasExactStatement?"Review the identified statement against the current schema and data. The failed transaction did not commit any migration or journal change.":hasPendingFile?"Review the only pending migration file against the current schema and data. The failed transaction did not commit any migration or journal change.":"Use the stable PostgreSQL reason and the pending list from db:check to identify the customer-owned statement. The transaction and journal did not commit."},suggestedFixes,forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"REDACTED_LITERALS"}})}if(error62.failureClass==="PLATFORM_ACTION_REQUIRED"){return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryAfterSeconds:30,retryCondition:"View the operation receipt and retry only after the Platform DDL permission or runner health has recovered.",reason:{code:error62.reasonCode,summary:"PostgreSQL rolled back because the managed DDL execution boundary was unavailable.",detail:"The transaction and journal did not commit. This is not fixed by editing applied migrations or the journal; use the receipt status before another attempt."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}return platformActionDiagnostic({...base(error62,correlationId),nextAction:"INSPECT_STATE",retryCondition:"Check the operation receipt status before any new mutation request. Do not retry blindly.",reason:{code:error62.reasonCode,summary:"The transaction rolled back, but its cause could not be classified automatically.",detail:"PostgreSQL did not return a recognized error code for this failure. The transaction and journal did not commit. Do not edit applied migrations or the journal."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}var SHARED_REPAIR_PATH,USER_REASON_CAUSES,USER_REASON_REPAIR_HINTS;var init_migration_rollback_diagnostic=__esm({"../platform/src/migration-rollback-diagnostic.ts"(){"use strict";init_dist();SHARED_REPAIR_PATH='Correct the cause in gencow/schema.ts first, because db:generate rebuilds an unapplied folder from that file. Then run `gencow db:check --inspect-state` (for a PROD target add `--prod --app <id>`). If it lists pending folders under "Pending migrations that may be regenerated", back up or commit the project, remove every folder it lists, and run `gencow db:generate`. If it lists nothing, correct the failing statement in its unapplied migration file in place. Then run `gencow db:check` and `gencow db:push`. Applied migrations and the Drizzle journal are never changed.';USER_REASON_CAUSES=new Map([["invalid_text_representation","A value does not match its column type: use a value valid for the declared type (for example, a whole number for an integer column) in the DEFAULT or inserted literal."],["string_data_right_truncation","A value is longer than its column allows: shorten the literal or change the column length."],["feature_not_supported_in_statement","A DEFAULT PostgreSQL does not accept (a bare word, a subquery, or a column reference): use a literal valid for the column type (a quoted string for text, a number for integer, true or false for boolean)."],["datatype_mismatch","A DEFAULT value type does not match its column: use a value of the column's declared type."],["undefined_function","The statement calls a function that does not exist in this database: correct the function name or remove it from the DEFAULT."],["undefined_object","The statement uses a type name that does not exist in this database: correct the column type."]]);USER_REASON_REPAIR_HINTS=new Map([...USER_REASON_CAUSES].map(([reason,cause])=>[reason,`${cause} ${SHARED_REPAIR_PATH}`]))}});function toJournalRow(row){const id=row.id;const hash9=row.hash;const createdAt=row.created_at;const name=row.name;if(typeof id!=="number"||!Number.isSafeInteger(id)||id<1||typeof hash9!=="string"||hash9.length===0||typeof createdAt!=="string"&&typeof createdAt!=="number"&&typeof createdAt!=="bigint"||name!==null&&(typeof name!=="string"||name.length===0)){throw new MigrationJournalReadError("a journal row has an invalid id, name, hash, or timestamp")}return{id,hash:hash9,createdAt:String(createdAt),name}}async function readDrizzleMigrationJournal(params){if(!params.snapshot.journalTableExists)return[];const rows8=await params.sql.unsafe(`
8984
8984
  SELECT id, hash, created_at::text AS created_at, name
8985
8985
  FROM "drizzle"."__drizzle_migrations"
8986
8986
  ORDER BY id