gencow 0.1.272 → 0.1.274

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.
@@ -108,6 +108,11 @@ const SAFE_LOCAL_ERROR_CODES = new Map([
108
108
  const where = safeSourceLocation(caught) ? "at the location above " : "";
109
109
  return `Retryable: yes, after the import of "${name}" ${where}names an export its module does not have — use an exported name, or export it from that module, then run \`npx gencow@latest codegen\` to confirm it passes, then rerun your deploy command.`;
110
110
  }
111
+ const unresolved = safeUnresolvedSpecifier(caught);
112
+ if (unresolved) {
113
+ const where = safeSourceLocation(caught) ? "at the location above " : "";
114
+ return `Retryable: yes, after the import of "${unresolved}" ${where}does not resolve — create that file or correct the import path, then run \`npx gencow@latest codegen\` to confirm it passes, then rerun your deploy command.`;
115
+ }
111
116
  const cause =
112
117
  "the top-level code that throws during module load, or an import path that does not resolve (check the path and that the imported package is installed)";
113
118
  if (safeSourceLocation(caught)) {
@@ -256,6 +261,18 @@ function safeMissingExportName(caught) {
256
261
  return typeof missingExport === "string" && SAFE_IMPORT_NAME.test(missingExport) ? missingExport : null;
257
262
  }
258
263
 
264
+ // Only a relative specifier is shown (never a bare package name or an absolute path).
265
+ const SAFE_UNRESOLVED_SPECIFIER = /^\.{1,2}\/[\w.@~+-]+(?:\/[\w.@~+-]+){0,15}$/u;
266
+
267
+ function safeUnresolvedSpecifier(caught) {
268
+ const { unresolvedSpecifier } = caught;
269
+ return typeof unresolvedSpecifier === "string" &&
270
+ unresolvedSpecifier.length <= 240 &&
271
+ SAFE_UNRESOLVED_SPECIFIER.test(unresolvedSpecifier)
272
+ ? unresolvedSpecifier
273
+ : null;
274
+ }
275
+
259
276
  function safeSourceLocation(caught) {
260
277
  const { sourceFile, line, column } = caught;
261
278
  if (typeof sourceFile !== "string" || !SAFE_SOURCE_LOCATION_PATH.test(sourceFile)) return null;
@@ -628,6 +628,13 @@ function createDbMigrationCommand(deps, command) {
628
628
  functionsDir,
629
629
  retryCommand,
630
630
  inspectionCommand,
631
+ receiptStatusCommand: (serverReceiptId) =>
632
+ buildMigrationStatusCommand({
633
+ appId,
634
+ environment: envLabel,
635
+ receiptId: serverReceiptId,
636
+ jsonMode,
637
+ }),
631
638
  },
632
639
  )
633
640
  : isCheck
@@ -41,6 +41,9 @@ function toProjectRelativePath(rawPath, cwd, processCwd) {
41
41
  const DIAGNOSTIC_LINE_PATTERN = /ERROR: |Could not resolve "|Cannot find (?:module|package)\b/u;
42
42
  const UNRESOLVED_MODULE_PATTERN = /Could not resolve "|Cannot find (?:module|package)\b|No matching export in "/u;
43
43
  const MISSING_EXPORT_PATTERN = /No matching export in "[^"\n]*" for import "([A-Za-z_$][\w$]{0,127})"/u;
44
+ // The specifier of an unresolved import, as esbuild and the named-import check print it. It is
45
+ // only carried here; the renderer decides whether it is safe to show.
46
+ const UNRESOLVED_SPECIFIER_PATTERN = /Could not resolve "([^"\n]{1,240})"/u;
44
47
 
45
48
  // The first diagnostic decides the class, matching how the first location is reported.
