@prisma-next/cli 0.13.0-dev.9 → 0.14.0-dev.1
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.
- package/dist/cli.mjs +8 -8
- package/dist/cli.mjs.map +1 -1
- package/dist/commands/migration-check.mjs +1 -1
- package/dist/commands/migration-plan.mjs +1 -1
- package/dist/commands/migration-status.mjs +1 -1
- package/dist/{migration-check-VwM8xCZV.mjs → migration-check-soB5uZEQ.mjs} +1 -2
- package/dist/{migration-check-VwM8xCZV.mjs.map → migration-check-soB5uZEQ.mjs.map} +1 -1
- package/dist/migration-cli.mjs +3 -3
- package/dist/migration-cli.mjs.map +1 -1
- package/dist/{migration-plan-z5Ing-TD.mjs → migration-plan-W_E8FQOk.mjs} +2 -2
- package/dist/migration-plan-W_E8FQOk.mjs.map +1 -0
- package/dist/{migration-status-CD-LC2Ip.mjs → migration-status-CgWSoI_g.mjs} +1 -2
- package/dist/{migration-status-CD-LC2Ip.mjs.map → migration-status-CgWSoI_g.mjs.map} +1 -1
- package/package.json +18 -18
- package/src/commands/init/templates/code-templates.ts +4 -4
- package/src/commands/migration-plan.ts +1 -1
- package/src/migration-cli.ts +4 -4
- package/dist/migration-plan-z5Ing-TD.mjs.map +0 -1
package/dist/cli.mjs
CHANGED
|
@@ -9,13 +9,13 @@ import { createDbUpdateCommand } from "./commands/db-update.mjs";
|
|
|
9
9
|
import { t as createDbVerifyCommand } from "./db-verify-C24FKhb7.mjs";
|
|
10
10
|
import { t as createMigrationListCommand } from "./migration-list-DlJJ_38Z.mjs";
|
|
11
11
|
import { createMigrateCommand } from "./commands/migrate.mjs";
|
|
12
|
-
import { t as createMigrationCheckCommand } from "./migration-check-
|
|
12
|
+
import { t as createMigrationCheckCommand } from "./migration-check-soB5uZEQ.mjs";
|
|
13
13
|
import { createMigrationGraphCommand } from "./commands/migration-graph.mjs";
|
|
14
14
|
import { t as createMigrationLogCommand } from "./migration-log-CG0qQAFm.mjs";
|
|
15
15
|
import { createMigrationNewCommand } from "./commands/migration-new.mjs";
|
|
16
|
-
import { t as createMigrationPlanCommand } from "./migration-plan-
|
|
16
|
+
import { t as createMigrationPlanCommand } from "./migration-plan-W_E8FQOk.mjs";
|
|
17
17
|
import { createMigrationShowCommand } from "./commands/migration-show.mjs";
|
|
18
|
-
import { r as createMigrationStatusCommand } from "./migration-status-
|
|
18
|
+
import { r as createMigrationStatusCommand } from "./migration-status-CgWSoI_g.mjs";
|
|
19
19
|
import { createRefCommand } from "./commands/ref.mjs";
|
|
20
20
|
import { t as createTelemetryCommand } from "./telemetry-BIM4beEO.mjs";
|
|
21
21
|
import { Command } from "commander";
|
|
@@ -24,7 +24,7 @@ import { ensureInstallationId, readUserConfig, resolveGating, runTelemetry, user
|
|
|
24
24
|
import { distance } from "closest-match";
|
|
25
25
|
import { fileURLToPath } from "node:url";
|
|
26
26
|
//#region package.json
|
|
27
|
-
var version = "0.
|
|
27
|
+
var version = "0.14.0-dev.1";
|
|
28
28
|
//#endregion
|
|
29
29
|
//#region src/commands/init/templates/code-templates.ts
|
|
30
30
|
function targetPackageName(target) {
|
|
@@ -85,7 +85,7 @@ export const contract = defineContract(
|
|
|
85
85
|
models: {
|
|
86
86
|
User: model('User', {
|
|
87
87
|
fields: {
|
|
88
|
-
id: field.id.
|
|
88
|
+
id: field.id.uuidv7String(),
|
|
89
89
|
email: field.text().unique(),
|
|
90
90
|
username: field.text().optional(),
|
|
91
91
|
name: field.text().optional(),
|
|
@@ -173,7 +173,7 @@ export const contract = defineContract(
|
|
|
173
173
|
models: {
|
|
174
174
|
User: model('User', {
|
|
175
175
|
fields: {
|
|
176
|
-
id: field.id.
|
|
176
|
+
id: field.id.uuidv7String(),
|
|
177
177
|
email: field.text().unique(),
|
|
178
178
|
username: field.text().optional(),
|
|
179
179
|
name: field.text().optional(),
|
|
@@ -187,10 +187,10 @@ export const contract = defineContract(
|
|
|
187
187
|
|
|
188
188
|
Post: model('Post', {
|
|
189
189
|
fields: {
|
|
190
|
-
id: field.id.
|
|
190
|
+
id: field.id.uuidv7String(),
|
|
191
191
|
title: field.text(),
|
|
192
192
|
content: field.text().optional(),
|
|
193
|
-
authorId: field.
|
|
193
|
+
authorId: field.uuidString(),
|
|
194
194
|
createdAt: field.temporal.createdAt(),
|
|
195
195
|
updatedAt: field.temporal.updatedAt(),
|
|
196
196
|
},
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":["CLI_VERSION","packageJson.version"],"sources":["../package.json","../src/commands/init/templates/code-templates.ts","../src/commands/init/index.ts","../src/utils/suggest-command.ts","../src/utils/telemetry.ts","../src/cli.ts"],"sourcesContent":["","import { DEFAULT_CONTRACT_SOURCE_DIR } from '@prisma-next/config/config-types';\n\nexport type TargetId = 'postgres' | 'mongo';\nexport type AuthoringId = 'psl' | 'typescript';\n\nexport function targetPackageName(target: TargetId): string {\n return target === 'postgres' ? '@prisma-next/postgres' : '@prisma-next/mongo';\n}\n\nexport function targetLabel(target: TargetId): string {\n return target === 'postgres' ? 'PostgreSQL' : 'MongoDB';\n}\n\nexport function defaultSchemaPath(authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return `${DEFAULT_CONTRACT_SOURCE_DIR}/contract.ts`;\n }\n return `${DEFAULT_CONTRACT_SOURCE_DIR}/contract.prisma`;\n}\n\nexport function starterSchema(target: TargetId, authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return target === 'mongo' ? starterSchemaTsMongo() : starterSchemaTsPostgres();\n }\n return target === 'mongo' ? starterSchemaPslMongo() : starterSchemaPslPostgres();\n}\n\n/**\n * Renders a short authoring-appropriate schema sample (FR5.1) for embedding\n * in `prisma-next.md`. Returns a complete fenced markdown code block.\n *\n * The sample intentionally shows just one model: it's illustrative, not\n * a substitute for the full scaffolded contract file. The TS samples use\n * the same outer shape as `starterSchemaTs*` (FR5.3) so a user reading\n * the doc and the file side-by-side sees the same structure.\n */\nexport function schemaSample(target: TargetId, authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return target === 'mongo' ? schemaSampleTsMongo() : schemaSampleTsPostgres();\n }\n return target === 'mongo' ? schemaSamplePslMongo() : schemaSamplePslPostgres();\n}\n\nfunction schemaSamplePslPostgres(): string {\n return `\\`\\`\\`prisma\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n username String?\n name String?\n}\n\\`\\`\\``;\n}\n\nfunction schemaSamplePslMongo(): string {\n return `\\`\\`\\`prisma\nmodel User {\n id ObjectId @id @map(\"_id\")\n email String @unique\n username String?\n name String?\n @@map(\"users\")\n}\n\\`\\`\\``;\n}\n\nfunction schemaSampleTsPostgres(): string {\n return `\\`\\`\\`typescript\nimport { defineContract } from '@prisma-next/postgres/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model }) => ({\n models: {\n User: model('User', {\n fields: {\n id: field.id.uuidv7(),\n email: field.text().unique(),\n username: field.text().optional(),\n name: field.text().optional(),\n },\n }),\n },\n }),\n);\n\\`\\`\\``;\n}\n\nfunction schemaSampleTsMongo(): string {\n return `\\`\\`\\`typescript\nimport { defineContract } from '@prisma-next/mongo/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model }) => ({\n models: {\n User: model('User', {\n collection: 'users',\n fields: {\n _id: field.objectId(),\n email: field.string(),\n username: field.string().optional(),\n name: field.string().optional(),\n },\n }),\n },\n }),\n);\n\\`\\`\\``;\n}\n\nfunction starterSchemaPslPostgres(): string {\n return `// use prisma-next\n\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n username String?\n name String?\n posts Post[]\n createdAt DateTime @default(now())\n updatedAt temporal.updatedAt()\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n title String\n content String?\n author User @relation(fields: [authorId], references: [id])\n authorId Int\n createdAt DateTime @default(now())\n updatedAt temporal.updatedAt()\n}\n`;\n}\n\nfunction starterSchemaPslMongo(): string {\n return `// use prisma-next\n\nmodel User {\n id ObjectId @id @map(\"_id\")\n email String @unique\n username String?\n name String?\n posts Post[]\n @@map(\"users\")\n}\n\nmodel Post {\n id ObjectId @id @map(\"_id\")\n title String\n content String?\n author User @relation(fields: [authorId], references: [id])\n authorId ObjectId\n @@map(\"posts\")\n}\n`;\n}\n\nfunction starterSchemaTsPostgres(): string {\n return `import { defineContract } from '@prisma-next/postgres/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model, rel }) => ({\n models: {\n User: model('User', {\n fields: {\n id: field.id.uuidv7(),\n email: field.text().unique(),\n username: field.text().optional(),\n name: field.text().optional(),\n createdAt: field.temporal.createdAt(),\n updatedAt: field.temporal.updatedAt(),\n },\n relations: {\n posts: rel.hasMany('Post', { by: 'authorId' }),\n },\n }),\n\n Post: model('Post', {\n fields: {\n id: field.id.uuidv7(),\n title: field.text(),\n content: field.text().optional(),\n authorId: field.uuid(),\n createdAt: field.temporal.createdAt(),\n updatedAt: field.temporal.updatedAt(),\n },\n relations: {\n author: rel.belongsTo('User', { from: 'authorId', to: 'id' }),\n },\n }),\n },\n }),\n);\n`;\n}\n\nfunction starterSchemaTsMongo(): string {\n return `import { defineContract } from '@prisma-next/mongo/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model, rel }) => ({\n models: {\n User: model('User', {\n collection: 'users',\n fields: {\n _id: field.objectId(),\n email: field.string(),\n username: field.string().optional(),\n name: field.string().optional(),\n },\n relations: {\n posts: rel.hasMany('Post', { from: '_id', to: 'authorId' }),\n },\n }),\n\n Post: model('Post', {\n collection: 'posts',\n fields: {\n _id: field.objectId(),\n title: field.string(),\n content: field.string().optional(),\n authorId: field.objectId(),\n },\n relations: {\n author: rel.belongsTo('User', { from: 'authorId', to: '_id' }),\n },\n }),\n },\n }),\n);\n`;\n}\n\nexport function configFile(target: TargetId, contractPath: string): string {\n const pkg = targetPackageName(target);\n return `import 'dotenv/config';\nimport { defineConfig } from '${pkg}/config';\n\nexport default defineConfig({\n contract: ${JSON.stringify(contractPath)},\n db: {\n connection: process.env['DATABASE_URL']!,\n },\n});\n`;\n}\n\nexport function dbFile(target: TargetId): string {\n if (target === 'postgres') {\n return `import postgres from '@prisma-next/postgres/runtime';\nimport type { Contract } from './contract.d';\nimport contractJson from './contract.json' with { type: 'json' };\n\nexport const db = postgres<Contract>({\n contractJson,\n url: process.env['DATABASE_URL']!,\n});\n`;\n }\n\n return `import mongo from '@prisma-next/mongo/runtime';\nimport type { Contract } from './contract.d';\nimport contractJson from './contract.json' with { type: 'json' };\n\nexport const db = mongo<Contract>({\n contractJson,\n url: process.env['DATABASE_URL']!,\n});\n`;\n}\n","import { Command } from 'commander';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../../utils/command-helpers';\nimport {\n type CommonCommandOptions,\n deriveCanPrompt,\n parseGlobalFlagsOrExit,\n} from '../../utils/global-flags';\nimport {\n INIT_EXIT_EMIT_FAILED,\n INIT_EXIT_INSTALL_FAILED,\n INIT_EXIT_INTERNAL_ERROR,\n INIT_EXIT_OK,\n INIT_EXIT_PRECONDITION,\n INIT_EXIT_SKILL_INSTALL_FAILED,\n INIT_EXIT_USER_ABORTED,\n} from './exit-codes';\nimport { defaultSchemaPath } from './templates/code-templates';\n\n/**\n * Commander.js parsed options for `init`. The init-specific options live\n * alongside the inherited `CommonCommandOptions` global flags.\n *\n * `target` and `authoring` are typed as plain `string` here because\n * Commander.js does not enforce enums at parse time — the validation /\n * normalisation happens in `inputs.ts::resolveInitInputs`, which can\n * raise a structured `errorInitInvalidFlagValue` with the full set of\n * allowed values.\n */\ninterface InitCommandOptions extends CommonCommandOptions {\n readonly target?: string;\n readonly authoring?: string;\n readonly schemaPath?: string;\n readonly force?: boolean;\n readonly writeEnv?: boolean;\n readonly probeDb?: boolean;\n readonly strictProbe?: boolean;\n readonly install?: boolean;\n readonly skill?: boolean;\n}\n\nexport function createInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Initialize a new Prisma Next project',\n 'Scaffolds config, schema, and runtime files, installs dependencies,\\n' +\n 'and emits the contract. Gets you from zero to typed queries in one step.\\n' +\n '\\n' +\n 'Run interactively for a guided experience, or supply --target / --authoring\\n' +\n 'and --yes for a fully scriptable run (CI, AI coding agents, automation).\\n' +\n '\\n' +\n 'Exit codes (see CLI Style Guide § Exit Codes):\\n' +\n ` ${INIT_EXIT_OK} OK Init succeeded.\\n` +\n ` ${INIT_EXIT_INTERNAL_ERROR} INTERNAL_ERROR Unexpected bug in prisma-next (please report).\\n` +\n ` ${INIT_EXIT_PRECONDITION} PRECONDITION Bad flags / missing prerequisite (e.g. no package.json).\\n` +\n ` ${INIT_EXIT_USER_ABORTED} USER_ABORTED User cancelled an interactive prompt.\\n` +\n ` ${INIT_EXIT_INSTALL_FAILED} INSTALL_FAILED Dependency installation failed (init-specific).\\n` +\n ` ${INIT_EXIT_EMIT_FAILED} EMIT_FAILED \\`contract emit\\` failed after install (init-specific).\\n` +\n ` ${INIT_EXIT_SKILL_INSTALL_FAILED} SKILL_INSTALL_FAILED Agent-skill install failed (re-run with --no-skill to skip).`,\n );\n setCommandExamples(command, [\n 'prisma-next init',\n 'prisma-next init --yes --target postgres --authoring psl',\n 'prisma-next init --yes --target mongodb --authoring typescript --json',\n 'prisma-next init --yes --force --target postgres --authoring psl # overwrite an existing scaffold',\n 'prisma-next init --no-install # skip pnpm/npm install + emit',\n 'prisma-next init --no-skill # skip the skills install (air-gapped / restricted env)',\n ]);\n\n return addGlobalOptions(command)\n .option('--target <db>', 'Database target: postgres or mongodb')\n .option('--authoring <style>', 'Schema authoring style: psl or typescript')\n .option(\n '--schema-path <path>',\n `Where to write the starter schema (default: ${defaultSchemaPath('psl')})`,\n )\n .option('--force', 'Overwrite an existing scaffold without prompting')\n .option(\n '--write-env',\n 'Write a .env file from .env.example (gitignored; default: only .env.example)',\n )\n .option(\n '--probe-db',\n 'Connect to DATABASE_URL once and check the server version against the target minimum (opt-in; off by default)',\n )\n .option(\n '--strict-probe',\n 'Treat a failed --probe-db as fatal (no-op without --probe-db; init is offline-by-default)',\n )\n .option('--no-install', 'Skip dependency installation and contract emission')\n .option(\n '--no-skill',\n 'Skip Prisma Next skills install (air-gapped CI, restricted registries, etc.)',\n )\n .action(async (options: InitCommandOptions) => {\n const { runInit } = await import('./init');\n const flags = parseGlobalFlagsOrExit(options);\n const canPrompt = deriveCanPrompt({\n flagsInteractive: flags.interactive,\n optionInteractive: options.interactive,\n stdinIsTTY: Boolean(process.stdin.isTTY),\n });\n const exitCode = await runInit(process.cwd(), {\n options,\n flags,\n canPrompt,\n });\n process.exit(exitCode);\n });\n}\n","import { distance } from 'closest-match';\n\n/**\n * Suggests similar command names for a mistyped input.\n *\n * Uses Levenshtein distance to find close matches. Only suggests commands\n * within a reasonable distance threshold (40% of the input length, minimum 2).\n * Returns up to 3 suggestions in case of ties.\n *\n * @returns Array of suggested command names (empty if nothing is close enough).\n */\nexport function suggestCommands(input: string, candidates: readonly string[]): string[] {\n if (candidates.length === 0) return [];\n\n // Threshold: at most 40% of the input length (min 2) to avoid absurd suggestions\n const maxDistance = Math.max(2, Math.ceil(input.length * 0.4));\n\n const scored = candidates\n .map((name) => ({ name, dist: distance(input, name) }))\n .filter((entry) => entry.dist <= maxDistance)\n .sort((a, b) => a.dist - b.dist);\n\n if (scored.length === 0) return [];\n\n // Take the best distance, then include ties (up to 3)\n const bestDist = scored[0]!.dist;\n return scored\n .filter((entry) => entry.dist === bestDist)\n .slice(0, 3)\n .map((entry) => entry.name);\n}\n","import { fileURLToPath } from 'node:url';\nimport {\n type CommanderOptionShape,\n type CommanderResultShape,\n ensureInstallationId,\n readUserConfig,\n resolveGating,\n runTelemetry,\n type TelemetryRunOutcome,\n type UserConfig,\n userConfigPath,\n} from '@prisma-next/cli-telemetry';\nimport type { Command } from 'commander';\nimport { version as CLI_VERSION } from '../../package.json' with { type: 'json' };\nimport { isCI } from './is-ci';\n\ntype TelemetryGate =\n | { readonly enabled: true; readonly userConfig: UserConfig }\n | { readonly enabled: false; readonly outcome: TelemetryRunOutcome };\n\n/**\n * Resolve the commander command path from a leaf `Command`, walking up\n * the parent chain. Result is rooted at the program name and ends at\n * the leaf — `['prisma-next', 'migration', 'new']` for\n * `prisma-next migration new …`.\n */\nfunction commandPathFor(actionCommand: Command): string[] {\n const path: string[] = [];\n let cursor: Command | null = actionCommand;\n while (cursor !== null) {\n path.unshift(cursor.name());\n cursor = cursor.parent;\n }\n return path;\n}\n\nfunction commanderOptionSnapshots(actionCommand: Command): CommanderOptionShape[] {\n return actionCommand.options.map((option) => {\n const attributeName = option.attributeName();\n return {\n attributeName,\n longName: option.long ?? null,\n source: actionCommand.getOptionValueSource(attributeName) ?? null,\n };\n });\n}\n\n/**\n * Project commander's leaf `Command` into the wire-shape snapshot the\n * telemetry sanitiser consumes. Pure projection — no env, no I/O.\n */\nexport function commanderSnapshotForTelemetry(actionCommand: Command): CommanderResultShape {\n return {\n commandPath: commandPathFor(actionCommand),\n positionalArgs: actionCommand.args,\n options: commanderOptionSnapshots(actionCommand),\n };\n}\n\nfunction resolveTelemetryGate(): TelemetryGate {\n if (isCI()) {\n return { enabled: false, outcome: { spawned: false, reason: 'ci' } };\n }\n const userConfig = readUserConfig();\n const gating = resolveGating({ env: process.env, config: userConfig });\n if (!gating.enabled) {\n return { enabled: false, outcome: { spawned: false, reason: 'gated-off' } };\n }\n return { enabled: true, userConfig };\n}\n\n/**\n * Path to the compiled sender script inside `@prisma-next/cli-telemetry`'s\n * `dist/`. Resolved off this module's `import.meta.url` via the package\n * specifier `@prisma-next/cli-telemetry/sender`, so the consumer pays\n * no attention to internal package layout.\n */\nfunction senderPath(): string {\n return fileURLToPath(new URL(import.meta.resolve('@prisma-next/cli-telemetry/sender')));\n}\n\nfunction fireTelemetry(actionCommand: Command, userConfig: UserConfig): TelemetryRunOutcome {\n return runTelemetry({\n command: commanderSnapshotForTelemetry(actionCommand),\n version: CLI_VERSION,\n projectRoot: process.cwd(),\n senderPath: senderPath(),\n isCI: isCI(),\n env: process.env,\n userConfig,\n });\n}\n\n/**\n * preAction-stage entry point. Synchronous by construction: resolve\n * env/CI/user-consent gates (cheap, all in-memory and a single tiny\n * user-config read), then — only when enabled — `fork()` the detached\n * sender script. The forked child loads `prisma-next.config.*` via\n * c12 on its own (see `loadProjectConfig` in cli-telemetry); the\n * parent does no project-config I/O on the command's hot path.\n *\n * Privacy invariant: gate resolution always happens before any project\n * config touches disk. The child loading user TS code is acceptable\n * only because it's gated behind the same resolved-enabled signal.\n */\n/**\n * Builds the one-time first-run disclosure. The resolved absolute path to\n * the user-level config file is substituted in so the user can see exactly\n * which file to edit (it must not be confused with `prisma-next.config.ts`).\n * `prisma-next telemetry disable` is named as the primary, friendliest\n * opt-out, alongside the env vars and the config edit.\n */\nfunction firstRunNotice(configPath: string): string {\n return [\n 'Prisma Next collects anonymous CLI usage data, enabled by default.',\n \"What's collected and why: https://prisma-next.dev/docs/cli/telemetry.\",\n 'Opt out: run \"prisma-next telemetry disable\", set DO_NOT_TRACK=1 or',\n `PRISMA_NEXT_DISABLE_TELEMETRY=1, or set \"enableTelemetry\": false in ${configPath}.`,\n ].join(' ');\n}\n\n/**\n * Best-effort first-run disclosure + installationId mint. Runs only on the\n * gating-enabled path. Prints the notice to stderr (never stdout) and mints\n * a persistent id without touching `enableTelemetry`, so the opt-out default\n * stays intact and no unasked-for consent is recorded.\n *\n * Every step is wrapped so an un-writable config dir (or any other failure)\n * never throws and never blocks the command. Returns the minted (or\n * pre-existing) id so the caller can forward it to `runTelemetry` without a\n * redundant disk read. On mint failure it returns `undefined`: the notice may\n * reprint next run, and `runTelemetry` no-ops on the missing id.\n */\nfunction discloseAndMintOnFirstRun(): string | undefined {\n try {\n process.stderr.write(`${firstRunNotice(userConfigPath())}\\n`);\n } catch {}\n try {\n return ensureInstallationId();\n } catch {}\n return undefined;\n}\n\n/**\n * True when the run is the `telemetry` command (or one of its\n * subcommands). The usage-telemetry preAction fire is exempted for it:\n * it would be absurd for `telemetry disable` to send a usage event before\n * disabling, or for `telemetry status` to mint an id + send while merely\n * reporting state. This is the only command-specific exemption.\n *\n * The check is rooted at the program: the path must be\n * `['prisma-next', 'telemetry', …]`, so it matches the top-level\n * `telemetry` command and its subcommands without matching a hypothetical\n * nested `… telemetry` elsewhere.\n */\nfunction isTelemetryCommand(actionCommand: Command): boolean {\n return commandPathFor(actionCommand)[1] === 'telemetry';\n}\n\nexport function fireTelemetryFromPreAction(actionCommand: Command): TelemetryRunOutcome {\n if (isTelemetryCommand(actionCommand)) {\n return { spawned: false, reason: 'gated-off' };\n }\n const gate = resolveTelemetryGate();\n if (!gate.enabled) {\n return gate.outcome;\n }\n const storedId = gate.userConfig.installationId;\n if (typeof storedId !== 'string' || storedId.length === 0) {\n const installationId = discloseAndMintOnFirstRun();\n return fireTelemetry(\n actionCommand,\n installationId === undefined ? gate.userConfig : { ...gate.userConfig, installationId },\n );\n }\n return fireTelemetry(actionCommand, gate.userConfig);\n}\n","import { Command } from 'commander';\nimport packageJson from '../package.json' with { type: 'json' };\nimport { createContractEmitCommand } from './commands/contract-emit';\nimport { createContractInferCommand } from './commands/contract-infer';\nimport { createInitCommand } from './commands/init';\nimport { installShutdownHandlers } from './utils/shutdown';\n\n// Install SIGINT/SIGTERM handlers before anything else\ninstallShutdownHandlers();\n\nimport { createDbInitCommand } from './commands/db-init';\nimport { createDbSchemaCommand } from './commands/db-schema';\nimport { createDbSignCommand } from './commands/db-sign';\nimport { createDbUpdateCommand } from './commands/db-update';\nimport { createDbVerifyCommand } from './commands/db-verify';\nimport { createMigrateCommand } from './commands/migrate';\nimport { createMigrationCheckCommand } from './commands/migration-check';\nimport { createMigrationGraphCommand } from './commands/migration-graph';\nimport { createMigrationListCommand } from './commands/migration-list';\nimport { createMigrationLogCommand } from './commands/migration-log';\nimport { createMigrationNewCommand } from './commands/migration-new';\nimport { createMigrationPlanCommand } from './commands/migration-plan';\nimport { createMigrationShowCommand } from './commands/migration-show';\nimport { createMigrationStatusCommand } from './commands/migration-status';\nimport { createRefCommand } from './commands/ref';\nimport { createTelemetryCommand } from './commands/telemetry';\nimport { setCommandDescriptions } from './utils/command-helpers';\nimport { formatCommandHelp, formatRootHelp } from './utils/formatters/help';\nimport { parseGlobalFlags } from './utils/global-flags';\nimport { suggestCommands } from './utils/suggest-command';\nimport { fireTelemetryFromPreAction } from './utils/telemetry';\n\n/**\n * Lookup table mapping removed subcommands to their replacement verbs.\n * Keyed by `<parent>:<subcommand>` (e.g. `migration:apply`).\n * The handler consults this before falling back to the fuzzy suggest engine.\n */\nconst removedVerbRedirects: Record<string, string> = {\n 'migration:apply': 'Use `prisma-next migrate --to <contract>` instead.',\n 'migration:ref': 'Use `prisma-next ref set|list|delete` instead.',\n};\n\n/**\n * Removed flags on specific subcommands. Keyed by `<parent>:<sub>:<flag>`.\n * Checked during the pre-parse argv scan before commander sees the flags.\n */\nconst removedFlagRedirects: Record<string, string> = {\n 'migration:status:graph': 'Use `prisma-next migration graph` to view the migration graph.',\n 'migration:status:all':\n 'Use `prisma-next migration log --db <url>` to view the full execution history.',\n 'migration:status:limit':\n 'Use `prisma-next migration log --db <url>` to view the full execution history.',\n 'migration:status:ref': 'Use `--to <contract>` instead of `--ref`.',\n};\n\n/**\n * Formats the \"Did you mean ...?\" hint for an unknown command.\n */\nfunction formatSuggestion(input: string, candidates: readonly string[]): string {\n const suggestions = suggestCommands(\n input,\n candidates.map((c) => c),\n );\n if (suggestions.length === 0) return '';\n if (suggestions.length === 1) return `\\nDid you mean ${suggestions[0]}?\\n`;\n return `\\nDid you mean one of these?\\n${suggestions.map((s) => ` ${s}`).join('\\n')}\\n`;\n}\n\nconst program = new Command();\n\nprogram.name('prisma-next').description('Prisma Next CLI').version(packageJson.version);\n\n// Telemetry hook — fires at command start, before the action body\n// runs. Synchronous by construction: `fireTelemetryFromPreAction`\n// resolves gates (cheap), then `fork()`s the detached sender. The\n// fork is enqueued before the action body runs at all, so the child\n// survives even when the action throws synchronously. The try/catch\n// is defence-in-depth — `runTelemetry` already swallows every failure\n// mode internally and returns an outcome instead of throwing.\nprogram.hook('preAction', (_thisCommand, actionCommand) => {\n try {\n fireTelemetryFromPreAction(actionCommand);\n } catch {\n // defence-in-depth — runTelemetry already swallows internally.\n }\n});\n\n// Override version option description to match capitalization style\nconst versionOption = program.options.find((opt) => opt.flags.includes('--version'));\nif (versionOption) {\n versionOption.description = 'Output the version number';\n}\n\nprogram.configureOutput({\n writeErr: () => {\n // Suppress all default error output - we handle errors in exitOverride\n },\n writeOut: (str) => {\n // Commander routes explicitly-requested `--help` (success-path help)\n // through writeOut; per the Style Guide § Output Conventions rule 8,\n // user-requested help is data and goes to stdout. Error-path help\n // (e.g. usage shown after an unknown command) goes through writeErr,\n // which stays suppressed because we render that ourselves with the\n // matching error envelope.\n //\n // Explicit `--version` is short-circuited before `program.parse()`\n // (see the argv pre-scan at the bottom of this file), so it does not\n // reach this writer.\n process.stdout.write(str);\n },\n});\n\n// Customize root help output to use our styled format\nconst rootHelpFormatter = (cmd: Command) => {\n const flags = parseGlobalFlags({});\n return formatRootHelp({ program: cmd, flags });\n};\n\nprogram.configureHelp({\n formatHelp: rootHelpFormatter,\n subcommandDescription: () => '',\n});\n\n// Override exit to handle unhandled errors (fail fast cases)\n// Commands handle structured errors themselves via process.exit()\nprogram.exitOverride((err) => {\n if (err) {\n const errorCode = (err as { code?: string }).code;\n const errorMessage = String(err.message ?? '');\n const errorName = err.name ?? '';\n\n // Unknown command/argument → exit 2 (CLI usage error)\n const isUnknownCommandError =\n errorCode === 'commander.unknownCommand' ||\n errorCode === 'commander.unknownArgument' ||\n (errorName === 'CommanderError' &&\n (errorMessage.includes('unknown command') || errorMessage.includes('unknown argument')));\n if (isUnknownCommandError) {\n const flags = parseGlobalFlags({});\n const match = errorMessage.match(/unknown command ['\"]([^'\"]+)['\"]/);\n const commandName = match ? match[1] : process.argv[3] || process.argv[2] || 'unknown';\n\n const firstArg = process.argv[2];\n const parentCommand = firstArg\n ? program.commands.find((cmd) => cmd.name() === firstArg)\n : undefined;\n\n if (parentCommand && commandName !== firstArg) {\n const subNames = parentCommand.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, subNames)}\\n`,\n );\n const helpText = formatCommandHelp({ command: parentCommand, flags });\n process.stderr.write(`${helpText}\\n`);\n } else {\n const topNames = program.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, topNames)}\\n`,\n );\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n }\n process.exit(2);\n return;\n }\n\n // Help requests → exit 0\n const isHelpError =\n errorCode === 'commander.help' ||\n errorCode === 'commander.helpDisplayed' ||\n errorCode === 'outputHelp' ||\n errorMessage === '(outputHelp)' ||\n errorMessage.includes('outputHelp') ||\n (errorName === 'CommanderError' && errorMessage.includes('outputHelp'));\n if (isHelpError) {\n process.exit(0);\n return;\n }\n\n // Missing required arguments → exit 2 (CLI usage error)\n const isMissingArgumentError =\n errorCode === 'commander.missingArgument' ||\n errorCode === 'commander.missingMandatoryOptionValue' ||\n (errorName === 'CommanderError' &&\n (errorMessage.includes('missing') || errorMessage.includes('required')));\n if (isMissingArgumentError) {\n process.exit(2);\n return;\n }\n\n // Unhandled error → exit 1\n process.stderr.write(`Unhandled error: ${err.message}\\n`);\n if (err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n process.exit(1);\n }\n process.exit(0);\n});\n\n// Register contract subcommand\nconst contractCommand = new Command('contract');\nsetCommandDescriptions(\n contractCommand,\n 'Contract management commands',\n 'Define and emit your application data contract. The contract describes your schema as a\\n' +\n 'declarative data structure that can be signed and verified against your database.',\n);\ncontractCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\n// Add emit subcommand to contract\nconst contractEmitCommand = createContractEmitCommand();\ncontractCommand.addCommand(contractEmitCommand);\n\n// Add infer subcommand to contract\nconst contractInferCommand = createContractInferCommand();\ncontractCommand.addCommand(contractInferCommand);\n\n// Register db subcommand\nconst dbCommand = new Command('db');\nsetCommandDescriptions(\n dbCommand,\n 'Database management commands',\n 'Verify and sign your database with your contract. Ensure your database schema matches\\n' +\n 'your contract, and sign it to record the contract hash for future verification.',\n);\ndbCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\n// Add verify subcommand to db\nconst dbVerifyCommand = createDbVerifyCommand();\ndbCommand.addCommand(dbVerifyCommand);\n\n// Add init subcommand to db\nconst dbInitCommand = createDbInitCommand();\ndbCommand.addCommand(dbInitCommand);\n\n// Add update subcommand to db\nconst dbUpdateCommand = createDbUpdateCommand();\ndbCommand.addCommand(dbUpdateCommand);\n\n// Add schema subcommand to db\nconst dbSchemaCommand = createDbSchemaCommand();\ndbCommand.addCommand(dbSchemaCommand);\n\n// Add sign subcommand to db\nconst dbSignCommand = createDbSignCommand();\ndbCommand.addCommand(dbSignCommand);\n\n// Register migration subcommand\nconst migrationCommand = new Command('migration');\nsetCommandDescriptions(\n migrationCommand,\n 'On-disk migration management commands',\n 'Plan, apply, and scaffold on-disk migration packages. Migrations are\\n' +\n 'contract-to-contract edges stored as versioned directories under migrations/.',\n);\nmigrationCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\nconst migrationPlanCommand = createMigrationPlanCommand();\nmigrationCommand.addCommand(migrationPlanCommand);\n\nconst migrationNewCommand = createMigrationNewCommand();\nmigrationCommand.addCommand(migrationNewCommand);\n\nconst migrationShowCommand = createMigrationShowCommand();\nmigrationCommand.addCommand(migrationShowCommand);\n\nconst migrationStatusCommand = createMigrationStatusCommand();\nmigrationCommand.addCommand(migrationStatusCommand);\n\nconst migrationLogCommand = createMigrationLogCommand();\nmigrationCommand.addCommand(migrationLogCommand);\n\nconst migrationListCommand = createMigrationListCommand();\nmigrationCommand.addCommand(migrationListCommand);\n\nconst migrationGraphCommand = createMigrationGraphCommand();\nmigrationCommand.addCommand(migrationGraphCommand);\n\nconst migrationCheckCommand = createMigrationCheckCommand();\nmigrationCommand.addCommand(migrationCheckCommand);\n\n// Top-level migrate command\nconst migrateCommand = createMigrateCommand();\n\n// Top-level ref command (replaces `migration ref`)\nconst refCommand = createRefCommand();\n\n// Top-level telemetry command\nconst telemetryCommand = createTelemetryCommand();\n\n// Top-level init command\nconst initCommand = createInitCommand();\n\n// Register top-level commands in the order the spec's intended-surface\n// diagram lists them: verbs (init, migrate) first, then subject\n// namespaces (contract, db, migration, ref). The order shows up in\n// `prisma-next --help` and is the first thing a new user sees, so it\n// matches the order spec.md uses to introduce the surface.\nprogram.addCommand(initCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(contractCommand);\nprogram.addCommand(dbCommand);\nprogram.addCommand(migrationCommand);\nprogram.addCommand(refCommand);\nprogram.addCommand(telemetryCommand);\n\n// Test-only hidden command used by `cli-telemetry`'s `cli-e2e.test.ts`\n// to verify that telemetry still lands when a CLI command crashes\n// mid-execution. The preAction hook is synchronous and `fork()`s the\n// detached sender before this action body runs; the small sleep\n// gives the IPC `child.send()` a tick to flush before the throw\n// triggers commander's `exitOverride` and `process.exit(1)`. Hidden\n// from help; underscore prefix marks it as internal. Doesn't depend\n// on any project state, so it runs in any tempdir.\n//\n// Gated behind `PRISMA_NEXT_ENABLE_TEST_COMMANDS=1` so the command is\n// not even registered (and therefore not invocable) in shipped\n// binaries. `hidden: true` only filters the help output; without this\n// env gate the command would still be callable from production. The\n// e2e suite sets the env var when it spawns the CLI.\nconst TELEMETRY_CRASH_TEST_SLEEP_MS = 200;\nif (process.env['PRISMA_NEXT_ENABLE_TEST_COMMANDS'] === '1') {\n const telemetryCrashTestCommand = new Command('__telemetry-crash-test')\n .description('Internal: deliberately throw for the telemetry e2e suite.')\n .action(async () => {\n await new Promise((settle) => setTimeout(settle, TELEMETRY_CRASH_TEST_SLEEP_MS));\n throw new Error('__telemetry-crash-test: intentional crash for e2e coverage');\n });\n telemetryCrashTestCommand.configureHelp({ visibleCommands: () => [] });\n program.addCommand(telemetryCrashTestCommand, { hidden: true });\n}\n\n// Create help command\nconst helpCommand = new Command('help')\n .description('Show usage instructions')\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .action(() => {\n const flags = parseGlobalFlags({});\n const helpText = formatRootHelp({ program, flags });\n // The `help` command was invoked explicitly: help is the data the\n // caller asked for. Per Style Guide § Output Conventions rule 8,\n // explicit help goes to stdout with exit code 0.\n process.stdout.write(`${helpText}\\n`);\n process.exit(0);\n });\n\nprogram.addCommand(helpCommand);\n\n// Set help as the default action when no command is provided. The user\n// did not invoke `--help`; we are voluntarily showing usage to help them\n// recover from an underspecified invocation, so the help text is\n// decoration around an implicit \"what did you want me to do?\" and goes\n// to stderr (Style Guide § Output Conventions rule 8).\n//\n// FOLLOW-UP: the exit code here is 0 today, but a no-arg invocation is\n// arguably a usage error (PRECONDITION → exit 2) for consistency with\n// the unknown-command path. Out of scope for the explicit-help routing\n// work; revisit when tightening exit-code semantics across the CLI.\nprogram.action(() => {\n const flags = parseGlobalFlags({});\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(0);\n});\n\n// Check if a command was invoked with no arguments (just the command name)\n// or if an unrecognized command was provided\nconst args = process.argv.slice(2);\nif (args.length > 0) {\n const commandName = args[0];\n // Handle version option explicitly since we suppress default output\n if (commandName === '--version' || commandName === '-V') {\n // Version is data → stdout\n process.stdout.write(`${program.version()}\\n`);\n process.exit(0);\n }\n // Skip command check for global options like --help, -h\n const isGlobalOption = commandName === '--help' || commandName === '-h';\n if (!isGlobalOption) {\n // Check if this is a recognized command\n const command = program.commands.find((cmd) => cmd.name() === commandName);\n\n if (!command) {\n // Unrecognized command → exit 2 (CLI usage error)\n const flags = parseGlobalFlags({});\n const topNames = program.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, topNames)}\\n`,\n );\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(2);\n } else if (command.commands.length > 0 && args.length >= 2) {\n const subcommandName = args[1];\n const redirectKey = `${commandName}:${subcommandName}`;\n const redirect = removedVerbRedirects[redirectKey];\n if (redirect) {\n process.stderr.write(`Unknown command: ${subcommandName}\\n${redirect}\\n`);\n process.exit(2);\n }\n for (let i = 2; i < args.length; i++) {\n const arg = args[i]!;\n if (!arg.startsWith('--')) continue;\n const flagName = arg.slice(2);\n const flagKey = `${commandName}:${subcommandName}:${flagName}`;\n const flagRedirect = removedFlagRedirects[flagKey];\n if (flagRedirect) {\n process.stderr.write(`Unknown option: ${arg}\\n${flagRedirect}\\n`);\n process.exit(2);\n }\n }\n }\n\n if (command.commands.length > 0 && args.length === 1) {\n // Parent command called with no subcommand. Same shape as the\n // no-args case above: the user did not request help, we are\n // voluntarily rendering it as decoration around an underspecified\n // invocation, so it goes to stderr per Style Guide § Output\n // Conventions rule 8. Exit code 0 today; the FOLLOW-UP note on\n // `program.action` applies here too (arguably should be 2).\n const flags = parseGlobalFlags({});\n const helpText = formatCommandHelp({ command, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(0);\n }\n }\n}\n\nprogram.parse();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACKA,SAAgB,kBAAkB,QAA0B;CAC1D,OAAO,WAAW,aAAa,0BAA0B;AAC3D;AAEA,SAAgB,YAAY,QAA0B;CACpD,OAAO,WAAW,aAAa,eAAe;AAChD;AAEA,SAAgB,kBAAkB,WAAgC;CAChE,IAAI,cAAc,cAChB,OAAO,GAAG,4BAA4B;CAExC,OAAO,GAAG,4BAA4B;AACxC;AAEA,SAAgB,cAAc,QAAkB,WAAgC;CAC9E,IAAI,cAAc,cAChB,OAAO,WAAW,UAAU,qBAAqB,IAAI,wBAAw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ChB;CACF;AACF;AAEA,QAAQ,MAAM"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":["CLI_VERSION","packageJson.version"],"sources":["../package.json","../src/commands/init/templates/code-templates.ts","../src/commands/init/index.ts","../src/utils/suggest-command.ts","../src/utils/telemetry.ts","../src/cli.ts"],"sourcesContent":["","import { DEFAULT_CONTRACT_SOURCE_DIR } from '@prisma-next/config/config-types';\n\nexport type TargetId = 'postgres' | 'mongo';\nexport type AuthoringId = 'psl' | 'typescript';\n\nexport function targetPackageName(target: TargetId): string {\n return target === 'postgres' ? '@prisma-next/postgres' : '@prisma-next/mongo';\n}\n\nexport function targetLabel(target: TargetId): string {\n return target === 'postgres' ? 'PostgreSQL' : 'MongoDB';\n}\n\nexport function defaultSchemaPath(authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return `${DEFAULT_CONTRACT_SOURCE_DIR}/contract.ts`;\n }\n return `${DEFAULT_CONTRACT_SOURCE_DIR}/contract.prisma`;\n}\n\nexport function starterSchema(target: TargetId, authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return target === 'mongo' ? starterSchemaTsMongo() : starterSchemaTsPostgres();\n }\n return target === 'mongo' ? starterSchemaPslMongo() : starterSchemaPslPostgres();\n}\n\n/**\n * Renders a short authoring-appropriate schema sample (FR5.1) for embedding\n * in `prisma-next.md`. Returns a complete fenced markdown code block.\n *\n * The sample intentionally shows just one model: it's illustrative, not\n * a substitute for the full scaffolded contract file. The TS samples use\n * the same outer shape as `starterSchemaTs*` (FR5.3) so a user reading\n * the doc and the file side-by-side sees the same structure.\n */\nexport function schemaSample(target: TargetId, authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return target === 'mongo' ? schemaSampleTsMongo() : schemaSampleTsPostgres();\n }\n return target === 'mongo' ? schemaSamplePslMongo() : schemaSamplePslPostgres();\n}\n\nfunction schemaSamplePslPostgres(): string {\n return `\\`\\`\\`prisma\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n username String?\n name String?\n}\n\\`\\`\\``;\n}\n\nfunction schemaSamplePslMongo(): string {\n return `\\`\\`\\`prisma\nmodel User {\n id ObjectId @id @map(\"_id\")\n email String @unique\n username String?\n name String?\n @@map(\"users\")\n}\n\\`\\`\\``;\n}\n\nfunction schemaSampleTsPostgres(): string {\n return `\\`\\`\\`typescript\nimport { defineContract } from '@prisma-next/postgres/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model }) => ({\n models: {\n User: model('User', {\n fields: {\n id: field.id.uuidv7String(),\n email: field.text().unique(),\n username: field.text().optional(),\n name: field.text().optional(),\n },\n }),\n },\n }),\n);\n\\`\\`\\``;\n}\n\nfunction schemaSampleTsMongo(): string {\n return `\\`\\`\\`typescript\nimport { defineContract } from '@prisma-next/mongo/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model }) => ({\n models: {\n User: model('User', {\n collection: 'users',\n fields: {\n _id: field.objectId(),\n email: field.string(),\n username: field.string().optional(),\n name: field.string().optional(),\n },\n }),\n },\n }),\n);\n\\`\\`\\``;\n}\n\nfunction starterSchemaPslPostgres(): string {\n return `// use prisma-next\n\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n username String?\n name String?\n posts Post[]\n createdAt DateTime @default(now())\n updatedAt temporal.updatedAt()\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n title String\n content String?\n author User @relation(fields: [authorId], references: [id])\n authorId Int\n createdAt DateTime @default(now())\n updatedAt temporal.updatedAt()\n}\n`;\n}\n\nfunction starterSchemaPslMongo(): string {\n return `// use prisma-next\n\nmodel User {\n id ObjectId @id @map(\"_id\")\n email String @unique\n username String?\n name String?\n posts Post[]\n @@map(\"users\")\n}\n\nmodel Post {\n id ObjectId @id @map(\"_id\")\n title String\n content String?\n author User @relation(fields: [authorId], references: [id])\n authorId ObjectId\n @@map(\"posts\")\n}\n`;\n}\n\nfunction starterSchemaTsPostgres(): string {\n return `import { defineContract } from '@prisma-next/postgres/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model, rel }) => ({\n models: {\n User: model('User', {\n fields: {\n id: field.id.uuidv7String(),\n email: field.text().unique(),\n username: field.text().optional(),\n name: field.text().optional(),\n createdAt: field.temporal.createdAt(),\n updatedAt: field.temporal.updatedAt(),\n },\n relations: {\n posts: rel.hasMany('Post', { by: 'authorId' }),\n },\n }),\n\n Post: model('Post', {\n fields: {\n id: field.id.uuidv7String(),\n title: field.text(),\n content: field.text().optional(),\n authorId: field.uuidString(),\n createdAt: field.temporal.createdAt(),\n updatedAt: field.temporal.updatedAt(),\n },\n relations: {\n author: rel.belongsTo('User', { from: 'authorId', to: 'id' }),\n },\n }),\n },\n }),\n);\n`;\n}\n\nfunction starterSchemaTsMongo(): string {\n return `import { defineContract } from '@prisma-next/mongo/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model, rel }) => ({\n models: {\n User: model('User', {\n collection: 'users',\n fields: {\n _id: field.objectId(),\n email: field.string(),\n username: field.string().optional(),\n name: field.string().optional(),\n },\n relations: {\n posts: rel.hasMany('Post', { from: '_id', to: 'authorId' }),\n },\n }),\n\n Post: model('Post', {\n collection: 'posts',\n fields: {\n _id: field.objectId(),\n title: field.string(),\n content: field.string().optional(),\n authorId: field.objectId(),\n },\n relations: {\n author: rel.belongsTo('User', { from: 'authorId', to: '_id' }),\n },\n }),\n },\n }),\n);\n`;\n}\n\nexport function configFile(target: TargetId, contractPath: string): string {\n const pkg = targetPackageName(target);\n return `import 'dotenv/config';\nimport { defineConfig } from '${pkg}/config';\n\nexport default defineConfig({\n contract: ${JSON.stringify(contractPath)},\n db: {\n connection: process.env['DATABASE_URL']!,\n },\n});\n`;\n}\n\nexport function dbFile(target: TargetId): string {\n if (target === 'postgres') {\n return `import postgres from '@prisma-next/postgres/runtime';\nimport type { Contract } from './contract.d';\nimport contractJson from './contract.json' with { type: 'json' };\n\nexport const db = postgres<Contract>({\n contractJson,\n url: process.env['DATABASE_URL']!,\n});\n`;\n }\n\n return `import mongo from '@prisma-next/mongo/runtime';\nimport type { Contract } from './contract.d';\nimport contractJson from './contract.json' with { type: 'json' };\n\nexport const db = mongo<Contract>({\n contractJson,\n url: process.env['DATABASE_URL']!,\n});\n`;\n}\n","import { Command } from 'commander';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../../utils/command-helpers';\nimport {\n type CommonCommandOptions,\n deriveCanPrompt,\n parseGlobalFlagsOrExit,\n} from '../../utils/global-flags';\nimport {\n INIT_EXIT_EMIT_FAILED,\n INIT_EXIT_INSTALL_FAILED,\n INIT_EXIT_INTERNAL_ERROR,\n INIT_EXIT_OK,\n INIT_EXIT_PRECONDITION,\n INIT_EXIT_SKILL_INSTALL_FAILED,\n INIT_EXIT_USER_ABORTED,\n} from './exit-codes';\nimport { defaultSchemaPath } from './templates/code-templates';\n\n/**\n * Commander.js parsed options for `init`. The init-specific options live\n * alongside the inherited `CommonCommandOptions` global flags.\n *\n * `target` and `authoring` are typed as plain `string` here because\n * Commander.js does not enforce enums at parse time — the validation /\n * normalisation happens in `inputs.ts::resolveInitInputs`, which can\n * raise a structured `errorInitInvalidFlagValue` with the full set of\n * allowed values.\n */\ninterface InitCommandOptions extends CommonCommandOptions {\n readonly target?: string;\n readonly authoring?: string;\n readonly schemaPath?: string;\n readonly force?: boolean;\n readonly writeEnv?: boolean;\n readonly probeDb?: boolean;\n readonly strictProbe?: boolean;\n readonly install?: boolean;\n readonly skill?: boolean;\n}\n\nexport function createInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Initialize a new Prisma Next project',\n 'Scaffolds config, schema, and runtime files, installs dependencies,\\n' +\n 'and emits the contract. Gets you from zero to typed queries in one step.\\n' +\n '\\n' +\n 'Run interactively for a guided experience, or supply --target / --authoring\\n' +\n 'and --yes for a fully scriptable run (CI, AI coding agents, automation).\\n' +\n '\\n' +\n 'Exit codes (see CLI Style Guide § Exit Codes):\\n' +\n ` ${INIT_EXIT_OK} OK Init succeeded.\\n` +\n ` ${INIT_EXIT_INTERNAL_ERROR} INTERNAL_ERROR Unexpected bug in prisma-next (please report).\\n` +\n ` ${INIT_EXIT_PRECONDITION} PRECONDITION Bad flags / missing prerequisite (e.g. no package.json).\\n` +\n ` ${INIT_EXIT_USER_ABORTED} USER_ABORTED User cancelled an interactive prompt.\\n` +\n ` ${INIT_EXIT_INSTALL_FAILED} INSTALL_FAILED Dependency installation failed (init-specific).\\n` +\n ` ${INIT_EXIT_EMIT_FAILED} EMIT_FAILED \\`contract emit\\` failed after install (init-specific).\\n` +\n ` ${INIT_EXIT_SKILL_INSTALL_FAILED} SKILL_INSTALL_FAILED Agent-skill install failed (re-run with --no-skill to skip).`,\n );\n setCommandExamples(command, [\n 'prisma-next init',\n 'prisma-next init --yes --target postgres --authoring psl',\n 'prisma-next init --yes --target mongodb --authoring typescript --json',\n 'prisma-next init --yes --force --target postgres --authoring psl # overwrite an existing scaffold',\n 'prisma-next init --no-install # skip pnpm/npm install + emit',\n 'prisma-next init --no-skill # skip the skills install (air-gapped / restricted env)',\n ]);\n\n return addGlobalOptions(command)\n .option('--target <db>', 'Database target: postgres or mongodb')\n .option('--authoring <style>', 'Schema authoring style: psl or typescript')\n .option(\n '--schema-path <path>',\n `Where to write the starter schema (default: ${defaultSchemaPath('psl')})`,\n )\n .option('--force', 'Overwrite an existing scaffold without prompting')\n .option(\n '--write-env',\n 'Write a .env file from .env.example (gitignored; default: only .env.example)',\n )\n .option(\n '--probe-db',\n 'Connect to DATABASE_URL once and check the server version against the target minimum (opt-in; off by default)',\n )\n .option(\n '--strict-probe',\n 'Treat a failed --probe-db as fatal (no-op without --probe-db; init is offline-by-default)',\n )\n .option('--no-install', 'Skip dependency installation and contract emission')\n .option(\n '--no-skill',\n 'Skip Prisma Next skills install (air-gapped CI, restricted registries, etc.)',\n )\n .action(async (options: InitCommandOptions) => {\n const { runInit } = await import('./init');\n const flags = parseGlobalFlagsOrExit(options);\n const canPrompt = deriveCanPrompt({\n flagsInteractive: flags.interactive,\n optionInteractive: options.interactive,\n stdinIsTTY: Boolean(process.stdin.isTTY),\n });\n const exitCode = await runInit(process.cwd(), {\n options,\n flags,\n canPrompt,\n });\n process.exit(exitCode);\n });\n}\n","import { distance } from 'closest-match';\n\n/**\n * Suggests similar command names for a mistyped input.\n *\n * Uses Levenshtein distance to find close matches. Only suggests commands\n * within a reasonable distance threshold (40% of the input length, minimum 2).\n * Returns up to 3 suggestions in case of ties.\n *\n * @returns Array of suggested command names (empty if nothing is close enough).\n */\nexport function suggestCommands(input: string, candidates: readonly string[]): string[] {\n if (candidates.length === 0) return [];\n\n // Threshold: at most 40% of the input length (min 2) to avoid absurd suggestions\n const maxDistance = Math.max(2, Math.ceil(input.length * 0.4));\n\n const scored = candidates\n .map((name) => ({ name, dist: distance(input, name) }))\n .filter((entry) => entry.dist <= maxDistance)\n .sort((a, b) => a.dist - b.dist);\n\n if (scored.length === 0) return [];\n\n // Take the best distance, then include ties (up to 3)\n const bestDist = scored[0]!.dist;\n return scored\n .filter((entry) => entry.dist === bestDist)\n .slice(0, 3)\n .map((entry) => entry.name);\n}\n","import { fileURLToPath } from 'node:url';\nimport {\n type CommanderOptionShape,\n type CommanderResultShape,\n ensureInstallationId,\n readUserConfig,\n resolveGating,\n runTelemetry,\n type TelemetryRunOutcome,\n type UserConfig,\n userConfigPath,\n} from '@prisma-next/cli-telemetry';\nimport type { Command } from 'commander';\nimport { version as CLI_VERSION } from '../../package.json' with { type: 'json' };\nimport { isCI } from './is-ci';\n\ntype TelemetryGate =\n | { readonly enabled: true; readonly userConfig: UserConfig }\n | { readonly enabled: false; readonly outcome: TelemetryRunOutcome };\n\n/**\n * Resolve the commander command path from a leaf `Command`, walking up\n * the parent chain. Result is rooted at the program name and ends at\n * the leaf — `['prisma-next', 'migration', 'new']` for\n * `prisma-next migration new …`.\n */\nfunction commandPathFor(actionCommand: Command): string[] {\n const path: string[] = [];\n let cursor: Command | null = actionCommand;\n while (cursor !== null) {\n path.unshift(cursor.name());\n cursor = cursor.parent;\n }\n return path;\n}\n\nfunction commanderOptionSnapshots(actionCommand: Command): CommanderOptionShape[] {\n return actionCommand.options.map((option) => {\n const attributeName = option.attributeName();\n return {\n attributeName,\n longName: option.long ?? null,\n source: actionCommand.getOptionValueSource(attributeName) ?? null,\n };\n });\n}\n\n/**\n * Project commander's leaf `Command` into the wire-shape snapshot the\n * telemetry sanitiser consumes. Pure projection — no env, no I/O.\n */\nexport function commanderSnapshotForTelemetry(actionCommand: Command): CommanderResultShape {\n return {\n commandPath: commandPathFor(actionCommand),\n positionalArgs: actionCommand.args,\n options: commanderOptionSnapshots(actionCommand),\n };\n}\n\nfunction resolveTelemetryGate(): TelemetryGate {\n if (isCI()) {\n return { enabled: false, outcome: { spawned: false, reason: 'ci' } };\n }\n const userConfig = readUserConfig();\n const gating = resolveGating({ env: process.env, config: userConfig });\n if (!gating.enabled) {\n return { enabled: false, outcome: { spawned: false, reason: 'gated-off' } };\n }\n return { enabled: true, userConfig };\n}\n\n/**\n * Path to the compiled sender script inside `@prisma-next/cli-telemetry`'s\n * `dist/`. Resolved off this module's `import.meta.url` via the package\n * specifier `@prisma-next/cli-telemetry/sender`, so the consumer pays\n * no attention to internal package layout.\n */\nfunction senderPath(): string {\n return fileURLToPath(new URL(import.meta.resolve('@prisma-next/cli-telemetry/sender')));\n}\n\nfunction fireTelemetry(actionCommand: Command, userConfig: UserConfig): TelemetryRunOutcome {\n return runTelemetry({\n command: commanderSnapshotForTelemetry(actionCommand),\n version: CLI_VERSION,\n projectRoot: process.cwd(),\n senderPath: senderPath(),\n isCI: isCI(),\n env: process.env,\n userConfig,\n });\n}\n\n/**\n * preAction-stage entry point. Synchronous by construction: resolve\n * env/CI/user-consent gates (cheap, all in-memory and a single tiny\n * user-config read), then — only when enabled — `fork()` the detached\n * sender script. The forked child loads `prisma-next.config.*` via\n * c12 on its own (see `loadProjectConfig` in cli-telemetry); the\n * parent does no project-config I/O on the command's hot path.\n *\n * Privacy invariant: gate resolution always happens before any project\n * config touches disk. The child loading user TS code is acceptable\n * only because it's gated behind the same resolved-enabled signal.\n */\n/**\n * Builds the one-time first-run disclosure. The resolved absolute path to\n * the user-level config file is substituted in so the user can see exactly\n * which file to edit (it must not be confused with `prisma-next.config.ts`).\n * `prisma-next telemetry disable` is named as the primary, friendliest\n * opt-out, alongside the env vars and the config edit.\n */\nfunction firstRunNotice(configPath: string): string {\n return [\n 'Prisma Next collects anonymous CLI usage data, enabled by default.',\n \"What's collected and why: https://prisma-next.dev/docs/cli/telemetry.\",\n 'Opt out: run \"prisma-next telemetry disable\", set DO_NOT_TRACK=1 or',\n `PRISMA_NEXT_DISABLE_TELEMETRY=1, or set \"enableTelemetry\": false in ${configPath}.`,\n ].join(' ');\n}\n\n/**\n * Best-effort first-run disclosure + installationId mint. Runs only on the\n * gating-enabled path. Prints the notice to stderr (never stdout) and mints\n * a persistent id without touching `enableTelemetry`, so the opt-out default\n * stays intact and no unasked-for consent is recorded.\n *\n * Every step is wrapped so an un-writable config dir (or any other failure)\n * never throws and never blocks the command. Returns the minted (or\n * pre-existing) id so the caller can forward it to `runTelemetry` without a\n * redundant disk read. On mint failure it returns `undefined`: the notice may\n * reprint next run, and `runTelemetry` no-ops on the missing id.\n */\nfunction discloseAndMintOnFirstRun(): string | undefined {\n try {\n process.stderr.write(`${firstRunNotice(userConfigPath())}\\n`);\n } catch {}\n try {\n return ensureInstallationId();\n } catch {}\n return undefined;\n}\n\n/**\n * True when the run is the `telemetry` command (or one of its\n * subcommands). The usage-telemetry preAction fire is exempted for it:\n * it would be absurd for `telemetry disable` to send a usage event before\n * disabling, or for `telemetry status` to mint an id + send while merely\n * reporting state. This is the only command-specific exemption.\n *\n * The check is rooted at the program: the path must be\n * `['prisma-next', 'telemetry', …]`, so it matches the top-level\n * `telemetry` command and its subcommands without matching a hypothetical\n * nested `… telemetry` elsewhere.\n */\nfunction isTelemetryCommand(actionCommand: Command): boolean {\n return commandPathFor(actionCommand)[1] === 'telemetry';\n}\n\nexport function fireTelemetryFromPreAction(actionCommand: Command): TelemetryRunOutcome {\n if (isTelemetryCommand(actionCommand)) {\n return { spawned: false, reason: 'gated-off' };\n }\n const gate = resolveTelemetryGate();\n if (!gate.enabled) {\n return gate.outcome;\n }\n const storedId = gate.userConfig.installationId;\n if (typeof storedId !== 'string' || storedId.length === 0) {\n const installationId = discloseAndMintOnFirstRun();\n return fireTelemetry(\n actionCommand,\n installationId === undefined ? gate.userConfig : { ...gate.userConfig, installationId },\n );\n }\n return fireTelemetry(actionCommand, gate.userConfig);\n}\n","import { Command } from 'commander';\nimport packageJson from '../package.json' with { type: 'json' };\nimport { createContractEmitCommand } from './commands/contract-emit';\nimport { createContractInferCommand } from './commands/contract-infer';\nimport { createInitCommand } from './commands/init';\nimport { installShutdownHandlers } from './utils/shutdown';\n\n// Install SIGINT/SIGTERM handlers before anything else\ninstallShutdownHandlers();\n\nimport { createDbInitCommand } from './commands/db-init';\nimport { createDbSchemaCommand } from './commands/db-schema';\nimport { createDbSignCommand } from './commands/db-sign';\nimport { createDbUpdateCommand } from './commands/db-update';\nimport { createDbVerifyCommand } from './commands/db-verify';\nimport { createMigrateCommand } from './commands/migrate';\nimport { createMigrationCheckCommand } from './commands/migration-check';\nimport { createMigrationGraphCommand } from './commands/migration-graph';\nimport { createMigrationListCommand } from './commands/migration-list';\nimport { createMigrationLogCommand } from './commands/migration-log';\nimport { createMigrationNewCommand } from './commands/migration-new';\nimport { createMigrationPlanCommand } from './commands/migration-plan';\nimport { createMigrationShowCommand } from './commands/migration-show';\nimport { createMigrationStatusCommand } from './commands/migration-status';\nimport { createRefCommand } from './commands/ref';\nimport { createTelemetryCommand } from './commands/telemetry';\nimport { setCommandDescriptions } from './utils/command-helpers';\nimport { formatCommandHelp, formatRootHelp } from './utils/formatters/help';\nimport { parseGlobalFlags } from './utils/global-flags';\nimport { suggestCommands } from './utils/suggest-command';\nimport { fireTelemetryFromPreAction } from './utils/telemetry';\n\n/**\n * Lookup table mapping removed subcommands to their replacement verbs.\n * Keyed by `<parent>:<subcommand>` (e.g. `migration:apply`).\n * The handler consults this before falling back to the fuzzy suggest engine.\n */\nconst removedVerbRedirects: Record<string, string> = {\n 'migration:apply': 'Use `prisma-next migrate --to <contract>` instead.',\n 'migration:ref': 'Use `prisma-next ref set|list|delete` instead.',\n};\n\n/**\n * Removed flags on specific subcommands. Keyed by `<parent>:<sub>:<flag>`.\n * Checked during the pre-parse argv scan before commander sees the flags.\n */\nconst removedFlagRedirects: Record<string, string> = {\n 'migration:status:graph': 'Use `prisma-next migration graph` to view the migration graph.',\n 'migration:status:all':\n 'Use `prisma-next migration log --db <url>` to view the full execution history.',\n 'migration:status:limit':\n 'Use `prisma-next migration log --db <url>` to view the full execution history.',\n 'migration:status:ref': 'Use `--to <contract>` instead of `--ref`.',\n};\n\n/**\n * Formats the \"Did you mean ...?\" hint for an unknown command.\n */\nfunction formatSuggestion(input: string, candidates: readonly string[]): string {\n const suggestions = suggestCommands(\n input,\n candidates.map((c) => c),\n );\n if (suggestions.length === 0) return '';\n if (suggestions.length === 1) return `\\nDid you mean ${suggestions[0]}?\\n`;\n return `\\nDid you mean one of these?\\n${suggestions.map((s) => ` ${s}`).join('\\n')}\\n`;\n}\n\nconst program = new Command();\n\nprogram.name('prisma-next').description('Prisma Next CLI').version(packageJson.version);\n\n// Telemetry hook — fires at command start, before the action body\n// runs. Synchronous by construction: `fireTelemetryFromPreAction`\n// resolves gates (cheap), then `fork()`s the detached sender. The\n// fork is enqueued before the action body runs at all, so the child\n// survives even when the action throws synchronously. The try/catch\n// is defence-in-depth — `runTelemetry` already swallows every failure\n// mode internally and returns an outcome instead of throwing.\nprogram.hook('preAction', (_thisCommand, actionCommand) => {\n try {\n fireTelemetryFromPreAction(actionCommand);\n } catch {\n // defence-in-depth — runTelemetry already swallows internally.\n }\n});\n\n// Override version option description to match capitalization style\nconst versionOption = program.options.find((opt) => opt.flags.includes('--version'));\nif (versionOption) {\n versionOption.description = 'Output the version number';\n}\n\nprogram.configureOutput({\n writeErr: () => {\n // Suppress all default error output - we handle errors in exitOverride\n },\n writeOut: (str) => {\n // Commander routes explicitly-requested `--help` (success-path help)\n // through writeOut; per the Style Guide § Output Conventions rule 8,\n // user-requested help is data and goes to stdout. Error-path help\n // (e.g. usage shown after an unknown command) goes through writeErr,\n // which stays suppressed because we render that ourselves with the\n // matching error envelope.\n //\n // Explicit `--version` is short-circuited before `program.parse()`\n // (see the argv pre-scan at the bottom of this file), so it does not\n // reach this writer.\n process.stdout.write(str);\n },\n});\n\n// Customize root help output to use our styled format\nconst rootHelpFormatter = (cmd: Command) => {\n const flags = parseGlobalFlags({});\n return formatRootHelp({ program: cmd, flags });\n};\n\nprogram.configureHelp({\n formatHelp: rootHelpFormatter,\n subcommandDescription: () => '',\n});\n\n// Override exit to handle unhandled errors (fail fast cases)\n// Commands handle structured errors themselves via process.exit()\nprogram.exitOverride((err) => {\n if (err) {\n const errorCode = (err as { code?: string }).code;\n const errorMessage = String(err.message ?? '');\n const errorName = err.name ?? '';\n\n // Unknown command/argument → exit 2 (CLI usage error)\n const isUnknownCommandError =\n errorCode === 'commander.unknownCommand' ||\n errorCode === 'commander.unknownArgument' ||\n (errorName === 'CommanderError' &&\n (errorMessage.includes('unknown command') || errorMessage.includes('unknown argument')));\n if (isUnknownCommandError) {\n const flags = parseGlobalFlags({});\n const match = errorMessage.match(/unknown command ['\"]([^'\"]+)['\"]/);\n const commandName = match ? match[1] : process.argv[3] || process.argv[2] || 'unknown';\n\n const firstArg = process.argv[2];\n const parentCommand = firstArg\n ? program.commands.find((cmd) => cmd.name() === firstArg)\n : undefined;\n\n if (parentCommand && commandName !== firstArg) {\n const subNames = parentCommand.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, subNames)}\\n`,\n );\n const helpText = formatCommandHelp({ command: parentCommand, flags });\n process.stderr.write(`${helpText}\\n`);\n } else {\n const topNames = program.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, topNames)}\\n`,\n );\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n }\n process.exit(2);\n return;\n }\n\n // Help requests → exit 0\n const isHelpError =\n errorCode === 'commander.help' ||\n errorCode === 'commander.helpDisplayed' ||\n errorCode === 'outputHelp' ||\n errorMessage === '(outputHelp)' ||\n errorMessage.includes('outputHelp') ||\n (errorName === 'CommanderError' && errorMessage.includes('outputHelp'));\n if (isHelpError) {\n process.exit(0);\n return;\n }\n\n // Missing required arguments → exit 2 (CLI usage error)\n const isMissingArgumentError =\n errorCode === 'commander.missingArgument' ||\n errorCode === 'commander.missingMandatoryOptionValue' ||\n (errorName === 'CommanderError' &&\n (errorMessage.includes('missing') || errorMessage.includes('required')));\n if (isMissingArgumentError) {\n process.exit(2);\n return;\n }\n\n // Unhandled error → exit 1\n process.stderr.write(`Unhandled error: ${err.message}\\n`);\n if (err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n process.exit(1);\n }\n process.exit(0);\n});\n\n// Register contract subcommand\nconst contractCommand = new Command('contract');\nsetCommandDescriptions(\n contractCommand,\n 'Contract management commands',\n 'Define and emit your application data contract. The contract describes your schema as a\\n' +\n 'declarative data structure that can be signed and verified against your database.',\n);\ncontractCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\n// Add emit subcommand to contract\nconst contractEmitCommand = createContractEmitCommand();\ncontractCommand.addCommand(contractEmitCommand);\n\n// Add infer subcommand to contract\nconst contractInferCommand = createContractInferCommand();\ncontractCommand.addCommand(contractInferCommand);\n\n// Register db subcommand\nconst dbCommand = new Command('db');\nsetCommandDescriptions(\n dbCommand,\n 'Database management commands',\n 'Verify and sign your database with your contract. Ensure your database schema matches\\n' +\n 'your contract, and sign it to record the contract hash for future verification.',\n);\ndbCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\n// Add verify subcommand to db\nconst dbVerifyCommand = createDbVerifyCommand();\ndbCommand.addCommand(dbVerifyCommand);\n\n// Add init subcommand to db\nconst dbInitCommand = createDbInitCommand();\ndbCommand.addCommand(dbInitCommand);\n\n// Add update subcommand to db\nconst dbUpdateCommand = createDbUpdateCommand();\ndbCommand.addCommand(dbUpdateCommand);\n\n// Add schema subcommand to db\nconst dbSchemaCommand = createDbSchemaCommand();\ndbCommand.addCommand(dbSchemaCommand);\n\n// Add sign subcommand to db\nconst dbSignCommand = createDbSignCommand();\ndbCommand.addCommand(dbSignCommand);\n\n// Register migration subcommand\nconst migrationCommand = new Command('migration');\nsetCommandDescriptions(\n migrationCommand,\n 'On-disk migration management commands',\n 'Plan, apply, and scaffold on-disk migration packages. Migrations are\\n' +\n 'contract-to-contract edges stored as versioned directories under migrations/.',\n);\nmigrationCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\nconst migrationPlanCommand = createMigrationPlanCommand();\nmigrationCommand.addCommand(migrationPlanCommand);\n\nconst migrationNewCommand = createMigrationNewCommand();\nmigrationCommand.addCommand(migrationNewCommand);\n\nconst migrationShowCommand = createMigrationShowCommand();\nmigrationCommand.addCommand(migrationShowCommand);\n\nconst migrationStatusCommand = createMigrationStatusCommand();\nmigrationCommand.addCommand(migrationStatusCommand);\n\nconst migrationLogCommand = createMigrationLogCommand();\nmigrationCommand.addCommand(migrationLogCommand);\n\nconst migrationListCommand = createMigrationListCommand();\nmigrationCommand.addCommand(migrationListCommand);\n\nconst migrationGraphCommand = createMigrationGraphCommand();\nmigrationCommand.addCommand(migrationGraphCommand);\n\nconst migrationCheckCommand = createMigrationCheckCommand();\nmigrationCommand.addCommand(migrationCheckCommand);\n\n// Top-level migrate command\nconst migrateCommand = createMigrateCommand();\n\n// Top-level ref command (replaces `migration ref`)\nconst refCommand = createRefCommand();\n\n// Top-level telemetry command\nconst telemetryCommand = createTelemetryCommand();\n\n// Top-level init command\nconst initCommand = createInitCommand();\n\n// Register top-level commands in the order the spec's intended-surface\n// diagram lists them: verbs (init, migrate) first, then subject\n// namespaces (contract, db, migration, ref). The order shows up in\n// `prisma-next --help` and is the first thing a new user sees, so it\n// matches the order spec.md uses to introduce the surface.\nprogram.addCommand(initCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(contractCommand);\nprogram.addCommand(dbCommand);\nprogram.addCommand(migrationCommand);\nprogram.addCommand(refCommand);\nprogram.addCommand(telemetryCommand);\n\n// Test-only hidden command used by `cli-telemetry`'s `cli-e2e.test.ts`\n// to verify that telemetry still lands when a CLI command crashes\n// mid-execution. The preAction hook is synchronous and `fork()`s the\n// detached sender before this action body runs; the small sleep\n// gives the IPC `child.send()` a tick to flush before the throw\n// triggers commander's `exitOverride` and `process.exit(1)`. Hidden\n// from help; underscore prefix marks it as internal. Doesn't depend\n// on any project state, so it runs in any tempdir.\n//\n// Gated behind `PRISMA_NEXT_ENABLE_TEST_COMMANDS=1` so the command is\n// not even registered (and therefore not invocable) in shipped\n// binaries. `hidden: true` only filters the help output; without this\n// env gate the command would still be callable from production. The\n// e2e suite sets the env var when it spawns the CLI.\nconst TELEMETRY_CRASH_TEST_SLEEP_MS = 200;\nif (process.env['PRISMA_NEXT_ENABLE_TEST_COMMANDS'] === '1') {\n const telemetryCrashTestCommand = new Command('__telemetry-crash-test')\n .description('Internal: deliberately throw for the telemetry e2e suite.')\n .action(async () => {\n await new Promise((settle) => setTimeout(settle, TELEMETRY_CRASH_TEST_SLEEP_MS));\n throw new Error('__telemetry-crash-test: intentional crash for e2e coverage');\n });\n telemetryCrashTestCommand.configureHelp({ visibleCommands: () => [] });\n program.addCommand(telemetryCrashTestCommand, { hidden: true });\n}\n\n// Create help command\nconst helpCommand = new Command('help')\n .description('Show usage instructions')\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .action(() => {\n const flags = parseGlobalFlags({});\n const helpText = formatRootHelp({ program, flags });\n // The `help` command was invoked explicitly: help is the data the\n // caller asked for. Per Style Guide § Output Conventions rule 8,\n // explicit help goes to stdout with exit code 0.\n process.stdout.write(`${helpText}\\n`);\n process.exit(0);\n });\n\nprogram.addCommand(helpCommand);\n\n// Set help as the default action when no command is provided. The user\n// did not invoke `--help`; we are voluntarily showing usage to help them\n// recover from an underspecified invocation, so the help text is\n// decoration around an implicit \"what did you want me to do?\" and goes\n// to stderr (Style Guide § Output Conventions rule 8).\n//\n// FOLLOW-UP: the exit code here is 0 today, but a no-arg invocation is\n// arguably a usage error (PRECONDITION → exit 2) for consistency with\n// the unknown-command path. Out of scope for the explicit-help routing\n// work; revisit when tightening exit-code semantics across the CLI.\nprogram.action(() => {\n const flags = parseGlobalFlags({});\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(0);\n});\n\n// Check if a command was invoked with no arguments (just the command name)\n// or if an unrecognized command was provided\nconst args = process.argv.slice(2);\nif (args.length > 0) {\n const commandName = args[0];\n // Handle version option explicitly since we suppress default output\n if (commandName === '--version' || commandName === '-V') {\n // Version is data → stdout\n process.stdout.write(`${program.version()}\\n`);\n process.exit(0);\n }\n // Skip command check for global options like --help, -h\n const isGlobalOption = commandName === '--help' || commandName === '-h';\n if (!isGlobalOption) {\n // Check if this is a recognized command\n const command = program.commands.find((cmd) => cmd.name() === commandName);\n\n if (!command) {\n // Unrecognized command → exit 2 (CLI usage error)\n const flags = parseGlobalFlags({});\n const topNames = program.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, topNames)}\\n`,\n );\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(2);\n } else if (command.commands.length > 0 && args.length >= 2) {\n const subcommandName = args[1];\n const redirectKey = `${commandName}:${subcommandName}`;\n const redirect = removedVerbRedirects[redirectKey];\n if (redirect) {\n process.stderr.write(`Unknown command: ${subcommandName}\\n${redirect}\\n`);\n process.exit(2);\n }\n for (let i = 2; i < args.length; i++) {\n const arg = args[i]!;\n if (!arg.startsWith('--')) continue;\n const flagName = arg.slice(2);\n const flagKey = `${commandName}:${subcommandName}:${flagName}`;\n const flagRedirect = removedFlagRedirects[flagKey];\n if (flagRedirect) {\n process.stderr.write(`Unknown option: ${arg}\\n${flagRedirect}\\n`);\n process.exit(2);\n }\n }\n }\n\n if (command.commands.length > 0 && args.length === 1) {\n // Parent command called with no subcommand. Same shape as the\n // no-args case above: the user did not request help, we are\n // voluntarily rendering it as decoration around an underspecified\n // invocation, so it goes to stderr per Style Guide § Output\n // Conventions rule 8. Exit code 0 today; the FOLLOW-UP note on\n // `program.action` applies here too (arguably should be 2).\n const flags = parseGlobalFlags({});\n const helpText = formatCommandHelp({ command, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(0);\n }\n }\n}\n\nprogram.parse();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACKA,SAAgB,kBAAkB,QAA0B;CAC1D,OAAO,WAAW,aAAa,0BAA0B;AAC3D;AAEA,SAAgB,YAAY,QAA0B;CACpD,OAAO,WAAW,aAAa,eAAe;AAChD;AAEA,SAAgB,kBAAkB,WAAgC;CAChE,IAAI,cAAc,cAChB,OAAO,GAAG,4BAA4B;CAExC,OAAO,GAAG,4BAA4B;AACxC;AAEA,SAAgB,cAAc,QAAkB,WAAgC;CAC9E,IAAI,cAAc,cAChB,OAAO,WAAW,UAAU,qBAAqB,IAAI,wBAAwB;CAE/E,OAAO,WAAW,UAAU,sBAAsB,IAAI,yBAAyB;AACjF;;;;;;;;;;AAWA,SAAgB,aAAa,QAAkB,WAAgC;CAC7E,IAAI,cAAc,cAChB,OAAO,WAAW,UAAU,oBAAoB,IAAI,uBAAuB;CAE7E,OAAO,WAAW,UAAU,qBAAqB,IAAI,wBAAwB;AAC/E;AAEA,SAAS,0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AW,QAAQ,SAAS,KAAK,MAAM,EAAE,KAAK,CAAC;GACrD,QAAQ,OAAO,MACb,oBAAoB,cAAc,iBAAiB,aAAc,QAAQ,EAAE,GAC7E;GACA,MAAM,WAAW,eAAe;IAAE;IAAS;GAAM,CAAC;GAClD,QAAQ,OAAO,MAAM,GAAG,SAAS,GAAG;GACpC,QAAQ,KAAK,CAAC;EAChB,OAAO,IAAI,QAAQ,SAAS,SAAS,KAAK,KAAK,UAAU,GAAG;GAC1D,MAAM,iBAAiB,KAAK;GAE5B,MAAM,WAAW,qBAAqB,GADf,YAAY,GAAG;GAEtC,IAAI,UAAU;IACZ,QAAQ,OAAO,MAAM,oBAAoB,eAAe,IAAI,SAAS,GAAG;IACxE,QAAQ,KAAK,CAAC;GAChB;GACA,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;IACpC,MAAM,MAAM,KAAK;IACjB,IAAI,CAAC,IAAI,WAAW,IAAI,GAAG;IAG3B,MAAM,eAAe,qBAAqB,GADvB,YAAY,GAAG,eAAe,GADhC,IAAI,MAAM,CACgC;IAE3D,IAAI,cAAc;KAChB,QAAQ,OAAO,MAAM,mBAAmB,IAAI,IAAI,aAAa,GAAG;KAChE,QAAQ,KAAK,CAAC;IAChB;GACF;EACF;EAEA,IAAI,QAAQ,SAAS,SAAS,KAAK,KAAK,WAAW,GAAG;GAQpD,MAAM,WAAW,kBAAkB;IAAE;IAAS,OADhC,iBAAiB,CAAC,CACkB;GAAE,CAAC;GACrD,QAAQ,OAAO,MAAM,GAAG,SAAS,GAAG;GACpC,QAAQ,KAAK,CAAC;EAChB;CACF;AACF;AAEA,QAAQ,MAAM"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as enumerateCheckSpaces, r as runMigrationCheck, t as createMigrationCheckCommand } from "../migration-check-
|
|
1
|
+
import { n as enumerateCheckSpaces, r as runMigrationCheck, t as createMigrationCheckCommand } from "../migration-check-soB5uZEQ.mjs";
|
|
2
2
|
import { t as migrationCheckResultSchema } from "../schemas-KhXMzNA_.mjs";
|
|
3
3
|
export { createMigrationCheckCommand, enumerateCheckSpaces, migrationCheckResultSchema, runMigrationCheck };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as formatMigrationPlanOutput, r as resolveBundleByPrefix, t as createMigrationPlanCommand } from "../migration-plan-
|
|
1
|
+
import { n as formatMigrationPlanOutput, r as resolveBundleByPrefix, t as createMigrationPlanCommand } from "../migration-plan-W_E8FQOk.mjs";
|
|
2
2
|
export { createMigrationPlanCommand, formatMigrationPlanOutput, resolveBundleByPrefix };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { n as migrationStatusJsonResultSchema } from "../schemas-KhXMzNA_.mjs";
|
|
2
|
-
import { a as formatStatusHumanOutput, i as executeMigrationStatusCommand, n as buildStatusHeadline, o as formatStatusSummary, r as createMigrationStatusCommand, t as buildNoPathSummary } from "../migration-status-
|
|
2
|
+
import { a as formatStatusHumanOutput, i as executeMigrationStatusCommand, n as buildStatusHeadline, o as formatStatusSummary, r as createMigrationStatusCommand, t as buildNoPathSummary } from "../migration-status-CgWSoI_g.mjs";
|
|
3
3
|
export { buildNoPathSummary, buildStatusHeadline, createMigrationStatusCommand, executeMigrationStatusCommand, formatStatusHumanOutput, formatStatusSummary, migrationStatusJsonResultSchema };
|
|
@@ -3,7 +3,6 @@ import { A as formatStyledHeader, K as errorInvalidSpaceId, L as errorAmbiguousM
|
|
|
3
3
|
import { t as toDeclaredExtensionsFromRaw } from "./extension-pack-inputs-1ySHqxKG.mjs";
|
|
4
4
|
import { n as buildReadAggregate } from "./contract-space-aggregate-loader-ClI1KN6d.mjs";
|
|
5
5
|
import { i as resolveTargetPathAcrossSpaces, n as looksLikePath, r as resolveAppTargetPath, t as findPackageByDirPath } from "./migration-path-target-Ce6OZImp.mjs";
|
|
6
|
-
import "./schemas-KhXMzNA_.mjs";
|
|
7
6
|
import { Command } from "commander";
|
|
8
7
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
9
8
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -571,4 +570,4 @@ function createMigrationCheckCommand() {
|
|
|
571
570
|
//#endregion
|
|
572
571
|
export { enumerateCheckSpaces as n, runMigrationCheck as r, createMigrationCheckCommand as t };
|
|
573
572
|
|
|
574
|
-
//# sourceMappingURL=migration-check-
|
|
573
|
+
//# sourceMappingURL=migration-check-soB5uZEQ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration-check-VwM8xCZV.mjs","names":["migrationPathRelative","migrationFileRelative"],"sources":["../src/utils/integrity-violation-to-check-failure.ts","../src/commands/migration-check.ts"],"sourcesContent":["import type { IntegrityViolation } from '@prisma-next/migration-tools/aggregate';\nimport { join, relative } from 'pathe';\nimport type { CheckFailure } from '../commands/json/schemas';\n\nexport type { CheckFailure } from '../commands/json/schemas';\n\nfunction migrationPathRelative(dirPath: string): string {\n return relative(process.cwd(), dirPath);\n}\n\nfunction migrationFileRelative(dirPath: string, fileName: string): string {\n return join(migrationPathRelative(dirPath), fileName);\n}\n\n/**\n * Map one {@link IntegrityViolation} onto a `migration check` failure row.\n * Sole catalogue mapping from integrity violations to `PN-MIG-CHECK-*`.\n */\nexport function integrityViolationToCheckFailure(\n violation: IntegrityViolation,\n migrationsDir: string,\n): CheckFailure {\n const spaceRelative = (spaceId: string): string =>\n migrationPathRelative(join(migrationsDir, spaceId));\n const packageRelative = (spaceId: string, dirName: string): string =>\n migrationPathRelative(join(migrationsDir, spaceId, dirName));\n const refRelative = (spaceId: string, refName: string): string =>\n migrationPathRelative(join(migrationsDir, spaceId, 'refs', `${refName}.json`));\n\n switch (violation.kind) {\n case 'hashMismatch':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-001',\n where: migrationFileRelative(\n join(migrationsDir, violation.spaceId, violation.dirName),\n 'migration.json',\n ),\n why: `Stored hash ${violation.stored} does not match recomputed hash ${violation.computed}`,\n fix: 'Re-emit the migration package or restore from version control.',\n };\n case 'providedInvariantsMismatch':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-002',\n where: packageRelative(violation.spaceId, violation.dirName),\n why: `Migration \"${violation.dirName}\" providedInvariants in migration.json disagrees with ops.json.`,\n fix: 'Re-emit the migration package so migration.json and ops.json agree.',\n };\n case 'packageUnloadable':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-002',\n where: packageRelative(violation.spaceId, violation.dirName),\n why: `Migration \"${violation.dirName}\" could not be loaded: ${violation.detail}`,\n fix: 'Re-emit the migration package or restore from version control.',\n };\n case 'sameSourceAndTarget':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-007',\n where: packageRelative(violation.spaceId, violation.dirName),\n why: `Migration \"${violation.dirName}\" in space \"${violation.spaceId}\" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`,\n fix: 'Add a data operation if this self-edge was meant to carry a data invariant, or delete the migration if it is a true no-op.',\n };\n case 'orphanSpaceDir':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-008',\n where: spaceRelative(violation.spaceId),\n why: `Contract-space directory \"${violation.spaceId}\" exists on disk but no extension declares it.`,\n fix: 'Remove the orphan directory, or declare the extension in `extensionPacks`.',\n };\n case 'declaredButUnmigrated':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-009',\n where: spaceRelative(violation.spaceId),\n why: `Extension \"${violation.spaceId}\" is declared in \\`extensionPacks\\` but has no on-disk migrations directory.`,\n fix: 'Re-emit the extension contract-space artefacts with `prisma-next contract emit` and migration planning, or remove the extension from `extensionPacks` if it is unused.',\n };\n case 'headRefMissing':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-010',\n where: refRelative(violation.spaceId, 'head'),\n why: `Head ref \\`refs/head.json\\` is missing for contract space \"${violation.spaceId}\".`,\n fix: 'Re-emit the contract-space migrations and head ref artefacts, or restore `refs/head.json` from version control.',\n };\n case 'headRefNotInGraph':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-011',\n where: refRelative(violation.spaceId, 'head'),\n why: `Head ref ${violation.hash} for contract space \"${violation.spaceId}\" is not present in its migration graph.`,\n fix: 'Re-emit the contract space migrations, or restore the missing migration package.',\n };\n case 'refUnreadable':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-012',\n where: refRelative(violation.spaceId, violation.refName),\n why: `Ref \"${violation.refName}\" for contract space \"${violation.spaceId}\" is unreadable: ${violation.detail}`,\n fix: 'Repair or remove the corrupt ref file.',\n };\n case 'targetMismatch':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-013',\n where: spaceRelative(violation.spaceId),\n why: `Contract space \"${violation.spaceId}\" targets \"${violation.actual}\" but the project targets \"${violation.expected}\".`,\n fix: 'Update the extension to target the configured database, or change the project target.',\n };\n case 'disjointness':\n return {\n space: 'app',\n code: 'PN-MIG-CHECK-014',\n where: migrationPathRelative(migrationsDir),\n why: `Storage element \"${violation.element}\" is claimed by multiple contract spaces: ${violation.claimedBy.join(', ')}.`,\n fix: 'Update the contracts so each storage element is owned by exactly one contract space.',\n };\n case 'contractUnreadable':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-015',\n where: migrationFileRelative(join(migrationsDir, violation.spaceId), 'contract.json'),\n why: `Contract for space \"${violation.spaceId}\" is unreadable: ${violation.detail}`,\n fix: 'Re-emit the extension contract artefacts, or fix the descriptor producing the invalid contract.',\n };\n case 'duplicateMigrationHash':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-016',\n where: spaceRelative(violation.spaceId),\n why: `Multiple migrations in space \"${violation.spaceId}\" share migrationHash \"${violation.migrationHash}\" (${violation.dirNames.join(', ')}).`,\n fix: 'Re-emit one of the conflicting packages so each migrationHash is unique.',\n };\n }\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport type {\n ContractSpaceAggregate,\n IntegrityViolation,\n} from '@prisma-next/migration-tools/aggregate';\nimport { loadContractSpaceAggregate } from '@prisma-next/migration-tools/aggregate';\nimport type { MigrationGraph } from '@prisma-next/migration-tools/graph';\nimport { verifyMigrationHash } from '@prisma-next/migration-tools/hash';\nimport type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';\nimport {\n parseMigrationRef,\n type RefResolutionError,\n} from '@prisma-next/migration-tools/ref-resolution';\nimport type { Refs } from '@prisma-next/migration-tools/refs';\nimport {\n isValidSpaceId,\n listContractSpaceDirectories,\n RESERVED_SPACE_SUBDIR_NAMES,\n spaceMigrationDirectory,\n spaceRefsDirectory,\n} from '@prisma-next/migration-tools/spaces';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join, relative } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport {\n type CliStructuredError,\n errorAmbiguousMigrationRef,\n errorInvalidSpaceId,\n errorSpaceNotFound,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n setCommandSeeAlso,\n} from '../utils/command-helpers';\nimport { buildReadAggregate } from '../utils/contract-space-aggregate-loader';\nimport { toDeclaredExtensionsFromRaw } from '../utils/extension-pack-inputs';\nimport { formatErrorJson, formatErrorOutput } from '../utils/formatters/errors';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { integrityViolationToCheckFailure } from '../utils/integrity-violation-to-check-failure';\nimport {\n findPackageByDirPath,\n looksLikePath,\n resolveAppTargetPath,\n resolveTargetPathAcrossSpaces,\n} from '../utils/migration-path-target';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\nimport type { CheckFailure, MigrationCheckResult } from './json/schemas';\nimport { INTEGRITY_FAILED, OK, PRECONDITION } from './migration-check/exit-codes';\n\ninterface MigrationCheckOptions extends CommonCommandOptions {\n readonly config?: string;\n readonly space?: string;\n}\n\nexport type { CheckFailure, MigrationCheckResult } from './json/schemas';\nexport { migrationCheckResultSchema } from './json/schemas';\n\nfunction migrationPathRelative(dirPath: string): string {\n return relative(process.cwd(), dirPath);\n}\n\nfunction migrationFileRelative(dirPath: string, fileName: string): string {\n return join(migrationPathRelative(dirPath), fileName);\n}\n\nfunction checkFileExists(\n spaceId: string,\n dirPath: string,\n dirName: string,\n fileName: string,\n): CheckFailure | null {\n if (!existsSync(join(dirPath, fileName))) {\n return {\n space: spaceId,\n code: 'PN-MIG-CHECK-002',\n where: migrationFileRelative(dirPath, fileName),\n why: `${fileName} is missing from ${dirName}`,\n fix: 'Re-emit the migration package or restore from version control.',\n };\n }\n return null;\n}\n\nfunction checkSnapshotConsistency(\n spaceId: string,\n pkg: OnDiskMigrationPackage,\n): CheckFailure | null {\n const endContractPath = join(pkg.dirPath, 'end-contract.json');\n if (!existsSync(endContractPath)) return null;\n try {\n const raw = JSON.parse(readFileSync(endContractPath, 'utf-8')) as Record<string, unknown>;\n const storage = raw['storage'] as Record<string, unknown> | undefined;\n const snapshotHash = storage?.['storageHash'];\n if (typeof snapshotHash === 'string' && snapshotHash !== pkg.metadata.to) {\n return {\n space: spaceId,\n code: 'PN-MIG-CHECK-005',\n where: migrationPathRelative(pkg.dirPath),\n why: `Migration \"${pkg.dirName}\" declares to=${pkg.metadata.to} but end-contract.json has storageHash=${snapshotHash}`,\n fix: 'Re-emit the migration package so migration.json and end-contract.json agree.',\n };\n }\n } catch {\n return {\n space: spaceId,\n code: 'PN-MIG-CHECK-006',\n where: migrationPathRelative(pkg.dirPath),\n why: `Migration \"${pkg.dirName}\" has an unparseable end-contract.json.`,\n fix: 'Re-emit the migration package to repair the snapshot file.',\n };\n }\n return null;\n}\n\n/**\n * One contract space's on-disk state, resolved for the explicit graph\n * checks `runMigrationCheck` runs per space: the space's migration\n * packages, its user-authored refs, its induced graph, and the absolute\n * `migrations/<space>/` + `migrations/<space>/refs/` directories the\n * file-existence and dangling-ref `where` paths are derived from.\n */\nexport interface CheckSpace {\n readonly spaceId: string;\n readonly packages: readonly OnDiskMigrationPackage[];\n readonly refs: Refs;\n readonly graph: MigrationGraph;\n readonly migrationsDir: string;\n readonly refsDir: string;\n}\n\n/**\n * Project the loaded {@link ContractSpaceAggregate} into the\n * {@link CheckSpace} rows the multi-space check iterates — one per on-disk\n * contract-space directory, in the aggregate's `app`-first ordering. Mirrors\n * `migration list`'s `migrationSpaceListEntriesFromAggregate`: space\n * membership matches the on-disk directories, package / ref / graph data come\n * from `aggregate.space(id)`.\n */\nexport async function enumerateCheckSpaces(\n aggregate: ContractSpaceAggregate,\n projectMigrationsDir: string,\n): Promise<readonly CheckSpace[]> {\n const candidateDirs = await listContractSpaceDirectories(projectMigrationsDir);\n const onDiskSpaceIds = new Set(\n candidateDirs.filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name)).filter(isValidSpaceId),\n );\n const spaces: CheckSpace[] = [];\n for (const member of aggregate.spaces()) {\n const spaceId = member.spaceId;\n if (!isValidSpaceId(spaceId)) continue;\n if (!onDiskSpaceIds.has(spaceId)) continue;\n const migrationsDir = spaceMigrationDirectory(projectMigrationsDir, spaceId);\n spaces.push({\n spaceId,\n packages: member.packages,\n refs: member.refs,\n graph: member.graph(),\n migrationsDir,\n refsDir: spaceRefsDirectory(migrationsDir),\n });\n }\n return spaces;\n}\n\nfunction checkManifestFilesPresent(space: CheckSpace): readonly CheckFailure[] {\n if (!existsSync(space.migrationsDir)) return [];\n const loadedDirNames = new Set(space.packages.map((p) => p.dirName));\n const failures: CheckFailure[] = [];\n let entries: string[];\n try {\n entries = readdirSync(space.migrationsDir);\n } catch {\n return failures;\n }\n for (const entry of entries) {\n if (entry.startsWith('.') || entry.startsWith('_') || entry === 'refs') continue;\n const entryPath = join(space.migrationsDir, entry);\n try {\n if (!statSync(entryPath).isDirectory()) continue;\n } catch {\n continue;\n }\n if (!loadedDirNames.has(entry)) {\n for (const f of ['migration.json', 'ops.json']) {\n const fail = checkFileExists(space.spaceId, entryPath, entry, f);\n if (fail) failures.push(fail);\n }\n }\n }\n return failures;\n}\n\nfunction checkReachability(space: CheckSpace): readonly CheckFailure[] {\n const allToHashes = new Set(space.packages.map((p) => p.metadata.to));\n const failures: CheckFailure[] = [];\n for (const pkg of space.packages) {\n const isReachable =\n pkg.metadata.from === null ||\n allToHashes.has(pkg.metadata.from) ||\n pkg.metadata.from === 'sha256:empty';\n if (!isReachable) {\n failures.push({\n space: space.spaceId,\n code: 'PN-MIG-CHECK-003',\n where: migrationPathRelative(pkg.dirPath),\n why: `Migration \"${pkg.dirName}\" starts from ${pkg.metadata.from} which no other migration produces`,\n fix: 'This migration is unreachable in the graph. Delete it or re-emit a connecting migration.',\n });\n }\n }\n return failures;\n}\n\nfunction checkDanglingRefs(space: CheckSpace): readonly CheckFailure[] {\n const failures: CheckFailure[] = [];\n for (const [name, entry] of Object.entries(space.refs)) {\n if (!space.graph.nodes.has(entry.hash)) {\n failures.push({\n space: space.spaceId,\n code: 'PN-MIG-CHECK-004',\n where: relative(process.cwd(), join(space.refsDir, `${name}.json`)),\n why: `Ref \"${name}\" points at ${entry.hash} which does not exist in the migration graph`,\n fix: `Update the ref with \\`prisma-next ref set ${name} <valid-hash>\\` or delete it.`,\n });\n }\n }\n return failures;\n}\n\nfunction checkSpace(space: CheckSpace): readonly CheckFailure[] {\n return [\n ...checkManifestFilesPresent(space),\n ...space.packages\n .map((pkg) => checkSnapshotConsistency(space.spaceId, pkg))\n .filter((f): f is CheckFailure => f !== null),\n ...checkReachability(space),\n ...checkDanglingRefs(space),\n ];\n}\n\n/**\n * Inputs for {@link runMigrationCheck} — the multi-space policy core of\n * the holistic (no-arg) `migration check`. Enumeration is supplied by the\n * caller (the CLI shell builds it from {@link enumerateCheckSpaces}); the\n * core does not touch config, flags, or streams.\n */\nexport interface RunMigrationCheckInputs {\n readonly spaces: readonly CheckSpace[];\n readonly spaceFilter?: string;\n}\n\n/**\n * Policy core of the holistic `migration check`: validates `--space`,\n * narrows the pre-enumerated spaces, and runs the per-space explicit graph\n * checks (file-existence, snapshot consistency, reachability, dangling\n * refs), aggregating every failure into one {@link MigrationCheckResult}.\n *\n * `--space` validation mirrors `migration list`: an invalid id →\n * {@link errorInvalidSpaceId}; an id with no on-disk space →\n * {@link errorSpaceNotFound}. Both map to exit `PRECONDITION` at the shell.\n * Aggregate-integrity violations (which already span every space) are folded\n * in by the caller, not here.\n */\nexport function runMigrationCheck(\n inputs: RunMigrationCheckInputs,\n): Result<MigrationCheckResult, CliStructuredError> {\n const { spaces, spaceFilter } = inputs;\n\n if (spaceFilter !== undefined && !isValidSpaceId(spaceFilter)) {\n return notOk(errorInvalidSpaceId(spaceFilter));\n }\n if (spaceFilter !== undefined && !spaces.some((s) => s.spaceId === spaceFilter)) {\n return notOk(errorSpaceNotFound(spaceFilter, spaces.map((s) => s.spaceId).sort()));\n }\n\n const scopedSpaces =\n spaceFilter !== undefined ? spaces.filter((s) => s.spaceId === spaceFilter) : spaces;\n\n const failures = scopedSpaces.flatMap(checkSpace);\n if (failures.length === 0) {\n return ok({ ok: true, failures: [], summary: 'All checks passed' });\n }\n return ok({ ok: false, failures, summary: `${failures.length} integrity failure(s)` });\n}\n\nasync function loadAggregateIntegrityViolations(\n config: Awaited<ReturnType<typeof loadConfig>>,\n migrationsDir: string,\n): Promise<readonly IntegrityViolation[]> {\n try {\n const contractJsonContent = await readFile(resolveContractPath(config), 'utf-8');\n const familyInstance = config.family.create(createControlStack(config));\n const declaredExtensions = toDeclaredExtensionsFromRaw(config.extensionPacks ?? []);\n\n const parsedAppContract: unknown = JSON.parse(contractJsonContent);\n const aggregate = await loadContractSpaceAggregate({\n migrationsDir,\n deserializeContract: (json: unknown) => familyInstance.deserializeContract(json),\n appContract: familyInstance.deserializeContract(parsedAppContract),\n });\n return aggregate.checkIntegrity({ declaredExtensions, checkContracts: true });\n } catch {\n return [];\n }\n}\n\ninterface MigrationCheckOutcome {\n readonly result?: MigrationCheckResult;\n readonly error?: CliStructuredError;\n readonly exitCode: number;\n readonly resolvedSpaceId?: string;\n}\n\nasync function executeMigrationCheckCommand(\n target: string | undefined,\n options: MigrationCheckOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<MigrationCheckOutcome> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative } =\n resolveMigrationPaths(options.config, config);\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: appMigrationsRelative },\n ];\n if (target) {\n details.push({ label: 'target', value: target });\n }\n const header = formatStyledHeader({\n command: 'migration check',\n description: 'Verify artifact and graph integrity',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n const loadedAggregate = await buildReadAggregate(config, { migrationsDir });\n if (!loadedAggregate.ok) {\n return { error: loadedAggregate.failure, exitCode: PRECONDITION };\n }\n\n const spaces = await enumerateCheckSpaces(loadedAggregate.value.aggregate, migrationsDir);\n\n if (target) {\n return await checkSingleTarget(target, {\n spaces,\n ...(options.space !== undefined ? { spaceFilter: options.space } : {}),\n appMigrationsDir,\n appMigrationsRelative,\n });\n }\n\n const checkResult = runMigrationCheck({\n spaces,\n ...(options.space !== undefined ? { spaceFilter: options.space } : {}),\n });\n if (!checkResult.ok) {\n return { error: checkResult.failure, exitCode: PRECONDITION };\n }\n\n const failures: CheckFailure[] = [...checkResult.value.failures];\n const allViolations = await loadAggregateIntegrityViolations(config, migrationsDir);\n const scopedViolations =\n options.space === undefined\n ? allViolations\n : allViolations.filter((v) => v.kind !== 'disjointness' && v.spaceId === options.space);\n for (const violation of scopedViolations) {\n failures.push(integrityViolationToCheckFailure(violation, migrationsDir));\n }\n\n if (failures.length === 0) {\n return {\n result: { ok: true, failures: [], summary: 'All checks passed' },\n exitCode: OK,\n };\n }\n\n return {\n result: { ok: false, failures, summary: `${failures.length} integrity failure(s)` },\n exitCode: INTEGRITY_FAILED,\n };\n}\n\ninterface SingleTargetInputs {\n readonly spaces: readonly CheckSpace[];\n readonly spaceFilter?: string;\n readonly appMigrationsDir: string;\n readonly appMigrationsRelative: string;\n}\n\n/**\n * Ranks ref-resolution failure kinds by how informative they are, so a\n * single-target check surfaces the most useful failure across spaces instead of\n * whichever space failed first. `not-found` (the input matched nothing here)\n * says the least; a malformed input, a wrong grammar, or an in-space ambiguity\n * all say more.\n */\nfunction refFailureSpecificity(error: RefResolutionError): number {\n switch (error.kind) {\n case 'wrong-grammar':\n return 3;\n case 'ambiguous':\n return 2;\n case 'invalid-format':\n return 1;\n case 'not-found':\n return 0;\n }\n}\n\n/**\n * Single-target (`check <ref/path>`) mode — resolves a migration reference\n * across all contract spaces (or the one space narrowed by `--space <id>`).\n *\n * Resolution:\n * - filesystem path → find the owning space by checking which space's\n * `migrationsDir` contains the resolved path; falls back to app-relative\n * validation when the path is outside every space dir.\n * - ref → `parseMigrationRef` against each in-scope space; collect every\n * (space, package) hit; 0 hits = not-found, 1 = check it, >1 = ambiguity\n * error (qualify with `--space`).\n *\n * `--space <id>` is validated the same way the holistic path does it:\n * invalid id → `errorInvalidSpaceId`; no on-disk space → `errorSpaceNotFound`.\n */\nasync function checkSingleTarget(\n target: string,\n inputs: SingleTargetInputs,\n): Promise<MigrationCheckOutcome> {\n const { spaces, spaceFilter, appMigrationsDir, appMigrationsRelative } = inputs;\n\n if (spaceFilter !== undefined && !isValidSpaceId(spaceFilter)) {\n return { error: errorInvalidSpaceId(spaceFilter), exitCode: PRECONDITION };\n }\n if (spaceFilter !== undefined && !spaces.some((s) => s.spaceId === spaceFilter)) {\n return {\n error: errorSpaceNotFound(spaceFilter, spaces.map((s) => s.spaceId).sort()),\n exitCode: PRECONDITION,\n };\n }\n\n const scopedSpaces =\n spaceFilter !== undefined ? spaces.filter((s) => s.spaceId === spaceFilter) : spaces;\n\n let matchedSpace: CheckSpace | undefined;\n let matchedPkg: OnDiskMigrationPackage | undefined;\n\n if (looksLikePath(target)) {\n const resolvedPath = resolveTargetPathAcrossSpaces(target, scopedSpaces);\n if (resolvedPath !== null) {\n for (const space of scopedSpaces) {\n const found = findPackageByDirPath(space.packages, resolvedPath);\n if (found) {\n matchedSpace = space;\n matchedPkg = found;\n break;\n }\n }\n } else {\n // Path outside every space dir — fall back to app-relative validation\n const resolved = resolveAppTargetPath(target, appMigrationsDir, appMigrationsRelative);\n if (!resolved.ok) {\n return { error: resolved.failure, exitCode: PRECONDITION };\n }\n const appSpace = scopedSpaces.find((s) => s.spaceId === 'app');\n if (appSpace) {\n matchedSpace = appSpace;\n matchedPkg = findPackageByDirPath(appSpace.packages, resolved.value);\n }\n }\n } else {\n // Ref resolution: try each in-scope space, collect all hits.\n const hits: Array<{ space: CheckSpace; pkg: OnDiskMigrationPackage }> = [];\n let bestParseFailure: RefResolutionError | undefined;\n for (const space of scopedSpaces) {\n const migResult = parseMigrationRef(target, { graph: space.graph, refs: space.refs });\n if (!migResult.ok) {\n // Keep scanning — a later space may hold a hit that must not be discarded.\n // When no space yields a hit, keep the most informative failure rather than\n // whichever space failed first (the kind is space-dependent).\n if (\n bestParseFailure === undefined ||\n refFailureSpecificity(migResult.failure) > refFailureSpecificity(bestParseFailure)\n ) {\n bestParseFailure = migResult.failure;\n }\n continue;\n }\n const pkg = space.packages.find(\n (p) => p.metadata.migrationHash === migResult.value.migrationHash,\n );\n if (pkg) {\n hits.push({ space, pkg });\n }\n }\n\n if (hits.length > 1) {\n const spaceIds = hits.map((h) => h.space.spaceId);\n return {\n error: errorAmbiguousMigrationRef(target, spaceIds),\n exitCode: PRECONDITION,\n };\n }\n\n if (hits.length === 1) {\n matchedSpace = hits[0]!.space;\n matchedPkg = hits[0]!.pkg;\n } else if (bestParseFailure !== undefined) {\n // The ref didn't resolve in any in-scope space — surface the most informative\n // parse failure through the shared ref-resolution envelope (PN-RUN-3000) the\n // earlier work established, rather than a bespoke string. (Ref-resolved-but-\n // no-package falls through to the \"not found on disk\" result below.)\n return { error: mapRefResolutionError(bestParseFailure), exitCode: PRECONDITION };\n }\n }\n\n if (!matchedPkg || !matchedSpace) {\n return {\n result: {\n ok: false,\n failures: [],\n summary: `Migration package for \"${target}\" not found on disk`,\n },\n exitCode: PRECONDITION,\n };\n }\n\n const failures: CheckFailure[] = [...checkManifestFilesPresent(matchedSpace)];\n\n for (const f of ['migration.json', 'ops.json']) {\n const fail = checkFileExists(matchedSpace.spaceId, matchedPkg.dirPath, matchedPkg.dirName, f);\n if (fail) failures.push(fail);\n }\n\n const verification = verifyMigrationHash(matchedPkg);\n if (!verification.ok) {\n failures.push({\n space: matchedSpace.spaceId,\n code: 'PN-MIG-CHECK-001',\n where: migrationFileRelative(matchedPkg.dirPath, 'migration.json'),\n why: `Stored hash ${verification.storedHash} does not match recomputed hash ${verification.computedHash}`,\n fix: 'Re-emit the migration package or restore from version control.',\n });\n }\n\n const snapshotFailure = checkSnapshotConsistency(matchedSpace.spaceId, matchedPkg);\n if (snapshotFailure) failures.push(snapshotFailure);\n\n const resolvedSpaceId = matchedSpace.spaceId !== 'app' ? matchedSpace.spaceId : undefined;\n\n if (failures.length === 0) {\n return {\n result: { ok: true, failures: [], summary: 'All checks passed' },\n exitCode: OK,\n ...ifDefined('resolvedSpaceId', resolvedSpaceId),\n };\n }\n return {\n result: { ok: false, failures, summary: `${failures.length} integrity failure(s)` },\n exitCode: INTEGRITY_FAILED,\n ...ifDefined('resolvedSpaceId', resolvedSpaceId),\n };\n}\n\nexport function createMigrationCheckCommand(): Command {\n const command = new Command('check');\n setCommandDescriptions(\n command,\n 'Verify artifact and graph integrity',\n 'Validates that on-disk migration packages are internally consistent\\n' +\n '(hashes match, manifests are complete) and that the graph is well-formed\\n' +\n '(edges connect, refs point at valid nodes). The whole-graph check spans\\n' +\n 'every contract space by default; pass --space <id> to narrow to one. A\\n' +\n 'migration reference checks a single package, resolved across all contract\\n' +\n 'spaces (narrow with --space; an ambiguous reference is a precondition failure).\\n' +\n 'Offline — does not consult the database.\\n' +\n 'Exit codes: 0 = all checks passed, 2 = precondition failed\\n' +\n '(unresolved target or unknown --space), 4 = integrity failure(s) found.',\n );\n setCommandExamples(command, [\n 'prisma-next migration check',\n 'prisma-next migration check --space app',\n 'prisma-next migration check 20260101-add-users',\n 'prisma-next migration check 20260101-add-users --space app',\n 'prisma-next migration check --json',\n ]);\n setCommandSeeAlso(command, [\n { verb: 'migration status', oneLiner: 'Show migration path and pending status' },\n { verb: 'migration list', oneLiner: 'List on-disk migrations' },\n { verb: 'migration graph', oneLiner: 'Show the migration graph topology' },\n { verb: 'migration show', oneLiner: 'Display migration package contents' },\n ]);\n command.exitOverride();\n addGlobalOptions(command)\n .argument('[target]', 'Migration reference: directory name, hash/prefix, ref, or path')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--space <id>', 'Narrow output to a single contract space')\n .action(async (target: string | undefined, options: MigrationCheckOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n\n let outcome: MigrationCheckOutcome;\n try {\n outcome = await executeMigrationCheckCommand(target, options, flags, ui);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n outcome = {\n result: { ok: false, failures: [], summary: msg },\n exitCode: PRECONDITION,\n };\n }\n\n if (outcome.error) {\n const envelope = outcome.error.toEnvelope();\n if (flags.json) {\n ui.output(formatErrorJson(envelope));\n } else if (!flags.quiet) {\n ui.error(formatErrorOutput(envelope, flags));\n }\n process.exit(outcome.exitCode);\n }\n\n const result = outcome.result ?? {\n ok: false,\n failures: [],\n summary: 'No check result produced',\n };\n\n if (flags.json) {\n ui.output(JSON.stringify(result, null, 2));\n } else if (!flags.quiet) {\n if (result.ok) {\n const spaceSuffix =\n outcome.resolvedSpaceId !== undefined ? ` (space: ${outcome.resolvedSpaceId})` : '';\n ui.log(`✔ ${result.summary}${spaceSuffix}`);\n } else {\n for (const f of result.failures) {\n ui.log(`✗ [${f.code}] ${f.where}: ${f.why}`);\n ui.log(` fix: ${f.fix}`);\n }\n ui.log(`\\n${result.summary}`);\n }\n }\n\n process.exit(outcome.exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAMA,SAASA,wBAAsB,SAAyB;CACtD,OAAO,SAAS,QAAQ,IAAI,GAAG,OAAO;AACxC;AAEA,SAASC,wBAAsB,SAAiB,UAA0B;CACxE,OAAO,KAAKD,wBAAsB,OAAO,GAAG,QAAQ;AACtD;;;;;AAMA,SAAgB,iCACd,WACA,eACc;CACd,MAAM,iBAAiB,YACrBA,wBAAsB,KAAK,eAAe,OAAO,CAAC;CACpD,MAAM,mBAAmB,SAAiB,YACxCA,wBAAsB,KAAK,eAAe,SAAS,OAAO,CAAC;CAC7D,MAAM,eAAe,SAAiB,YACpCA,wBAAsB,KAAK,eAAe,SAAS,QAAQ,GAAG,QAAQ,MAAM,CAAC;CAE/E,QAAQ,UAAU,MAAlB;EACE,KAAK,gBACH,OAAO;GACL,OAAO,UAAU;GACjB,MAAM;GACN,OAAOC,wBACL,KAAK,eAAe,UAAU,SAAS,UAAU,OAAO,GACxD,gBACF;GACA,KAAK,eAAe,UAAU,OAAO,kCAAkC,UAAU;GACjF,KAAK;EACP;EACF,KAAK,8BACH,OAAO;GACL,OAAO,UAAU;GACjB,MAAM;GACN,OAAO,gBAAgB,UAAU,SAAS,UAAU,OAAO;GAC3D,KAAK,cAAc,UAAU,QAAQ;GACrC,KAAK;EACP;EACF,KAAK,qBACH,OAAO;GACL,OAAO,UAAU;GACjB,MAAM;GACN,OAAO,gBAAgB,UAAU,SAAS,UAAU,OAAO;GAC3D,KAAK,cAAc,UAAU,QAAQ,yBAAyB,UAAU;GACxE,KAAK;EACP;EACF,KAAK,uBACH,OAAO;GACL,OAAO,UAAU;GACjB,MAAM;GACN,OAAO,gBAAgB,UAAU,SAAS,UAAU,OAAO;GAC3D,KAAK,cAAc,UAAU,QAAQ,cAAc,UAAU,QAAQ,gCAAgC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IAAI,QAAQ,OAAO;GACjB,MAAM,WAAW,QAAQ,MAAM,WAAW;GAC1C,IAAI,MAAM,MACR,GAAG,OAAO,gBAAgB,QAAQ,CAAC;QAC9B,IAAI,CAAC,MAAM,OAChB,GAAG,MAAM,kBAAkB,UAAU,KAAK,CAAC;GAE7C,QAAQ,KAAK,QAAQ,QAAQ;EAC/B;EAEA,MAAM,SAAS,QAAQ,UAAU;GAC/B,IAAI;GACJ,UAAU,CAAC;GACX,SAAS;EACX;EAEA,IAAI,MAAM,MACR,GAAG,OAAO,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;OACpC,IAAI,CAAC,MAAM,OAChB,IAAI,OAAO,IAAI;GACb,MAAM,cACJ,QAAQ,oBAAoB,KAAA,IAAY,aAAa,QAAQ,gBAAgB,KAAK;GACpF,GAAG,IAAI,KAAK,OAAO,UAAU,aAAa;EAC5C,OAAO;GACL,KAAK,MAAM,KAAK,OAAO,UAAU;IAC/B,GAAG,IAAI,MAAM,EAAE,KAAK,IAAI,EAAE,MAAM,IAAI,EAAE,KAAK;IAC3C,GAAG,IAAI,UAAU,EAAE,KAAK;GAC1B;GACA,GAAG,IAAI,KAAK,OAAO,SAAS;EAC9B;EAGF,QAAQ,KAAK,QAAQ,QAAQ;CAC/B,CAAC;CAEH,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"migration-check-soB5uZEQ.mjs","names":["migrationPathRelative","migrationFileRelative"],"sources":["../src/utils/integrity-violation-to-check-failure.ts","../src/commands/migration-check.ts"],"sourcesContent":["import type { IntegrityViolation } from '@prisma-next/migration-tools/aggregate';\nimport { join, relative } from 'pathe';\nimport type { CheckFailure } from '../commands/json/schemas';\n\nexport type { CheckFailure } from '../commands/json/schemas';\n\nfunction migrationPathRelative(dirPath: string): string {\n return relative(process.cwd(), dirPath);\n}\n\nfunction migrationFileRelative(dirPath: string, fileName: string): string {\n return join(migrationPathRelative(dirPath), fileName);\n}\n\n/**\n * Map one {@link IntegrityViolation} onto a `migration check` failure row.\n * Sole catalogue mapping from integrity violations to `PN-MIG-CHECK-*`.\n */\nexport function integrityViolationToCheckFailure(\n violation: IntegrityViolation,\n migrationsDir: string,\n): CheckFailure {\n const spaceRelative = (spaceId: string): string =>\n migrationPathRelative(join(migrationsDir, spaceId));\n const packageRelative = (spaceId: string, dirName: string): string =>\n migrationPathRelative(join(migrationsDir, spaceId, dirName));\n const refRelative = (spaceId: string, refName: string): string =>\n migrationPathRelative(join(migrationsDir, spaceId, 'refs', `${refName}.json`));\n\n switch (violation.kind) {\n case 'hashMismatch':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-001',\n where: migrationFileRelative(\n join(migrationsDir, violation.spaceId, violation.dirName),\n 'migration.json',\n ),\n why: `Stored hash ${violation.stored} does not match recomputed hash ${violation.computed}`,\n fix: 'Re-emit the migration package or restore from version control.',\n };\n case 'providedInvariantsMismatch':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-002',\n where: packageRelative(violation.spaceId, violation.dirName),\n why: `Migration \"${violation.dirName}\" providedInvariants in migration.json disagrees with ops.json.`,\n fix: 'Re-emit the migration package so migration.json and ops.json agree.',\n };\n case 'packageUnloadable':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-002',\n where: packageRelative(violation.spaceId, violation.dirName),\n why: `Migration \"${violation.dirName}\" could not be loaded: ${violation.detail}`,\n fix: 'Re-emit the migration package or restore from version control.',\n };\n case 'sameSourceAndTarget':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-007',\n where: packageRelative(violation.spaceId, violation.dirName),\n why: `Migration \"${violation.dirName}\" in space \"${violation.spaceId}\" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`,\n fix: 'Add a data operation if this self-edge was meant to carry a data invariant, or delete the migration if it is a true no-op.',\n };\n case 'orphanSpaceDir':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-008',\n where: spaceRelative(violation.spaceId),\n why: `Contract-space directory \"${violation.spaceId}\" exists on disk but no extension declares it.`,\n fix: 'Remove the orphan directory, or declare the extension in `extensionPacks`.',\n };\n case 'declaredButUnmigrated':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-009',\n where: spaceRelative(violation.spaceId),\n why: `Extension \"${violation.spaceId}\" is declared in \\`extensionPacks\\` but has no on-disk migrations directory.`,\n fix: 'Re-emit the extension contract-space artefacts with `prisma-next contract emit` and migration planning, or remove the extension from `extensionPacks` if it is unused.',\n };\n case 'headRefMissing':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-010',\n where: refRelative(violation.spaceId, 'head'),\n why: `Head ref \\`refs/head.json\\` is missing for contract space \"${violation.spaceId}\".`,\n fix: 'Re-emit the contract-space migrations and head ref artefacts, or restore `refs/head.json` from version control.',\n };\n case 'headRefNotInGraph':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-011',\n where: refRelative(violation.spaceId, 'head'),\n why: `Head ref ${violation.hash} for contract space \"${violation.spaceId}\" is not present in its migration graph.`,\n fix: 'Re-emit the contract space migrations, or restore the missing migration package.',\n };\n case 'refUnreadable':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-012',\n where: refRelative(violation.spaceId, violation.refName),\n why: `Ref \"${violation.refName}\" for contract space \"${violation.spaceId}\" is unreadable: ${violation.detail}`,\n fix: 'Repair or remove the corrupt ref file.',\n };\n case 'targetMismatch':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-013',\n where: spaceRelative(violation.spaceId),\n why: `Contract space \"${violation.spaceId}\" targets \"${violation.actual}\" but the project targets \"${violation.expected}\".`,\n fix: 'Update the extension to target the configured database, or change the project target.',\n };\n case 'disjointness':\n return {\n space: 'app',\n code: 'PN-MIG-CHECK-014',\n where: migrationPathRelative(migrationsDir),\n why: `Storage element \"${violation.element}\" is claimed by multiple contract spaces: ${violation.claimedBy.join(', ')}.`,\n fix: 'Update the contracts so each storage element is owned by exactly one contract space.',\n };\n case 'contractUnreadable':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-015',\n where: migrationFileRelative(join(migrationsDir, violation.spaceId), 'contract.json'),\n why: `Contract for space \"${violation.spaceId}\" is unreadable: ${violation.detail}`,\n fix: 'Re-emit the extension contract artefacts, or fix the descriptor producing the invalid contract.',\n };\n case 'duplicateMigrationHash':\n return {\n space: violation.spaceId,\n code: 'PN-MIG-CHECK-016',\n where: spaceRelative(violation.spaceId),\n why: `Multiple migrations in space \"${violation.spaceId}\" share migrationHash \"${violation.migrationHash}\" (${violation.dirNames.join(', ')}).`,\n fix: 'Re-emit one of the conflicting packages so each migrationHash is unique.',\n };\n }\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport type {\n ContractSpaceAggregate,\n IntegrityViolation,\n} from '@prisma-next/migration-tools/aggregate';\nimport { loadContractSpaceAggregate } from '@prisma-next/migration-tools/aggregate';\nimport type { MigrationGraph } from '@prisma-next/migration-tools/graph';\nimport { verifyMigrationHash } from '@prisma-next/migration-tools/hash';\nimport type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';\nimport {\n parseMigrationRef,\n type RefResolutionError,\n} from '@prisma-next/migration-tools/ref-resolution';\nimport type { Refs } from '@prisma-next/migration-tools/refs';\nimport {\n isValidSpaceId,\n listContractSpaceDirectories,\n RESERVED_SPACE_SUBDIR_NAMES,\n spaceMigrationDirectory,\n spaceRefsDirectory,\n} from '@prisma-next/migration-tools/spaces';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join, relative } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport {\n type CliStructuredError,\n errorAmbiguousMigrationRef,\n errorInvalidSpaceId,\n errorSpaceNotFound,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n setCommandSeeAlso,\n} from '../utils/command-helpers';\nimport { buildReadAggregate } from '../utils/contract-space-aggregate-loader';\nimport { toDeclaredExtensionsFromRaw } from '../utils/extension-pack-inputs';\nimport { formatErrorJson, formatErrorOutput } from '../utils/formatters/errors';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { integrityViolationToCheckFailure } from '../utils/integrity-violation-to-check-failure';\nimport {\n findPackageByDirPath,\n looksLikePath,\n resolveAppTargetPath,\n resolveTargetPathAcrossSpaces,\n} from '../utils/migration-path-target';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\nimport type { CheckFailure, MigrationCheckResult } from './json/schemas';\nimport { INTEGRITY_FAILED, OK, PRECONDITION } from './migration-check/exit-codes';\n\ninterface MigrationCheckOptions extends CommonCommandOptions {\n readonly config?: string;\n readonly space?: string;\n}\n\nexport type { CheckFailure, MigrationCheckResult } from './json/schemas';\nexport { migrationCheckResultSchema } from './json/schemas';\n\nfunction migrationPathRelative(dirPath: string): string {\n return relative(process.cwd(), dirPath);\n}\n\nfunction migrationFileRelative(dirPath: string, fileName: string): string {\n return join(migrationPathRelative(dirPath), fileName);\n}\n\nfunction checkFileExists(\n spaceId: string,\n dirPath: string,\n dirName: string,\n fileName: string,\n): CheckFailure | null {\n if (!existsSync(join(dirPath, fileName))) {\n return {\n space: spaceId,\n code: 'PN-MIG-CHECK-002',\n where: migrationFileRelative(dirPath, fileName),\n why: `${fileName} is missing from ${dirName}`,\n fix: 'Re-emit the migration package or restore from version control.',\n };\n }\n return null;\n}\n\nfunction checkSnapshotConsistency(\n spaceId: string,\n pkg: OnDiskMigrationPackage,\n): CheckFailure | null {\n const endContractPath = join(pkg.dirPath, 'end-contract.json');\n if (!existsSync(endContractPath)) return null;\n try {\n const raw = JSON.parse(readFileSync(endContractPath, 'utf-8')) as Record<string, unknown>;\n const storage = raw['storage'] as Record<string, unknown> | undefined;\n const snapshotHash = storage?.['storageHash'];\n if (typeof snapshotHash === 'string' && snapshotHash !== pkg.metadata.to) {\n return {\n space: spaceId,\n code: 'PN-MIG-CHECK-005',\n where: migrationPathRelative(pkg.dirPath),\n why: `Migration \"${pkg.dirName}\" declares to=${pkg.metadata.to} but end-contract.json has storageHash=${snapshotHash}`,\n fix: 'Re-emit the migration package so migration.json and end-contract.json agree.',\n };\n }\n } catch {\n return {\n space: spaceId,\n code: 'PN-MIG-CHECK-006',\n where: migrationPathRelative(pkg.dirPath),\n why: `Migration \"${pkg.dirName}\" has an unparseable end-contract.json.`,\n fix: 'Re-emit the migration package to repair the snapshot file.',\n };\n }\n return null;\n}\n\n/**\n * One contract space's on-disk state, resolved for the explicit graph\n * checks `runMigrationCheck` runs per space: the space's migration\n * packages, its user-authored refs, its induced graph, and the absolute\n * `migrations/<space>/` + `migrations/<space>/refs/` directories the\n * file-existence and dangling-ref `where` paths are derived from.\n */\nexport interface CheckSpace {\n readonly spaceId: string;\n readonly packages: readonly OnDiskMigrationPackage[];\n readonly refs: Refs;\n readonly graph: MigrationGraph;\n readonly migrationsDir: string;\n readonly refsDir: string;\n}\n\n/**\n * Project the loaded {@link ContractSpaceAggregate} into the\n * {@link CheckSpace} rows the multi-space check iterates — one per on-disk\n * contract-space directory, in the aggregate's `app`-first ordering. Mirrors\n * `migration list`'s `migrationSpaceListEntriesFromAggregate`: space\n * membership matches the on-disk directories, package / ref / graph data come\n * from `aggregate.space(id)`.\n */\nexport async function enumerateCheckSpaces(\n aggregate: ContractSpaceAggregate,\n projectMigrationsDir: string,\n): Promise<readonly CheckSpace[]> {\n const candidateDirs = await listContractSpaceDirectories(projectMigrationsDir);\n const onDiskSpaceIds = new Set(\n candidateDirs.filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name)).filter(isValidSpaceId),\n );\n const spaces: CheckSpace[] = [];\n for (const member of aggregate.spaces()) {\n const spaceId = member.spaceId;\n if (!isValidSpaceId(spaceId)) continue;\n if (!onDiskSpaceIds.has(spaceId)) continue;\n const migrationsDir = spaceMigrationDirectory(projectMigrationsDir, spaceId);\n spaces.push({\n spaceId,\n packages: member.packages,\n refs: member.refs,\n graph: member.graph(),\n migrationsDir,\n refsDir: spaceRefsDirectory(migrationsDir),\n });\n }\n return spaces;\n}\n\nfunction checkManifestFilesPresent(space: CheckSpace): readonly CheckFailure[] {\n if (!existsSync(space.migrationsDir)) return [];\n const loadedDirNames = new Set(space.packages.map((p) => p.dirName));\n const failures: CheckFailure[] = [];\n let entries: string[];\n try {\n entries = readdirSync(space.migrationsDir);\n } catch {\n return failures;\n }\n for (const entry of entries) {\n if (entry.startsWith('.') || entry.startsWith('_') || entry === 'refs') continue;\n const entryPath = join(space.migrationsDir, entry);\n try {\n if (!statSync(entryPath).isDirectory()) continue;\n } catch {\n continue;\n }\n if (!loadedDirNames.has(entry)) {\n for (const f of ['migration.json', 'ops.json']) {\n const fail = checkFileExists(space.spaceId, entryPath, entry, f);\n if (fail) failures.push(fail);\n }\n }\n }\n return failures;\n}\n\nfunction checkReachability(space: CheckSpace): readonly CheckFailure[] {\n const allToHashes = new Set(space.packages.map((p) => p.metadata.to));\n const failures: CheckFailure[] = [];\n for (const pkg of space.packages) {\n const isReachable =\n pkg.metadata.from === null ||\n allToHashes.has(pkg.metadata.from) ||\n pkg.metadata.from === 'sha256:empty';\n if (!isReachable) {\n failures.push({\n space: space.spaceId,\n code: 'PN-MIG-CHECK-003',\n where: migrationPathRelative(pkg.dirPath),\n why: `Migration \"${pkg.dirName}\" starts from ${pkg.metadata.from} which no other migration produces`,\n fix: 'This migration is unreachable in the graph. Delete it or re-emit a connecting migration.',\n });\n }\n }\n return failures;\n}\n\nfunction checkDanglingRefs(space: CheckSpace): readonly CheckFailure[] {\n const failures: CheckFailure[] = [];\n for (const [name, entry] of Object.entries(space.refs)) {\n if (!space.graph.nodes.has(entry.hash)) {\n failures.push({\n space: space.spaceId,\n code: 'PN-MIG-CHECK-004',\n where: relative(process.cwd(), join(space.refsDir, `${name}.json`)),\n why: `Ref \"${name}\" points at ${entry.hash} which does not exist in the migration graph`,\n fix: `Update the ref with \\`prisma-next ref set ${name} <valid-hash>\\` or delete it.`,\n });\n }\n }\n return failures;\n}\n\nfunction checkSpace(space: CheckSpace): readonly CheckFailure[] {\n return [\n ...checkManifestFilesPresent(space),\n ...space.packages\n .map((pkg) => checkSnapshotConsistency(space.spaceId, pkg))\n .filter((f): f is CheckFailure => f !== null),\n ...checkReachability(space),\n ...checkDanglingRefs(space),\n ];\n}\n\n/**\n * Inputs for {@link runMigrationCheck} — the multi-space policy core of\n * the holistic (no-arg) `migration check`. Enumeration is supplied by the\n * caller (the CLI shell builds it from {@link enumerateCheckSpaces}); the\n * core does not touch config, flags, or streams.\n */\nexport interface RunMigrationCheckInputs {\n readonly spaces: readonly CheckSpace[];\n readonly spaceFilter?: string;\n}\n\n/**\n * Policy core of the holistic `migration check`: validates `--space`,\n * narrows the pre-enumerated spaces, and runs the per-space explicit graph\n * checks (file-existence, snapshot consistency, reachability, dangling\n * refs), aggregating every failure into one {@link MigrationCheckResult}.\n *\n * `--space` validation mirrors `migration list`: an invalid id →\n * {@link errorInvalidSpaceId}; an id with no on-disk space →\n * {@link errorSpaceNotFound}. Both map to exit `PRECONDITION` at the shell.\n * Aggregate-integrity violations (which already span every space) are folded\n * in by the caller, not here.\n */\nexport function runMigrationCheck(\n inputs: RunMigrationCheckInputs,\n): Result<MigrationCheckResult, CliStructuredError> {\n const { spaces, spaceFilter } = inputs;\n\n if (spaceFilter !== undefined && !isValidSpaceId(spaceFilter)) {\n return notOk(errorInvalidSpaceId(spaceFilter));\n }\n if (spaceFilter !== undefined && !spaces.some((s) => s.spaceId === spaceFilter)) {\n return notOk(errorSpaceNotFound(spaceFilter, spaces.map((s) => s.spaceId).sort()));\n }\n\n const scopedSpaces =\n spaceFilter !== undefined ? spaces.filter((s) => s.spaceId === spaceFilter) : spaces;\n\n const failures = scopedSpaces.flatMap(checkSpace);\n if (failures.length === 0) {\n return ok({ ok: true, failures: [], summary: 'All checks passed' });\n }\n return ok({ ok: false, failures, summary: `${failures.length} integrity failure(s)` });\n}\n\nasync function loadAggregateIntegrityViolations(\n config: Awaited<ReturnType<typeof loadConfig>>,\n migrationsDir: string,\n): Promise<readonly IntegrityViolation[]> {\n try {\n const contractJsonContent = await readFile(resolveContractPath(config), 'utf-8');\n const familyInstance = config.family.create(createControlStack(config));\n const declaredExtensions = toDeclaredExtensionsFromRaw(config.extensionPacks ?? []);\n\n const parsedAppContract: unknown = JSON.parse(contractJsonContent);\n const aggregate = await loadContractSpaceAggregate({\n migrationsDir,\n deserializeContract: (json: unknown) => familyInstance.deserializeContract(json),\n appContract: familyInstance.deserializeContract(parsedAppContract),\n });\n return aggregate.checkIntegrity({ declaredExtensions, checkContracts: true });\n } catch {\n return [];\n }\n}\n\ninterface MigrationCheckOutcome {\n readonly result?: MigrationCheckResult;\n readonly error?: CliStructuredError;\n readonly exitCode: number;\n readonly resolvedSpaceId?: string;\n}\n\nasync function executeMigrationCheckCommand(\n target: string | undefined,\n options: MigrationCheckOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<MigrationCheckOutcome> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative } =\n resolveMigrationPaths(options.config, config);\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: appMigrationsRelative },\n ];\n if (target) {\n details.push({ label: 'target', value: target });\n }\n const header = formatStyledHeader({\n command: 'migration check',\n description: 'Verify artifact and graph integrity',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n const loadedAggregate = await buildReadAggregate(config, { migrationsDir });\n if (!loadedAggregate.ok) {\n return { error: loadedAggregate.failure, exitCode: PRECONDITION };\n }\n\n const spaces = await enumerateCheckSpaces(loadedAggregate.value.aggregate, migrationsDir);\n\n if (target) {\n return await checkSingleTarget(target, {\n spaces,\n ...(options.space !== undefined ? { spaceFilter: options.space } : {}),\n appMigrationsDir,\n appMigrationsRelative,\n });\n }\n\n const checkResult = runMigrationCheck({\n spaces,\n ...(options.space !== undefined ? { spaceFilter: options.space } : {}),\n });\n if (!checkResult.ok) {\n return { error: checkResult.failure, exitCode: PRECONDITION };\n }\n\n const failures: CheckFailure[] = [...checkResult.value.failures];\n const allViolations = await loadAggregateIntegrityViolations(config, migrationsDir);\n const scopedViolations =\n options.space === undefined\n ? allViolations\n : allViolations.filter((v) => v.kind !== 'disjointness' && v.spaceId === options.space);\n for (const violation of scopedViolations) {\n failures.push(integrityViolationToCheckFailure(violation, migrationsDir));\n }\n\n if (failures.length === 0) {\n return {\n result: { ok: true, failures: [], summary: 'All checks passed' },\n exitCode: OK,\n };\n }\n\n return {\n result: { ok: false, failures, summary: `${failures.length} integrity failure(s)` },\n exitCode: INTEGRITY_FAILED,\n };\n}\n\ninterface SingleTargetInputs {\n readonly spaces: readonly CheckSpace[];\n readonly spaceFilter?: string;\n readonly appMigrationsDir: string;\n readonly appMigrationsRelative: string;\n}\n\n/**\n * Ranks ref-resolution failure kinds by how informative they are, so a\n * single-target check surfaces the most useful failure across spaces instead of\n * whichever space failed first. `not-found` (the input matched nothing here)\n * says the least; a malformed input, a wrong grammar, or an in-space ambiguity\n * all say more.\n */\nfunction refFailureSpecificity(error: RefResolutionError): number {\n switch (error.kind) {\n case 'wrong-grammar':\n return 3;\n case 'ambiguous':\n return 2;\n case 'invalid-format':\n return 1;\n case 'not-found':\n return 0;\n }\n}\n\n/**\n * Single-target (`check <ref/path>`) mode — resolves a migration reference\n * across all contract spaces (or the one space narrowed by `--space <id>`).\n *\n * Resolution:\n * - filesystem path → find the owning space by checking which space's\n * `migrationsDir` contains the resolved path; falls back to app-relative\n * validation when the path is outside every space dir.\n * - ref → `parseMigrationRef` against each in-scope space; collect every\n * (space, package) hit; 0 hits = not-found, 1 = check it, >1 = ambiguity\n * error (qualify with `--space`).\n *\n * `--space <id>` is validated the same way the holistic path does it:\n * invalid id → `errorInvalidSpaceId`; no on-disk space → `errorSpaceNotFound`.\n */\nasync function checkSingleTarget(\n target: string,\n inputs: SingleTargetInputs,\n): Promise<MigrationCheckOutcome> {\n const { spaces, spaceFilter, appMigrationsDir, appMigrationsRelative } = inputs;\n\n if (spaceFilter !== undefined && !isValidSpaceId(spaceFilter)) {\n return { error: errorInvalidSpaceId(spaceFilter), exitCode: PRECONDITION };\n }\n if (spaceFilter !== undefined && !spaces.some((s) => s.spaceId === spaceFilter)) {\n return {\n error: errorSpaceNotFound(spaceFilter, spaces.map((s) => s.spaceId).sort()),\n exitCode: PRECONDITION,\n };\n }\n\n const scopedSpaces =\n spaceFilter !== undefined ? spaces.filter((s) => s.spaceId === spaceFilter) : spaces;\n\n let matchedSpace: CheckSpace | undefined;\n let matchedPkg: OnDiskMigrationPackage | undefined;\n\n if (looksLikePath(target)) {\n const resolvedPath = resolveTargetPathAcrossSpaces(target, scopedSpaces);\n if (resolvedPath !== null) {\n for (const space of scopedSpaces) {\n const found = findPackageByDirPath(space.packages, resolvedPath);\n if (found) {\n matchedSpace = space;\n matchedPkg = found;\n break;\n }\n }\n } else {\n // Path outside every space dir — fall back to app-relative validation\n const resolved = resolveAppTargetPath(target, appMigrationsDir, appMigrationsRelative);\n if (!resolved.ok) {\n return { error: resolved.failure, exitCode: PRECONDITION };\n }\n const appSpace = scopedSpaces.find((s) => s.spaceId === 'app');\n if (appSpace) {\n matchedSpace = appSpace;\n matchedPkg = findPackageByDirPath(appSpace.packages, resolved.value);\n }\n }\n } else {\n // Ref resolution: try each in-scope space, collect all hits.\n const hits: Array<{ space: CheckSpace; pkg: OnDiskMigrationPackage }> = [];\n let bestParseFailure: RefResolutionError | undefined;\n for (const space of scopedSpaces) {\n const migResult = parseMigrationRef(target, { graph: space.graph, refs: space.refs });\n if (!migResult.ok) {\n // Keep scanning — a later space may hold a hit that must not be discarded.\n // When no space yields a hit, keep the most informative failure rather than\n // whichever space failed first (the kind is space-dependent).\n if (\n bestParseFailure === undefined ||\n refFailureSpecificity(migResult.failure) > refFailureSpecificity(bestParseFailure)\n ) {\n bestParseFailure = migResult.failure;\n }\n continue;\n }\n const pkg = space.packages.find(\n (p) => p.metadata.migrationHash === migResult.value.migrationHash,\n );\n if (pkg) {\n hits.push({ space, pkg });\n }\n }\n\n if (hits.length > 1) {\n const spaceIds = hits.map((h) => h.space.spaceId);\n return {\n error: errorAmbiguousMigrationRef(target, spaceIds),\n exitCode: PRECONDITION,\n };\n }\n\n if (hits.length === 1) {\n matchedSpace = hits[0]!.space;\n matchedPkg = hits[0]!.pkg;\n } else if (bestParseFailure !== undefined) {\n // The ref didn't resolve in any in-scope space — surface the most informative\n // parse failure through the shared ref-resolution envelope (PN-RUN-3000) the\n // earlier work established, rather than a bespoke string. (Ref-resolved-but-\n // no-package falls through to the \"not found on disk\" result below.)\n return { error: mapRefResolutionError(bestParseFailure), exitCode: PRECONDITION };\n }\n }\n\n if (!matchedPkg || !matchedSpace) {\n return {\n result: {\n ok: false,\n failures: [],\n summary: `Migration package for \"${target}\" not found on disk`,\n },\n exitCode: PRECONDITION,\n };\n }\n\n const failures: CheckFailure[] = [...checkManifestFilesPresent(matchedSpace)];\n\n for (const f of ['migration.json', 'ops.json']) {\n const fail = checkFileExists(matchedSpace.spaceId, matchedPkg.dirPath, matchedPkg.dirName, f);\n if (fail) failures.push(fail);\n }\n\n const verification = verifyMigrationHash(matchedPkg);\n if (!verification.ok) {\n failures.push({\n space: matchedSpace.spaceId,\n code: 'PN-MIG-CHECK-001',\n where: migrationFileRelative(matchedPkg.dirPath, 'migration.json'),\n why: `Stored hash ${verification.storedHash} does not match recomputed hash ${verification.computedHash}`,\n fix: 'Re-emit the migration package or restore from version control.',\n });\n }\n\n const snapshotFailure = checkSnapshotConsistency(matchedSpace.spaceId, matchedPkg);\n if (snapshotFailure) failures.push(snapshotFailure);\n\n const resolvedSpaceId = matchedSpace.spaceId !== 'app' ? matchedSpace.spaceId : undefined;\n\n if (failures.length === 0) {\n return {\n result: { ok: true, failures: [], summary: 'All checks passed' },\n exitCode: OK,\n ...ifDefined('resolvedSpaceId', resolvedSpaceId),\n };\n }\n return {\n result: { ok: false, failures, summary: `${failures.length} integrity failure(s)` },\n exitCode: INTEGRITY_FAILED,\n ...ifDefined('resolvedSpaceId', resolvedSpaceId),\n };\n}\n\nexport function createMigrationCheckCommand(): Command {\n const command = new Command('check');\n setCommandDescriptions(\n command,\n 'Verify artifact and graph integrity',\n 'Validates that on-disk migration packages are internally consistent\\n' +\n '(hashes match, manifests are complete) and that the graph is well-formed\\n' +\n '(edges connect, refs point at valid nodes). The whole-graph check spans\\n' +\n 'every contract space by default; pass --space <id> to narrow to one. A\\n' +\n 'migration reference checks a single package, resolved across all contract\\n' +\n 'spaces (narrow with --space; an ambiguous reference is a precondition failure).\\n' +\n 'Offline — does not consult the database.\\n' +\n 'Exit codes: 0 = all checks passed, 2 = precondition failed\\n' +\n '(unresolved target or unknown --space), 4 = integrity failure(s) found.',\n );\n setCommandExamples(command, [\n 'prisma-next migration check',\n 'prisma-next migration check --space app',\n 'prisma-next migration check 20260101-add-users',\n 'prisma-next migration check 20260101-add-users --space app',\n 'prisma-next migration check --json',\n ]);\n setCommandSeeAlso(command, [\n { verb: 'migration status', oneLiner: 'Show migration path and pending status' },\n { verb: 'migration list', oneLiner: 'List on-disk migrations' },\n { verb: 'migration graph', oneLiner: 'Show the migration graph topology' },\n { verb: 'migration show', oneLiner: 'Display migration package contents' },\n ]);\n command.exitOverride();\n addGlobalOptions(command)\n .argument('[target]', 'Migration reference: directory name, hash/prefix, ref, or path')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--space <id>', 'Narrow output to a single contract space')\n .action(async (target: string | undefined, options: MigrationCheckOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n\n let outcome: MigrationCheckOutcome;\n try {\n outcome = await executeMigrationCheckCommand(target, options, flags, ui);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n outcome = {\n result: { ok: false, failures: [], summary: msg },\n exitCode: PRECONDITION,\n };\n }\n\n if (outcome.error) {\n const envelope = outcome.error.toEnvelope();\n if (flags.json) {\n ui.output(formatErrorJson(envelope));\n } else if (!flags.quiet) {\n ui.error(formatErrorOutput(envelope, flags));\n }\n process.exit(outcome.exitCode);\n }\n\n const result = outcome.result ?? {\n ok: false,\n failures: [],\n summary: 'No check result produced',\n };\n\n if (flags.json) {\n ui.output(JSON.stringify(result, null, 2));\n } else if (!flags.quiet) {\n if (result.ok) {\n const spaceSuffix =\n outcome.resolvedSpaceId !== undefined ? ` (space: ${outcome.resolvedSpaceId})` : '';\n ui.log(`✔ ${result.summary}${spaceSuffix}`);\n } else {\n for (const f of result.failures) {\n ui.log(`✗ [${f.code}] ${f.where}: ${f.why}`);\n ui.log(` fix: ${f.fix}`);\n }\n ui.log(`\\n${result.summary}`);\n }\n }\n\n process.exit(outcome.exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAMA,SAASA,wBAAsB,SAAyB;CACtD,OAAO,SAAS,QAAQ,IAAI,GAAG,OAAO;AACxC;AAEA,SAASC,wBAAsB,SAAiB,UAA0B;CACxE,OAAO,KAAKD,wBAAsB,OAAO,GAAG,QAAQ;AACtD;;;;;AAMA,SAAgB,iCACd,WACA,eACc;CACd,MAAM,iBAAiB,YACrBA,wBAAsB,KAAK,eAAe,OAAO,CAAC;CACpD,MAAM,mBAAmB,SAAiB,YACxCA,wBAAsB,KAAK,eAAe,SAAS,OAAO,CAAC;CAC7D,MAAM,eAAe,SAAiB,YACpCA,wBAAsB,KAAK,eAAe,SAAS,QAAQ,GAAG,QAAQ,MAAM,CAAC;CAE/E,QAAQ,UAAU,MAAlB;EACE,KAAK,gBACH,OAAO;GACL,OAAO,UAAU;GACjB,MAAM;GACN,OAAOC,wBACL,KAAK,eAAe,UAAU,SAAS,UAAU,OAAO,GACxD,gBAC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AG,IAAI,KAAK,OAAO,SAAS;EAC9B;EAGF,QAAQ,KAAK,QAAQ,QAAQ;CAC/B,CAAC;CAEH,OAAO;AACT"}
|
package/dist/migration-cli.mjs
CHANGED
|
@@ -369,9 +369,9 @@ function readExistingMetadata(metadataPath) {
|
|
|
369
369
|
* legitimate site for combining config loading, stack assembly, and
|
|
370
370
|
* filesystem persistence.
|
|
371
371
|
*/
|
|
372
|
-
function serializeMigrationToDisk(instance, migrationDir, dryRun, stdout) {
|
|
372
|
+
async function serializeMigrationToDisk(instance, migrationDir, dryRun, stdout) {
|
|
373
373
|
const metadataPath = join(migrationDir, "migration.json");
|
|
374
|
-
const { opsJson, metadataJson } = buildMigrationArtifacts(instance, readExistingMetadata(metadataPath));
|
|
374
|
+
const { opsJson, metadataJson } = await buildMigrationArtifacts(instance, readExistingMetadata(metadataPath));
|
|
375
375
|
if (dryRun) {
|
|
376
376
|
stdout.write(`--- migration.json ---\n${metadataJson}\n`);
|
|
377
377
|
stdout.write("--- ops.json ---\n");
|
|
@@ -398,7 +398,7 @@ async function runMigration(importMetaUrl, MigrationClass, parsed, ctx) {
|
|
|
398
398
|
migrationTargetId: probe.targetId,
|
|
399
399
|
configTargetId: config.target.targetId
|
|
400
400
|
});
|
|
401
|
-
serializeMigrationToDisk(new MigrationClass(createControlStack(config)), migrationDir, parsed.dryRun, ctx.stdout);
|
|
401
|
+
await serializeMigrationToDisk(new MigrationClass(createControlStack(config)), migrationDir, parsed.dryRun, ctx.stdout);
|
|
402
402
|
ctx.stderr;
|
|
403
403
|
}
|
|
404
404
|
//#endregion
|