46
49
  function firstDiagnosticLine(message) {
@@ -56,6 +59,11 @@ function findMissingExportName(message) {
56
59
  return MISSING_EXPORT_PATTERN.exec(firstDiagnosticLine(message))?.[1] ?? null;
57
60
  }
58
61
 
62
+ // Returns the specifier of an unresolved-import diagnostic, or null.
63
+ function findUnresolvedSpecifier(message) {
64
+ return UNRESOLVED_SPECIFIER_PATTERN.exec(firstDiagnosticLine(message))?.[1] ?? null;
65
+ }
66
+
59
67
  // Returns the first project-relative source location found in a raw message, or null.
60
68
  // Absolute paths, stacks and the raw text are never returned.
61
69
  function findProjectSourceLocation(message, { cwd, processCwd }) {
@@ -79,10 +87,12 @@ export function classifyDeployCodegenFailure(error, { cwd, backendRoot = "gencow
79
87
  const backendLocation = location && location.sourceFile.startsWith(`${backendRoot}/`) ? location : null;
80
88
  if (isUnresolvedModuleFailure(message)) {
81
89
  const missingExport = findMissingExportName(message);
90
+ const unresolvedSpecifier = findUnresolvedSpecifier(message);
82
91
  return {
83
92
  code: CODEGEN_FAILURE_CODES.SOURCE_LOAD_FAILED,
84
93
  ...(backendLocation ?? {}),
85
94
  ...(missingExport ? { missingExport } : {}),
95
+ ...(unresolvedSpecifier ? { unresolvedSpecifier } : {}),
86
96
  };
87
97
  }
88
98
  if (location) {
@@ -157,6 +167,7 @@ export function createDeployCodegenFailure(classification, { correlationId } = {
157
167
  if (classification.column !== undefined) error.column = classification.column;
158
168
  }
159
169
  if (classification.missingExport !== undefined) error.missingExport = classification.missingExport;
170
+ if (classification.unresolvedSpecifier !== undefined) error.unresolvedSpecifier = classification.unresolvedSpecifier;
160
171
  // Local reference only (no Platform request exists for a codegen failure).
161
172
  if (correlationId !== undefined) error.correlationId = correlationId;
162
173
  return error;
@@ -23,7 +23,7 @@ import {
23
23
  import { buildDeployClaimFromArchive } from "./deploy-package-claim.mjs";
24
24
  import { renderDeployFailureDiagnosticLines } from "./deploy-failure-diagnostic.mjs";
25
25
  import { readJsonObjectResponse } from "./http-response-json.mjs";
26
- import { pollAcceptedDeploymentOperation } from "./deployment-operation-poll.mjs";
26
+ import { formatDeploymentAcceptedLine, pollAcceptedDeploymentOperation } from "./deployment-operation-poll.mjs";
27
27
  import { postDeploymentAdmissionWithTimeout } from "./deploy-admission-boundary.mjs";
28
28
  import { submitDeploymentWithIdempotentRetry } from "./deployment-admission-retry.mjs";
29
29
  import * as deployReceiptStore from "./deploy-receipt-store.mjs";
@@ -548,19 +548,26 @@ export function createDeployPackageRuntime({
548
548
  const spinnerFrames = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"];
549
549
  const start = Date.now();
550
550
  let index = 0;
551
- return setIntervalImpl(() => {
551
+ const spinner = { label, timer: null, setLabel: (next) => void (spinner.label = next) };
552
+ spinner.timer = setIntervalImpl(() => {
552
553
  const elapsed = ((Date.now() - start) / 1000).toFixed(0);
553
554
  processRef.stdout.write(
554
- `\r ${CYAN}${spinnerFrames[index++ % spinnerFrames.length]}${RESET} ${label} ${DIM}(${elapsed}s)${RESET} `,
555
+ `\r ${CYAN}${spinnerFrames[index++ % spinnerFrames.length]}${RESET} ${spinner.label} ${DIM}(${elapsed}s)${RESET} `,
555
556
  );
556
557
  }, 120);
558
+ return spinner;
557
559
  }
558
560
 
559
- function stopSpinner(spinner) {
560
- clearInterval(spinner);
561
+ // Clears the spinner glyph from the current terminal line before a status line is printed.
562
+ function clearSpinnerLine() {
561
563
  processRef.stdout.write("\r" + " ".repeat(50) + "\r");
562
564
  }
563
565
 
566
+ function stopSpinner(spinner) {
567
+ clearInterval(spinner.timer);
568
+ clearSpinnerLine();
569
+ }
570
+
564
571
  async function deployBundleWithRetry({
565
572
  creds,
566
573
  appId,
@@ -618,6 +625,7 @@ export function createDeployPackageRuntime({
618
625
  body: activeBundleBuffer,
619
626
  signal,
620
627
  });
628
+ let activeSpinner = null;
621
629
  const pollAcceptedDeployment = (initialResponse) =>
622
630
  pollAcceptedDeploymentOperation({
623
631
  initialResponse,
@@ -625,6 +633,11 @@ export function createDeployPackageRuntime({
625
633
  expectedAppName: appId,
626
634
  platformFetch: platformFetchImpl,
627
635
  setTimeoutImpl,
636
+ onAccepted: (accepted) => {
637
+ clearSpinnerLine();
638
+ infoImpl(formatDeploymentAcceptedLine({ ...accepted, envTarget }));
639
+ },
640
+ onPhase: (phase) => activeSpinner?.setLabel(`Deploying... (${phase})`),
628
641
  });
629
642
  const submitDeployAdmission = () => {
630
643
  return submitDeploymentWithIdempotentRetry({
@@ -660,7 +673,7 @@ export function createDeployPackageRuntime({
660
673
 
661
674
  let targetAppId = appId;
662
675
  const startTime = Date.now();
663
- const spinner = startSpinner("Deploying...");
676
+ const spinner = (activeSpinner = startSpinner("Deploying..."));
664
677
  let deployRes;
665
678
  try {
666
679
  deployRes = await submitDeployAdmission();
@@ -672,6 +685,7 @@ export function createDeployPackageRuntime({
672
685
  throw error;
673
686
  } finally {
674
687
  stopSpinner(spinner);
688
+ activeSpinner = null;
675
689
  }
676
690
 
677
691
  if (!deployRes.ok && deployRes.status === 404) {
@@ -715,7 +729,7 @@ export function createDeployPackageRuntime({
715
729
  activeDeployClaim = receipt.deployClaim;
716
730
  }
717
731
  infoImpl("Retrying deploy...");
718
- const retrySpinner = startSpinner("Deploying...");
732
+ const retrySpinner = (activeSpinner = startSpinner("Deploying..."));
719
733
  try {
720
734
  deployRes = await submitDeployAdmission();
721
735
  if (deployRes.status === 202) {
@@ -723,6 +737,7 @@ export function createDeployPackageRuntime({
723
737
  }
724
738
  } finally {
725
739
  stopSpinner(retrySpinner);
740
+ activeSpinner = null;
726
741
  }
727
742
  }
728
743
 
@@ -30,6 +30,17 @@ export function readDeploymentOperationPhase(body) {
30
30
  return { phase: body.phase, reasonCode, deadlineAt };
31
31
  }
32
32
 
33
+ /**
34
+ * One-line acceptance notice for `gencow deploy`. The identity was validated by
35
+ * pollAcceptedDeploymentOperation (positive integer operation ID, safe correlation ID).
36
+ * The status command uses the operation-scoped `--deployment` form, which accepts only `--prod` as
37
+ * a trailing selector, so no `--app` is appended.
38
+ */
39
+ export function formatDeploymentAcceptedLine({ operationId, correlationId, envTarget }) {
40
+ const prodSelector = envTarget === "prod" ? " --prod" : "";
41
+ return `Deployment accepted: ${operationId} (correlation ${correlationId}) - check with: gencow deploy status --deployment ${operationId}${prodSelector}`;
42
+ }
43
+
33
44
  export function formatDeploymentOperationPhase(body) {
34
45
  const phase = readDeploymentOperationPhase(body);
35
46
  if (!phase) return null;
@@ -99,6 +110,11 @@ function isNonterminalResponse(response, body, identity) {
99
110
  );
100
111
  }
101
112
 
113
+ /**
114
+ * Optional observers (no extra requests): `onAccepted` runs once when the
115
+ * accepted operation identity is established; `onPhase` runs when the reported
116
+ * phase name changes.
117
+ */
102
118
  export async function pollAcceptedDeploymentOperation({
103
119
  initialResponse,
104
120
  creds,
@@ -109,6 +125,8 @@ export async function pollAcceptedDeploymentOperation({
109
125
  deadlineClearTimeoutImpl = clearTimeout,
110
126
  nowImpl = () => performance.now(),
111
127
  totalDeadlineMs = DEFAULT_DEPLOYMENT_OPERATION_POLL_DEADLINE_MS,
128
+ onAccepted = null,
129
+ onPhase = null,
112
130
  }) {
113
131
  const expected = {
114
132
  operationId: null,
@@ -126,6 +144,7 @@ export async function pollAcceptedDeploymentOperation({
126
144
  const startedAtMs = nowImpl();
127
145
  const deadlineMs = startedAtMs + totalDeadlineMs;
128
146
  let lastIdentity = null;
147
+ let lastReportedPhase = null;
129
148
  const pendingResponse = () => ({
130
149
  ok: false,
131
150
  status: 503,
@@ -188,10 +207,23 @@ export async function pollAcceptedDeploymentOperation({
188
207
  return invalidOperationResponse("Platform returned an invalid deployment operation");
189
208
  }
190
209
  } else {
210
+ const firstAcceptance = expected.operationId === null;
191
211
  expected.operationId ??= identity.operationId;
192
212
  expected.correlationId ??= identity.correlationId;
193
213
  expected.pollUrl ??= identity.pollUrl;
194
214
  lastIdentity = identity;
215
+ // Diagnostic callbacks must never fail an already-accepted deployment.
216
+ if (firstAcceptance) {
217
+ try {
218
+ onAccepted?.({ operationId: identity.operationId, correlationId: identity.correlationId });
219
+ } catch {}
220
+ }
221
+ if (identity.phase && identity.phase.phase !== lastReportedPhase) {
222
+ lastReportedPhase = identity.phase.phase;
223
+ try {
224
+ onPhase?.(identity.phase.phase);
225
+ } catch {}
226
+ }
195
227
  }
196
228
  if (nowImpl() >= deadlineMs) return pendingResponse();
197
229
  const retryAfter = Number(response.headers?.get?.("Retry-After"));
@@ -222,6 +222,7 @@ export function enrichMigrationDiagnostic(
222
222
  functionsDir,
223
223
  retryCommand,
224
224
  inspectionCommand,
225
+ receiptStatusCommand,
225
226
  readFileSyncImpl = readFileSync,
226
227
  realpathSyncImpl = realpathSync,
227
228
  },
@@ -233,11 +234,20 @@ export function enrichMigrationDiagnostic(
233
234
  diagnostic.retryPolicy !== "BLOCKED" &&
234
235
  (diagnostic.nextAction?.kind === "EDIT_AND_CHECK" || diagnostic.nextAction?.kind === "RETRY");
235
236
  const canAttachInspectionCommand = inspectionCommand && diagnostic.nextAction?.kind === "INSPECT_STATE";
237
+ // An unclassified rollback has no safe retry: its exact next step is the receipt status command.
238
+ const canAttachReceiptStatusCommand =
239
+ typeof receiptStatusCommand === "function" &&
240
+ diagnostic.code === "MIGRATION_TRANSACTION_ROLLED_BACK" &&
241
+ diagnostic.databaseState === "ROLLED_BACK" &&
242
+ diagnostic.nextAction?.kind === "INSPECT_STATE" &&
243
+ typeof diagnostic.receiptId === "string";
236
244
  const nextAction = canAttachRetryCommand
237
245
  ? { kind: diagnostic.nextAction.kind, command: retryCommand }
238
- : canAttachInspectionCommand
239
- ? { kind: "INSPECT_STATE", command: inspectionCommand }
240
- : { kind: diagnostic.nextAction?.kind };
246
+ : canAttachReceiptStatusCommand
247
+ ? { kind: "INSPECT_STATE", command: receiptStatusCommand(diagnostic.receiptId) }
248
+ : canAttachInspectionCommand
249
+ ? { kind: "INSPECT_STATE", command: inspectionCommand }
250
+ : { kind: diagnostic.nextAction?.kind };
241
251
  const base = {
242
252
  ...diagnostic,
243
253
  ...(diagnostic.migration
@@ -316,9 +326,12 @@ function shouldRenderForbiddenActions(diagnostic) {
316
326
  }
317
327
 
318
328
  export function renderMigrationDiagnosticLines(diagnostic) {
329
+ // A rolled-back diagnostic keeps its own title and state; the "temporarily unavailable"
330
+ // wording is reserved for non-rollback platform-action failures.
319
331
  if (
320
332
  diagnostic.failureClass === "PLATFORM_ACTION_REQUIRED" &&
321
- diagnostic.nextAction?.kind !== "UPDATE_CLI"
333
+ diagnostic.nextAction?.kind !== "UPDATE_CLI" &&
334
+ diagnostic.databaseState !== "ROLLED_BACK"
322
335
  ) {
323
336
  const lines = [
324
337
  "Migration check is temporarily unavailable",
@@ -22,6 +22,19 @@ const USER_FIXABLE_CAUSES = new Map([
22
22
  const NOT_NULL_REPAIR_HINT =
23
23
  "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).";
24
24
 
25
+ // Type/data repair hints for the unlocated fallback. Mirrors the server's suggested-fix text in
26
+ // migration-rollback-diagnostic.ts; both must name only the column DEFAULT or literal in schema.ts.
27
+ const TYPE_REPAIR_HINTS = new Map([
28
+ [
29
+ "invalid_text_representation",
30
+ "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.",
31
+ ],
32
+ [
33
+ "string_data_right_truncation",
34
+ "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.",
35
+ ],
36
+ ]);
37
+
25
38
  const SAFE_REASON_CODE = /^[a-z0-9_]{1,80}$/u;
26
39
 
27
40
  export function isUserFixableRolledBackDiagnostic(diagnostic) {
@@ -51,7 +64,8 @@ export function renderRollbackCauseLine(diagnostic) {
51
64
  export function renderUnlocatedRollbackFix(diagnostic) {
52
65
  const name = diagnostic?.migration?.name;
53
66
  const code = safeRollbackReasonCode(diagnostic);
54
- const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : "";
67
+ const typeHint = code ? TYPE_REPAIR_HINTS.get(code) : undefined;
68
+ const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : typeHint ? ` ${typeHint}` : "";
55
69
  return {
56
70
  title: name
57
71
  ? `Inspect the unapplied migration file ${name}`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gencow",
3
- "version": "0.1.272",
3
+ "version": "0.1.274",
4
4
  "description": "Gencow — AI Backend Engine",
5
5
  "type": "module",
6
6
  "bin": {
@@ -41,10 +41,10 @@
41
41
  "better-auth": "1.7.11",
42
42
  "postgres": "^3.4.9",
43
43
  "@gencow/client": "0.2.8",
44
+ "@gencow/react": "0.2.8",
44
45
  "@gencow/core": "0.1.47",
45
46
  "@gencow/server": "0.1.3",
46
- "@gencow/shared": "0.0.0",
47
- "@gencow/react": "0.2.8"
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",
@@ -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];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);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-9A-Z]{5}$/u.test(value2))sqlStates.add(value2)}}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]}}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(sqlStates){for(const state2 of sqlStates){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.sqlStates);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:"PLATFORM_ACTION_REQUIRED",reasonCode:"execution_failure_unclassified",planId:params.planId})}var RETRYABLE_SQLSTATES,USER_SQLSTATE_REASONS,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"],["42P01","undefined_table"],["42P07","duplicate_table"]]);PLATFORM_SQLSTATE_REASONS=new Map([["42501","insufficient_privilege"],["0A000","feature_not_supported"],["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 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.",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 retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryAfterSeconds:30,retryCondition:"Retry the same immutable bundle after the temporary classification failure clears.",reason:{code:error62.reasonCode,summary:"The transaction rolled back, but the failure could not be classified automatically.",detail:"PostgreSQL proved that the transaction did not commit. Keep the source unchanged and retry after the indicated delay."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}var init_migration_rollback_diagnostic=__esm({"../platform/src/migration-rollback-diagnostic.ts"(){"use strict";init_dist()}});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];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);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)}}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]}}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(sqlStates){for(const state2 of sqlStates){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.sqlStates);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,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"],["42P01","undefined_table"],["42P07","duplicate_table"]]);PLATFORM_SQLSTATE_REASONS=new Map([["42501","insufficient_privilege"],["0A000","feature_not_supported"],["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."]])}});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
@@ -6777,12 +6777,14 @@ function shouldTriggerCodegenFromPath(path, backendRoot = "gencow") {
6777
6777
  }
6778
6778
 
6779
6779
  // scripts/codegen-named-import-check.ts
6780
+ import { statSync as statSync3 } from "node:fs";
6780
6781
  import { createRequire } from "node:module";
6781
- import { join as join6, relative as relative4, resolve as resolve10, sep as sep2 } from "node:path";
6782
+ import { dirname as dirname4, join as join6, relative as relative4, resolve as resolve10, sep as sep2 } from "node:path";
6782
6783
  var SCRIPT_FILE = /\.(?:[cm]?[jt]sx?)$/u;
6783
6784
  var TYPESCRIPT_FILE = /\.(?:[cm]?tsx?)$/u;
6784
6785
  var RELATIVE_SPECIFIER = /^\.{1,2}\//u;
6785
6786
  var DECLARATION_FILE = /\.d\.[cm]?ts$/u;
6787
+ var FALLBACK_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".json", ".css"];
6786
6788
  function loadProjectTypeScript(projectRoot) {
6787
6789
  try {
6788
6790
  const requireFromProject = createRequire(join6(projectRoot, "package.json"));
@@ -6792,17 +6794,31 @@ function loadProjectTypeScript(projectRoot) {
6792
6794
  return null;
6793
6795
  }
6794
6796
  }
6797
+ function isFile(path) {
6798
+ try {
6799
+ return statSync3(path).isFile();
6800
+ } catch {
6801
+ return false;
6802
+ }
6803
+ }
6804
+ function existsOnDisk(fromFile, specifier) {
6805
+ const base = resolve10(dirname4(fromFile), specifier);
6806
+ if (isFile(base)) return true;
6807
+ return FALLBACK_EXTENSIONS.some((ext) => isFile(`${base}${ext}`) || isFile(join6(base, `index${ext}`)));
6808
+ }
6795
6809
  function resolveRelativeModule(ctx, fromFile, specifier) {
6796
- if (!RELATIVE_SPECIFIER.test(specifier)) return null;
6810
+ if (!RELATIVE_SPECIFIER.test(specifier)) return { status: "skipped" };
6797
6811
  const resolved = ctx.ts.resolveModuleName(
6798
6812
  specifier,
6799
6813
  fromFile,
6800
6814
  ctx.compilerOptions,
6801
6815
  ctx.ts.sys
6802
6816
  ).resolvedModule;
6803
- if (!resolved || resolved.isExternalLibraryImport) return null;
6804
- if (DECLARATION_FILE.test(resolved.resolvedFileName)) return null;
6805
- return resolved.resolvedFileName;
6817
+ if (resolved && !resolved.isExternalLibraryImport) {
6818
+ if (DECLARATION_FILE.test(resolved.resolvedFileName)) return { status: "skipped" };
6819
+ return { status: "resolved", file: resolved.resolvedFileName };
6820
+ }
6821
+ return existsOnDisk(fromFile, specifier) ? { status: "skipped" } : { status: "unresolved" };
6806
6822
  }
6807
6823
  function parseSource(ctx, file2) {
6808
6824
  const text = ctx.ts.sys.readFile(file2);
@@ -6840,8 +6856,8 @@ function collectExportNames(ctx, file2) {
6840
6856
  if (ts.isExportDeclaration(statement)) {
6841
6857
  const clause = statement.exportClause;
6842
6858
  if (!clause) {
6843
- const target = resolveRelativeModule(ctx, file2, statement.moduleSpecifier.text);
6844
- const inner = target ? exportNamesOf(ctx, target) : null;
6859
+ const resolution = resolveRelativeModule(ctx, file2, statement.moduleSpecifier.text);
6860
+ const inner = resolution.status === "resolved" ? exportNamesOf(ctx, resolution.file) : null;
6845
6861
  if (!inner) return null;
6846
6862
  for (const name2 of inner) if (name2 !== "default") names.add(name2);
6847
6863
  } else if (ts.isNamespaceExport(clause)) {
@@ -6867,40 +6883,65 @@ function collectExportNames(ctx, file2) {
6867
6883
  }
6868
6884
  return names;
6869
6885
  }
6870
- function missingNamedImportsIn(ctx, file2) {
6886
+ function valueReferenceOf(ts, statement) {
6887
+ if (ts.isImportDeclaration(statement)) {
6888
+ const clause = statement.importClause;
6889
+ if (!clause) return { specifier: statement.moduleSpecifier, elements: [] };
6890
+ if (clause.isTypeOnly) return null;
6891
+ const bindings = clause.namedBindings;
6892
+ if (bindings && ts.isNamedImports(bindings)) {
6893
+ const elements = bindings.elements.filter((element) => !element.isTypeOnly);
6894
+ if (!clause.name && bindings.elements.length > 0 && elements.length === 0) return null;
6895
+ return { specifier: statement.moduleSpecifier, elements };
6896
+ }
6897
+ return { specifier: statement.moduleSpecifier, elements: [] };
6898
+ }
6899
+ if (ts.isExportDeclaration(statement) && statement.moduleSpecifier && !statement.isTypeOnly) {
6900
+ const clause = statement.exportClause;
6901
+ if (clause && ts.isNamedExports(clause)) {
6902
+ const elements = clause.elements.filter((element) => !element.isTypeOnly);
6903
+ if (clause.elements.length > 0 && elements.length === 0) return null;
6904
+ return { specifier: statement.moduleSpecifier, elements };
6905
+ }
6906
+ return { specifier: statement.moduleSpecifier, elements: [] };
6907
+ }
6908
+ return null;
6909
+ }
6910
+ function positionOf(sourceFile, node2) {
6911
+ const position = sourceFile.getLineAndCharacterOfPosition(node2.getStart(sourceFile));
6912
+ return { line: position.line + 1, column: position.character };
6913
+ }
6914
+ function importResolutionIssuesIn(ctx, file2) {
6871
6915
  const { ts } = ctx;
6872
6916
  const sourceFile = parseSource(ctx, file2);
6873
6917
  if (!sourceFile) return [];
6874
- const missing = [];
6918
+ const issues = [];
6875
6919
  for (const statement of sourceFile.statements) {
6876
- let specifiers = [];
6877
- let specifier = null;
6878
- if (ts.isImportDeclaration(statement)) {
6879
- const clause = statement.importClause;
6880
- const bindings = clause && !clause.isTypeOnly ? clause.namedBindings : void 0;
6881
- if (bindings && ts.isNamedImports(bindings)) {
6882
- specifiers = bindings.elements;
6883
- specifier = statement.moduleSpecifier.text;
6884
- }
6885
- } else if (ts.isExportDeclaration(statement) && statement.moduleSpecifier && !statement.isTypeOnly && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
6886
- specifiers = statement.exportClause.elements;
6887
- specifier = statement.moduleSpecifier.text;
6888
- }
6889
- if (!specifier) continue;
6890
- const target = resolveRelativeModule(ctx, file2, specifier);
6891
- if (!target) continue;
6892
- const exported = exportNamesOf(ctx, target);
6920
+ const reference = valueReferenceOf(ts, statement);
6921
+ if (!reference) continue;
6922
+ const specifier = reference.specifier.text;
6923
+ const resolution = resolveRelativeModule(ctx, file2, specifier);
6924
+ if (resolution.status === "unresolved") {
6925
+ issues.push({ kind: "unresolvedModule", file: file2, ...positionOf(sourceFile, reference.specifier), specifier });
6926
+ continue;
6927
+ }
6928
+ if (resolution.status !== "resolved") continue;
6929
+ const exported = exportNamesOf(ctx, resolution.file);
6893
6930
  if (!exported) continue;
6894
- for (const element of specifiers) {
6895
- if (element.isTypeOnly) continue;
6931
+ for (const element of reference.elements) {
6896
6932
  const nameNode = element.propertyName ?? element.name;
6897
6933
  const name2 = nameNode.text;
6898
6934
  if (exported.has(name2)) continue;
6899
- const position = sourceFile.getLineAndCharacterOfPosition(nameNode.getStart(sourceFile));
6900
- missing.push({ file: file2, line: position.line + 1, column: position.character, name: name2, target });
6935
+ issues.push({
6936
+ kind: "missingExport",
6937
+ file: file2,
6938
+ ...positionOf(sourceFile, nameNode),
6939
+ name: name2,
6940
+ target: resolution.file
6941
+ });
6901
6942
  }
6902
6943
  }
6903
- return missing;
6944
+ return issues;
6904
6945
  }
6905
6946
  function isProjectSource(file2, projectRoot) {
6906
6947
  return file2.startsWith(`${projectRoot}${sep2}`) && !file2.split(sep2).includes("node_modules") && SCRIPT_FILE.test(file2);
@@ -6908,7 +6949,7 @@ function isProjectSource(file2, projectRoot) {
6908
6949
  function hasProjectTypeScript(projectRootInput) {
6909
6950
  return loadProjectTypeScript(resolve10(projectRootInput)) !== null;
6910
6951
  }
6911
- function findMissingNamedImports(inputFiles, projectRootInput) {
6952
+ function findImportResolutionIssues(inputFiles, projectRootInput) {
6912
6953
  const projectRoot = resolve10(projectRootInput);
6913
6954
  const ts = loadProjectTypeScript(projectRoot);
6914
6955
  if (!ts) return [];
@@ -6923,17 +6964,20 @@ function findMissingNamedImports(inputFiles, projectRootInput) {
6923
6964
  exportCache: /* @__PURE__ */ new Map()
6924
6965
  };
6925
6966
  try {
6926
- const missing = [];
6967
+ const issues = [];
6927
6968
  for (const file2 of inputFiles) {
6928
- if (isProjectSource(file2, projectRoot)) missing.push(...missingNamedImportsIn(ctx, file2));
6969
+ if (isProjectSource(file2, projectRoot)) issues.push(...importResolutionIssuesIn(ctx, file2));
6929
6970
  }
6930
- return missing;
6971
+ return issues;
6931
6972
  } catch {
6932
6973
  return [];
6933
6974
  }
6934
6975
  }
6935
- function formatMissingNamedImports(missing, projectRoot) {
6936
- return missing.map((item) => {
6976
+ function formatImportResolutionIssues(issues, projectRoot) {
6977
+ return issues.map((item) => {
6978
+ if (item.kind === "unresolvedModule") {
6979
+ return `${item.file}:${item.line}:${item.column}: ERROR: Could not resolve "${item.specifier}"`;
6980
+ }
6937
6981
  const target = relative4(resolve10(projectRoot), item.target).split(sep2).join("/");
6938
6982
  return `${item.file}:${item.line}:${item.column}: ERROR: No matching export in "${target}" for import "${item.name}"`;
6939
6983
  });
@@ -7069,7 +7113,7 @@ async function transpileTypescriptForNodeDefault(entryPath, context) {
7069
7113
  }
7070
7114
  };
7071
7115
  }
7072
- var MISSING_EXPORT_DIAGNOSTIC = /No matching export in "/u;
7116
+ var IMPORT_RESOLUTION_DIAGNOSTIC = /No matching export in "|Could not resolve "/u;
7073
7117
  var NAMED_IMPORT_CHECK_SKIPPED_MESSAGE = "Warning: codegen skipped the named-import check because this project has no typescript package. Install typescript in the project (for example: npm install -D typescript) and rerun codegen.";
7074
7118
  function defaultWarn(message) {
7075
7119
  process.stderr.write(`${message}
@@ -7098,15 +7142,15 @@ async function assertNamedImportsResolve(input2) {
7098
7142
  inputFiles = bundledInputFiles(await build({ ...esbuildEntryOptions(input2.appEntryAbs), write: false }));
7099
7143
  } catch (error62) {
7100
7144
  const details = error62 instanceof Error ? error62.message : String(error62);
7101
- if (input2.runtime === "bun" && !MISSING_EXPORT_DIAGNOSTIC.test(details)) return;
7145
+ if (input2.runtime === "bun" && !IMPORT_RESOLUTION_DIAGNOSTIC.test(details)) return;
7102
7146
  throw namedImportLoadFailure(input2.appEntryAbs, input2.runtime, [`Transpile error: ${details}`]);
7103
7147
  }
7104
7148
  }
7105
- const missing = findMissingNamedImports(inputFiles, input2.projectRoot);
7106
- if (missing.length > 0) {
7149
+ const issues = findImportResolutionIssues(inputFiles, input2.projectRoot);
7150
+ if (issues.length > 0) {
7107
7151
  throw namedImportLoadFailure(input2.appEntryAbs, input2.runtime, [
7108
- `Transpile error: Build failed with ${missing.length} error${missing.length === 1 ? "" : "s"}:`,
7109
- ...formatMissingNamedImports(missing, input2.projectRoot)
7152
+ `Transpile error: Build failed with ${issues.length} error${issues.length === 1 ? "" : "s"}:`,
7153
+ ...formatImportResolutionIssues(issues, input2.projectRoot)
7110
7154
  ]);
7111
7155
  }
7112
7156
  }
@@ -7223,10 +7267,10 @@ async function runCodegen2(input2) {
7223
7267
 
7224
7268
  // ../shared/src/analyzer/consumers/doctor/run-app-doctor.ts
7225
7269
  import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync9, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
7226
- import { dirname as dirname9, resolve as resolve16 } from "path";
7270
+ import { dirname as dirname10, resolve as resolve16 } from "path";
7227
7271
 
7228
7272
  // ../shared/src/analyzer/shared/deprecated-api-fix-plugin.ts
7229
- import { dirname as dirname4, relative as relative5 } from "path";
7273
+ import { dirname as dirname5, relative as relative5 } from "path";
7230
7274
  var DEPRECATED_CORE_IMPORTS = {
7231
7275
  query: {
7232
7276
  code: "DOC_DEPRECATED_QUERY_API",
@@ -7279,7 +7323,7 @@ function stripExtension(pathValue) {
7279
7323
  return pathValue.replace(/\.[^.\/]+$/, "");
7280
7324
  }
7281
7325
  function toImportSpecifier2(fromFile, targetFile) {
7282
- const fromDir = dirname4(fromFile);
7326
+ const fromDir = dirname5(fromFile);
7283
7327
  const rel = relative5(fromDir, stripExtension(targetFile)).replace(/\\/g, "/");
7284
7328
  if (!rel || rel === ".") return "./ai";
7285
7329
  return rel.startsWith(".") ? rel : `./${rel}`;
@@ -7418,17 +7462,17 @@ function createDeprecatedApiFixPlugin() {
7418
7462
  import { readFileSync as readFileSync8 } from "fs";
7419
7463
 
7420
7464
  // ../shared/src/analyzer/adapters/app-schema-graph.ts
7421
- import { basename, dirname as dirname6, join as join9, resolve as resolve13 } from "path";
7465
+ import { basename, dirname as dirname7, join as join9, resolve as resolve13 } from "path";
7422
7466
  import { existsSync as existsSync7, readFileSync as readFileSync5 } from "fs";
7423
7467
 
7424
7468
  // ../shared/src/analyzer/internal/source-files.ts
7425
- import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync3 } from "fs";
7426
- import { dirname as dirname5, join as join8, relative as relative6, resolve as resolve12 } from "path";
7469
+ import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync4 } from "fs";
7470
+ import { dirname as dirname6, join as join8, relative as relative6, resolve as resolve12 } from "path";
7427
7471
  var SOURCE_FILE_EXTENSIONS2 = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"];
7428
7472
  function findSourceFiles(dir) {
7429
7473
  if (!existsSync6(dir)) return [];
7430
7474
  try {
7431
- if (statSync3(dir).isFile()) {
7475
+ if (statSync4(dir).isFile()) {
7432
7476
  return /\.(?:[cm]?[jt]sx?)$/.test(dir) ? [dir] : [];
7433
7477
  }
7434
7478
  } catch {
@@ -7487,7 +7531,7 @@ function findStaticRelativeImports(filePath) {
7487
7531
  }
7488
7532
  function resolveRelativeModule2(fromPath, specifier) {
7489
7533
  if (!specifier.startsWith(".")) return null;
7490
- const base = resolve12(dirname5(fromPath), specifier);
7534
+ const base = resolve12(dirname6(fromPath), specifier);
7491
7535
  return resolveSourceFileCandidate(base);
7492
7536
  }
7493
7537
  function toProjectPath(projectRootAbs, absPath) {
@@ -7573,7 +7617,7 @@ function parseJsoncObject(filePath) {
7573
7617
  }
7574
7618
  function resolveTsConfigExtendsPath(configFile, extendsValue) {
7575
7619
  if (!extendsValue.startsWith(".") && !extendsValue.startsWith("/")) return null;
7576
- const configDir = dirname5(configFile);
7620
+ const configDir = dirname6(configFile);
7577
7621
  const rawPath = extendsValue.startsWith("/") ? extendsValue : resolve12(configDir, extendsValue);
7578
7622
  const candidates = rawPath.endsWith(".json") ? [rawPath] : [rawPath, `${rawPath}.json`, join8(rawPath, "tsconfig.json")];
7579
7623
  return candidates.find((candidate) => existsSync6(candidate)) ?? null;
@@ -7627,7 +7671,7 @@ function findNearestProjectConfigFiles(startDir) {
7627
7671
  }
7628
7672
  } catch {
7629
7673
  }
7630
- const parentDir = dirname5(currentDir);
7674
+ const parentDir = dirname6(currentDir);
7631
7675
  if (parentDir === currentDir) break;
7632
7676
  currentDir = parentDir;
7633
7677
  }
@@ -7648,9 +7692,9 @@ function substituteTsconfigPathTarget(target, wildcardValue) {
7648
7692
  return target.replace("*", wildcardValue);
7649
7693
  }
7650
7694
  function resolveTsconfigAliasImportFile(importerFile, specifier) {
7651
- for (const configFile of findNearestProjectConfigFiles(dirname5(importerFile))) {
7695
+ for (const configFile of findNearestProjectConfigFiles(dirname6(importerFile))) {
7652
7696
  const compilerOptions = loadTsConfigCompilerOptions(configFile);
7653
- const configDir = dirname5(configFile);
7697
+ const configDir = dirname6(configFile);
7654
7698
  const baseDir = compilerOptions.baseUrl ? resolve12(configDir, compilerOptions.baseUrl) : configDir;
7655
7699
  for (const [pattern, targets] of Object.entries(compilerOptions.paths ?? {})) {
7656
7700
  const wildcardValue = matchTsconfigPathPattern(specifier, pattern);
@@ -7702,7 +7746,7 @@ function collectReachableSourceFiles(entryPoint) {
7702
7746
  }
7703
7747
  function resolveSourceEntrypoint(basePath) {
7704
7748
  try {
7705
- if (existsSync6(basePath) && statSync3(basePath).isFile() && /\.(?:[cm]?[jt]sx?)$/.test(basePath)) {
7749
+ if (existsSync6(basePath) && statSync4(basePath).isFile() && /\.(?:[cm]?[jt]sx?)$/.test(basePath)) {
7706
7750
  return basePath;
7707
7751
  }
7708
7752
  } catch {
@@ -7846,9 +7890,9 @@ function resolveSchemaAuthGeneratedTarget(schemaAuthPathAbs, source) {
7846
7890
  /(?:export|import)\s+[^;\n]*\bfrom\s+["']([^"']*schema-auth\.gen(?:\.[cm]?[jt]sx?)?)["']/m
7847
7891
  );
7848
7892
  if (!match) {
7849
- return resolve13(dirname6(schemaAuthPathAbs), "./generated/schema-auth.gen.ts");
7893
+ return resolve13(dirname7(schemaAuthPathAbs), "./generated/schema-auth.gen.ts");
7850
7894
  }
7851
- return resolve13(dirname6(schemaAuthPathAbs), match[1]);
7895
+ return resolve13(dirname7(schemaAuthPathAbs), match[1]);
7852
7896
  }
7853
7897
  function classifySchemaSourceKind(pathValue) {
7854
7898
  const normalized = pathValue.replace(/\\/g, "/");
@@ -7884,14 +7928,14 @@ function dedupeOwners(owners) {
7884
7928
  }
7885
7929
 
7886
7930
  // ../shared/src/analyzer/adapters/app-project.ts
7887
- import { existsSync as existsSync8, statSync as statSync4 } from "fs";
7888
- import { dirname as dirname7, isAbsolute as isAbsolute3, resolve as resolve14 } from "path";
7931
+ import { existsSync as existsSync8, statSync as statSync5 } from "fs";
7932
+ import { dirname as dirname8, isAbsolute as isAbsolute3, resolve as resolve14 } from "path";
7889
7933
  function resolveAppProject(input2) {
7890
7934
  const projectRootAbs = resolve14(input2.projectRoot);
7891
7935
  const rootDir = input2.rootDir ?? input2.functionsDir ?? "gencow";
7892
7936
  const functionsDirAbs = isAbsolute3(rootDir) ? rootDir : resolve14(projectRootAbs, rootDir);
7893
7937
  const entryPointAbs = resolveSourceEntrypoint(functionsDirAbs);
7894
- const sourceBaseAbs = isExistingDirectory(functionsDirAbs) ? functionsDirAbs : dirname7(entryPointAbs);
7938
+ const sourceBaseAbs = isExistingDirectory(functionsDirAbs) ? functionsDirAbs : dirname8(entryPointAbs);
7895
7939
  const sourceFilesAbs = existsSync8(entryPointAbs) ? collectReachableSourceFiles(entryPointAbs) : isExistingDirectory(functionsDirAbs) ? findSourceFiles(functionsDirAbs) : [];
7896
7940
  const serverCodegenDirAbs = resolveServerCodegenDirAbs(
7897
7941
  projectRootAbs,
@@ -7920,7 +7964,7 @@ function resolveAppProject(input2) {
7920
7964
  }
7921
7965
  function isExistingDirectory(pathValue) {
7922
7966
  try {
7923
- return statSync4(pathValue).isDirectory();
7967
+ return statSync5(pathValue).isDirectory();
7924
7968
  } catch {
7925
7969
  return false;
7926
7970
  }
@@ -8402,7 +8446,7 @@ function createSourcePatternsPlugin() {
8402
8446
 
8403
8447
  // ../shared/src/analyzer/consumers/auditor/source-auditor.ts
8404
8448
  import { existsSync as existsSync9 } from "fs";
8405
- import { basename as basename3, dirname as dirname8, extname, resolve as resolve15 } from "path";
8449
+ import { basename as basename3, dirname as dirname9, extname, resolve as resolve15 } from "path";
8406
8450
 
8407
8451
  // ../shared/src/analyzer/consumers/auditor/source-auditor-shared.ts
8408
8452
  import { readFileSync as readFileSync7 } from "fs";
@@ -8580,7 +8624,7 @@ function describeAnalyzerFunctionsLabel(entryPoint) {
8580
8624
  const normalized = entryPoint.replace(/\\/g, "/");
8581
8625
  const fileName = normalized.split("/").pop() ?? normalized;
8582
8626
  if (/^index\.[cm]?[jt]sx?$/.test(fileName)) {
8583
- return `${basename3(dirname8(normalized))}/`;
8627
+ return `${basename3(dirname9(normalized))}/`;
8584
8628
  }
8585
8629
  return extname(fileName) ? fileName : `${fileName}/`;
8586
8630
  }
@@ -9525,7 +9569,7 @@ function validateNonOverlappingReplaceEdits(source, edits) {
9525
9569
  }
9526
9570
  }
9527
9571
  function ensureParentDir(pathValue) {
9528
- mkdirSync3(dirname9(pathValue), { recursive: true });
9572
+ mkdirSync3(dirname10(pathValue), { recursive: true });
9529
9573
  }
9530
9574
  function formatPatchTimestamp(now = /* @__PURE__ */ new Date()) {
9531
9575
  return now.toISOString();
@@ -1,26 +1,41 @@
1
+ import { statSync } from "node:fs";
1
2
  import { createRequire } from "node:module";
2
- import { join, relative, resolve, sep } from "node:path";
3
+ import { dirname, join, relative, resolve, sep } from "node:path";
3
4
 
4
- // esbuild drops an unused import of a missing name without a diagnostic, and it only
5
- // warns for namespace member access. Codegen would then load a backend that names an
6
- // export its module does not have. This check runs after esbuild bundles the entry and before
7
- // the module is imported, on every runtime, over the project's own sources, and only for relative
8
- // named imports and re-exports. It reads
9
- // the ASTs with the user project's `typescript` (the CLI does not depend on it), so the
10
- // AST nodes are not statically typed here.
5
+ // esbuild drops an unused import without resolving it, so a missing module or a missing name
6
+ // in an unused import produces no diagnostic. Codegen would then load a backend that imports
7
+ // something that is not there. This check runs after esbuild bundles the entry and before
8
+ // the module is imported, on every runtime, over the project's own sources. For every value
9
+ // import and export-from (named, default, namespace, export-star, or side-effect), it reports:
10
+ // - a relative specifier that does not resolve to a file, and
11
+ // - a named import or re-export whose target module does not export the name.
12
+ // `import type`, `export type`, and specifiers whose names are all type-only are skipped.
13
+ // Bare and `node:`/`bun:` specifiers are not checked. It reads the ASTs with the user project's
14
+ // `typescript` (the CLI does not depend on it), so the AST nodes are not statically typed here.
11
15
 
12
16
  const SCRIPT_FILE = /\.(?:[cm]?[jt]sx?)$/u;
13
17
  const TYPESCRIPT_FILE = /\.(?:[cm]?tsx?)$/u;
14
18
  const RELATIVE_SPECIFIER = /^\.{1,2}\//u;
15
19
  const DECLARATION_FILE = /\.d\.[cm]?ts$/u;
20
+ // Extensions esbuild resolves for a relative path without one, tried after TypeScript's own lookup.
21
+ const FALLBACK_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".json", ".css"];
16
22
 
17
- export type MissingNamedImport = {
18
- file: string;
19
- line: number;
20
- column: number;
21
- name: string;
22
- target: string;
23
- };
23
+ export type ImportResolutionIssue =
24
+ | {
25
+ kind: "missingExport";
26
+ file: string;
27
+ line: number;
28
+ column: number;
29
+ name: string;
30
+ target: string;
31
+ }
32
+ | {
33
+ kind: "unresolvedModule";
34
+ file: string;
35
+ line: number;
36
+ column: number;
37
+ specifier: string;
38
+ };
24
39
 
25
40
  type Context = {
26
41
  ts: any;
@@ -29,6 +44,13 @@ type Context = {
29
44
  exportCache: Map<string, Set<string> | null>;
30
45
  };
31
46
 
47
+ // `resolved` carries the file to read names from; `unresolved` is a relative path that does not
48
+ // exist; `skipped` covers a specifier this check does not judge (a `.d.ts` target or an existing asset).
49
+ type Resolution = { status: "resolved"; file: string } | { status: "unresolved" } | { status: "skipped" };
50
+
51
+ // A value import or export-from: the module specifier and the value names (named imports or re-exports) to check.
52
+ type ValueReference = { specifier: any; elements: any[] };
53
+
32
54
  // The project's typescript is the one the user compiles with. A missing or unusable copy
33
55
  // skips the check, so an unusual project is never blocked by the CLI.
34
56
  function loadProjectTypeScript(projectRoot: string): any | null {
@@ -43,19 +65,37 @@ function loadProjectTypeScript(projectRoot: string): any | null {
43
65
  }
44
66
  }
45
67
 
68
+ function isFile(path: string): boolean {
69
+ try {
70
+ return statSync(path).isFile();
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ // TypeScript resolves most relative paths. This covers what it does not: an exact-path asset such as
77
+ // `./data.json` or `./query.sql`, and any extension or directory index esbuild resolves on its own.
78
+ function existsOnDisk(fromFile: string, specifier: string): boolean {
79
+ const base = resolve(dirname(fromFile), specifier);
80
+ if (isFile(base)) return true;
81
+ return FALLBACK_EXTENSIONS.some((ext) => isFile(`${base}${ext}`) || isFile(join(base, `index${ext}`)));
82
+ }
83
+
46
84
  // A `.d.ts` target is skipped: TypeScript prefers it over a sibling `.js` that esbuild
47
85
  // bundles, so a stale declaration file would report names the real module does export.
48
- function resolveRelativeModule(ctx: Context, fromFile: string, specifier: string): string | null {
49
- if (!RELATIVE_SPECIFIER.test(specifier)) return null;
86
+ function resolveRelativeModule(ctx: Context, fromFile: string, specifier: string): Resolution {
87
+ if (!RELATIVE_SPECIFIER.test(specifier)) return { status: "skipped" };
50
88
  const resolved = ctx.ts.resolveModuleName(
51
89
  specifier,
52
90
  fromFile,
53
91
  ctx.compilerOptions,
54
92
  ctx.ts.sys,
55
93
  ).resolvedModule;
56
- if (!resolved || resolved.isExternalLibraryImport) return null;
57
- if (DECLARATION_FILE.test(resolved.resolvedFileName)) return null;
58
- return resolved.resolvedFileName;
94
+ if (resolved && !resolved.isExternalLibraryImport) {
95
+ if (DECLARATION_FILE.test(resolved.resolvedFileName)) return { status: "skipped" };
96
+ return { status: "resolved", file: resolved.resolvedFileName };
97
+ }
98
+ return existsOnDisk(fromFile, specifier) ? { status: "skipped" } : { status: "unresolved" };
59
99
  }
60
100
 
61
101
  // `null` when the file cannot be read, so the caller skips it instead of parsing empty text.
@@ -104,8 +144,8 @@ function collectExportNames(ctx: Context, file: string): Set<string> | null {
104
144
  const clause = statement.exportClause;
105
145
  if (!clause) {
106
146
  // `export * from "pkg"` or an unresolved path leaves the names unknown.
107
- const target = resolveRelativeModule(ctx, file, statement.moduleSpecifier.text);
108
- const inner = target ? exportNamesOf(ctx, target) : null;
147
+ const resolution = resolveRelativeModule(ctx, file, statement.moduleSpecifier.text);
148
+ const inner = resolution.status === "resolved" ? exportNamesOf(ctx, resolution.file) : null;
109
149
  if (!inner) return null;
110
150
  for (const name of inner) if (name !== "default") names.add(name);
111
151
  } else if (ts.isNamespaceExport(clause)) {
@@ -132,47 +172,71 @@ function collectExportNames(ctx: Context, file: string): Set<string> | null {
132
172
  return names;
133
173
  }
134
174
 
135
- function missingNamedImportsIn(ctx: Context, file: string): MissingNamedImport[] {
175
+ // Returns the value form of an import or export-from, or null when the statement carries no value
176
+ // (`import type`, `export type`, or a statement whose every named binding is `type`-marked).
177
+ // `import "x"` and `import {} from "x"` are side-effect imports, so they are value forms.
178
+ function valueReferenceOf(ts: any, statement: any): ValueReference | null {
179
+ if (ts.isImportDeclaration(statement)) {
180
+ const clause = statement.importClause;
181
+ if (!clause) return { specifier: statement.moduleSpecifier, elements: [] };
182
+ if (clause.isTypeOnly) return null;
183
+ const bindings = clause.namedBindings;
184
+ if (bindings && ts.isNamedImports(bindings)) {
185
+ const elements = bindings.elements.filter((element: any) => !element.isTypeOnly);
186
+ if (!clause.name && bindings.elements.length > 0 && elements.length === 0) return null;
187
+ return { specifier: statement.moduleSpecifier, elements };
188
+ }
189
+ return { specifier: statement.moduleSpecifier, elements: [] };
190
+ }
191
+ if (ts.isExportDeclaration(statement) && statement.moduleSpecifier && !statement.isTypeOnly) {
192
+ const clause = statement.exportClause;
193
+ if (clause && ts.isNamedExports(clause)) {
194
+ const elements = clause.elements.filter((element: any) => !element.isTypeOnly);
195
+ if (clause.elements.length > 0 && elements.length === 0) return null;
196
+ return { specifier: statement.moduleSpecifier, elements };
197
+ }
198
+ return { specifier: statement.moduleSpecifier, elements: [] };
199
+ }
200
+ return null;
201
+ }
202
+
203
+ // 0-based column like esbuild's, so every diagnostic in one output uses the same convention.
204
+ function positionOf(sourceFile: any, node: any): { line: number; column: number } {
205
+ const position = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
206
+ return { line: position.line + 1, column: position.character };
207
+ }
208
+
209
+ function importResolutionIssuesIn(ctx: Context, file: string): ImportResolutionIssue[] {
136
210
  const { ts } = ctx;
137
211
  const sourceFile = parseSource(ctx, file);
138
212
  if (!sourceFile) return [];
139
- const missing: MissingNamedImport[] = [];
213
+ const issues: ImportResolutionIssue[] = [];
140
214
  for (const statement of sourceFile.statements) {
141
- let specifiers: any[] = [];
142
- let specifier: string | null = null;
143
- if (ts.isImportDeclaration(statement)) {
144
- const clause = statement.importClause;
145
- const bindings = clause && !clause.isTypeOnly ? clause.namedBindings : undefined;
146
- if (bindings && ts.isNamedImports(bindings)) {
147
- specifiers = bindings.elements;
148
- specifier = statement.moduleSpecifier.text;
149
- }
150
- } else if (
151
- ts.isExportDeclaration(statement) &&
152
- statement.moduleSpecifier &&
153
- !statement.isTypeOnly &&
154
- statement.exportClause &&
155
- ts.isNamedExports(statement.exportClause)
156
- ) {
157
- specifiers = statement.exportClause.elements;
158
- specifier = statement.moduleSpecifier.text;
215
+ const reference = valueReferenceOf(ts, statement);
216
+ if (!reference) continue;
217
+ const specifier: string = reference.specifier.text;
218
+ const resolution = resolveRelativeModule(ctx, file, specifier);
219
+ if (resolution.status === "unresolved") {
220
+ issues.push({ kind: "unresolvedModule", file, ...positionOf(sourceFile, reference.specifier), specifier });
221
+ continue;
159
222
  }
160
- if (!specifier) continue;
161
- const target = resolveRelativeModule(ctx, file, specifier);
162
- if (!target) continue;
163
- const exported = exportNamesOf(ctx, target);
223
+ if (resolution.status !== "resolved") continue;
224
+ const exported = exportNamesOf(ctx, resolution.file);
164
225
  if (!exported) continue;
165
- for (const element of specifiers) {
166
- if (element.isTypeOnly) continue;
226
+ for (const element of reference.elements) {
167
227
  const nameNode = element.propertyName ?? element.name;
168
- const name = nameNode.text;
228
+ const name: string = nameNode.text;
169
229
  if (exported.has(name)) continue;
170
- const position = sourceFile.getLineAndCharacterOfPosition(nameNode.getStart(sourceFile));
171
- // Column is 0-based like esbuild's, so both diagnostics in one output use the same convention.
172
- missing.push({ file, line: position.line + 1, column: position.character, name, target });
230
+ issues.push({
231
+ kind: "missingExport",
232
+ file,
233
+ ...positionOf(sourceFile, nameNode),
234
+ name,
235
+ target: resolution.file,
236
+ });
173
237
  }
174
238
  }
175
- return missing;
239
+ return issues;
176
240
  }
177
241
 
178
242
  function isProjectSource(file: string, projectRoot: string): boolean {
@@ -188,12 +252,13 @@ export function hasProjectTypeScript(projectRootInput: string): boolean {
188
252
  return loadProjectTypeScript(resolve(projectRootInput)) !== null;
189
253
  }
190
254
 
191
- // `inputFiles` are the files esbuild bundled (absolute paths). Returns every relative named
192
- // import whose target module does not export the name. Any internal failure skips the check.
193
- export function findMissingNamedImports(
255
+ // `inputFiles` are the files esbuild bundled (absolute paths). Returns every value import or
256
+ // export-from in those files whose relative specifier does not resolve, and every named binding
257
+ // whose target module does not export the name. Any internal failure skips the check.
258
+ export function findImportResolutionIssues(
194
259
  inputFiles: readonly string[],
195
260
  projectRootInput: string,
196
- ): MissingNamedImport[] {
261
+ ): ImportResolutionIssue[] {
197
262
  const projectRoot = resolve(projectRootInput);
198
263
  const ts = loadProjectTypeScript(projectRoot);
199
264
  if (!ts) return [];
@@ -208,22 +273,25 @@ export function findMissingNamedImports(
208
273
  exportCache: new Map(),
209
274
  };
210
275
  try {
211
- const missing: MissingNamedImport[] = [];
276
+ const issues: ImportResolutionIssue[] = [];
212
277
  for (const file of inputFiles) {
213
- if (isProjectSource(file, projectRoot)) missing.push(...missingNamedImportsIn(ctx, file));
278
+ if (isProjectSource(file, projectRoot)) issues.push(...importResolutionIssuesIn(ctx, file));
214
279
  }
215
- return missing;
280
+ return issues;
216
281
  } catch {
217
282
  return [];
218
283
  }
219
284
  }
220
285
 
221
286
  // Formats each finding like an esbuild diagnostic, so the classifier reads it the same way.
222
- export function formatMissingNamedImports(
223
- missing: readonly MissingNamedImport[],
287
+ export function formatImportResolutionIssues(
288
+ issues: readonly ImportResolutionIssue[],
224
289
  projectRoot: string,
225
290
  ): string[] {
226
- return missing.map((item) => {
291
+ return issues.map((item) => {
292
+ if (item.kind === "unresolvedModule") {
293
+ return `${item.file}:${item.line}:${item.column}: ERROR: Could not resolve "${item.specifier}"`;
294
+ }
227
295
  const target = relative(resolve(projectRoot), item.target).split(sep).join("/");
228
296
  return `${item.file}:${item.line}:${item.column}: ERROR: No matching export in "${target}" for import "${item.name}"`;
229
297
  });
@@ -11,8 +11,8 @@ import {
11
11
  extractTables,
12
12
  } from "../../shared/src/codegen/index.ts";
13
13
  import {
14
- findMissingNamedImports,
15
- formatMissingNamedImports,
14
+ findImportResolutionIssues,
15
+ formatImportResolutionIssues,
16
16
  hasProjectTypeScript,
17
17
  } from "./codegen-named-import-check.ts";
18
18
  import {
@@ -172,7 +172,7 @@ async function transpileTypescriptForNodeDefault(
172
172
  };
173
173
  }
174
174
 
175
- const MISSING_EXPORT_DIAGNOSTIC = /No matching export in "/u;
175
+ const IMPORT_RESOLUTION_DIAGNOSTIC = /No matching export in "|Could not resolve "/u;
176
176
 
177
177
  const NAMED_IMPORT_CHECK_SKIPPED_MESSAGE =
178
178
  "Warning: codegen skipped the named-import check because this project has no typescript package. " +
@@ -217,18 +217,19 @@ async function assertNamedImportsResolve(input: {
217
217
  } catch (error) {
218
218
  const details = error instanceof Error ? error.message : String(error);
219
219
  // Bun can run inputs esbuild rejects (for example `with { type: "text" }`). On bun those failures
220
- // skip the check and bun's loader reports any real error. A missing import in such a backend is
221
- // not caught here. A missing-export diagnostic is still reported, since it is this check's domain.
220
+ // skip the check and bun's loader reports any real error. Unresolved imports and missing exports
221
+ // are still reported, since they are this check's domain: esbuild keeps some unused imports
222
+ // (`export *`, `export { x } from`, side-effect imports) and fails on them with a location.
222
223
  // On node the transpile already failed above, so this branch is bun-only in practice.
223
- if (input.runtime === "bun" && !MISSING_EXPORT_DIAGNOSTIC.test(details)) return;
224
+ if (input.runtime === "bun" && !IMPORT_RESOLUTION_DIAGNOSTIC.test(details)) return;
224
225
  throw namedImportLoadFailure(input.appEntryAbs, input.runtime, [`Transpile error: ${details}`]);
225
226
  }
226
227
  }
227
- const missing = findMissingNamedImports(inputFiles, input.projectRoot);
228
- if (missing.length > 0) {
228
+ const issues = findImportResolutionIssues(inputFiles, input.projectRoot);
229
+ if (issues.length > 0) {
229
230
  throw namedImportLoadFailure(input.appEntryAbs, input.runtime, [
230
- `Transpile error: Build failed with ${missing.length} error${missing.length === 1 ? "" : "s"}:`,
231
- ...formatMissingNamedImports(missing, input.projectRoot),
231
+ `Transpile error: Build failed with ${issues.length} error${issues.length === 1 ? "" : "s"}:`,
232
+ ...formatImportResolutionIssues(issues, input.projectRoot),
232
233
  ]);
233
234
  }
234
235
  }