@prisma-next/cli 0.3.0-dev.14 → 0.3.0-dev.16
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/chunk-5MPKZYVI.js +47 -0
- package/dist/chunk-5MPKZYVI.js.map +1 -0
- package/dist/chunk-74IELXRA.js +371 -0
- package/dist/chunk-74IELXRA.js.map +1 -0
- package/dist/{chunk-MG7PBERL.js → chunk-U6QI3AZ3.js} +7 -5
- package/dist/{chunk-MG7PBERL.js.map → chunk-U6QI3AZ3.js.map} +1 -1
- package/dist/{chunk-DIJPT5TZ.js → chunk-ZG5T6OB5.js} +2 -46
- package/dist/chunk-ZG5T6OB5.js.map +1 -0
- package/dist/cli.js +593 -268
- package/dist/cli.js.map +1 -1
- package/dist/commands/contract-emit.js +3 -2
- package/dist/commands/db-init.d.ts.map +1 -1
- package/dist/commands/db-init.js +238 -275
- package/dist/commands/db-init.js.map +1 -1
- package/dist/commands/db-introspect.js +6 -4
- package/dist/commands/db-introspect.js.map +1 -1
- package/dist/commands/db-schema-verify.js +6 -4
- package/dist/commands/db-schema-verify.js.map +1 -1
- package/dist/commands/db-sign.js +6 -4
- package/dist/commands/db-sign.js.map +1 -1
- package/dist/commands/db-verify.js +6 -4
- package/dist/commands/db-verify.js.map +1 -1
- package/dist/control-api/operations/db-init.d.ts +3 -1
- package/dist/control-api/operations/db-init.d.ts.map +1 -1
- package/dist/control-api/types.d.ts +54 -1
- package/dist/control-api/types.d.ts.map +1 -1
- package/dist/exports/control-api.d.ts +1 -1
- package/dist/exports/control-api.d.ts.map +1 -1
- package/dist/exports/control-api.js +3 -234
- package/dist/exports/control-api.js.map +1 -1
- package/dist/exports/index.js +3 -2
- package/dist/exports/index.js.map +1 -1
- package/dist/utils/progress-adapter.d.ts +26 -0
- package/dist/utils/progress-adapter.d.ts.map +1 -0
- package/package.json +10 -10
- package/src/commands/db-init.ts +262 -355
- package/src/control-api/client.ts +30 -0
- package/src/control-api/operations/db-init.ts +116 -2
- package/src/control-api/types.ts +63 -1
- package/src/exports/control-api.ts +3 -0
- package/src/utils/progress-adapter.ts +86 -0
- package/dist/chunk-DIJPT5TZ.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-init.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type {\n MigrationPlan,\n MigrationPlannerResult,\n MigrationPlanOperation,\n MigrationRunnerResult,\n} from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { redactDatabaseUrl } from '@prisma-next/utils/redact-db-url';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport {\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorJsonFormatNotSupported,\n errorMigrationPlanningFailed,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n type DbInitResult,\n formatCommandHelp,\n formatDbInitApplyOutput,\n formatDbInitJson,\n formatDbInitPlanOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbInitOptions {\n readonly db?: string;\n readonly config?: string;\n readonly plan?: boolean;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Bootstrap a database to match the current contract and write the contract marker',\n 'Initializes a database to match your emitted contract using additive-only operations.\\n' +\n 'Creates any missing tables, columns, indexes, and constraints defined in your contract.\\n' +\n 'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\\n' +\n 'would be required, and writes a contract marker to track the database state. Use --plan to\\n' +\n 'preview changes without applying.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--plan', 'Preview planned operations without applying', false)\n .option('--json [format]', 'Output as JSON (object)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbInitOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const result = await performAction(async () => {\n if (flags.json === 'ndjson') {\n throw errorJsonFormatNotSupported({\n command: 'db init',\n format: 'ndjson',\n supportedFormats: ['object'],\n });\n }\n\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n if (options.plan) {\n details.push({ label: 'mode', value: 'plan (dry run)' });\n }\n const header = formatStyledHeader({\n command: 'db init',\n description: 'Bootstrap a database to match the current contract',\n url: 'https://pris.ly/db-init',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n throw errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired({\n why: `Database connection is required for db init (set db.connection in ${configPath}, or pass --db <url>)`,\n });\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired({ why: 'Config.driver is required for db init' });\n }\n const driverDescriptor = config.driver;\n\n // Check target supports migrations via the migrations capability\n if (!config.target.migrations) {\n throw errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n });\n }\n const migrations = config.target.migrations;\n\n let driver: Awaited<ReturnType<(typeof driverDescriptor)['create']>>;\n try {\n driver = await withSpinner(() => driverDescriptor.create(dbConnection), {\n message: 'Connecting to database...',\n flags,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const code = (error as { code?: unknown }).code;\n // Only redact if connection is a string (URL)\n const redacted =\n typeof dbConnection === 'string' ? redactDatabaseUrl(dbConnection) : undefined;\n throw errorRuntime('Database connection failed', {\n why: message,\n fix: 'Verify the database connection, ensure the database is reachable, and confirm credentials/permissions',\n meta: {\n ...(typeof code !== 'undefined' ? { code } : {}),\n ...(redacted ?? {}),\n },\n });\n }\n\n try {\n // Create family instance\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Validate contract\n const contractIR = familyInstance.validateContractIR(contractJson);\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n // Create planner and runner from target migrations capability\n const planner = migrations.createPlanner(familyInstance);\n const runner = migrations.createRunner(familyInstance);\n\n // Introspect live schema\n const schemaIR = await withSpinner(() => familyInstance.introspect({ driver }), {\n message: 'Introspecting database schema...',\n flags,\n });\n\n // Policy for init mode (additive only)\n const policy = { allowedOperationClasses: ['additive'] as const };\n\n // Plan migration\n const plannerResult: MigrationPlannerResult = await withSpinner(\n async () =>\n planner.plan({\n contract: contractIR,\n schema: schemaIR,\n policy,\n frameworkComponents,\n }),\n {\n message: 'Planning migration...',\n flags,\n },\n );\n\n if (plannerResult.kind === 'failure') {\n throw errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts });\n }\n\n const migrationPlan: MigrationPlan = plannerResult.plan;\n\n // Check for existing marker - handle idempotency and mismatch errors\n const existingMarker = await familyInstance.readMarker({ driver });\n if (existingMarker) {\n const markerMatchesDestination =\n existingMarker.coreHash === migrationPlan.destination.coreHash &&\n (!migrationPlan.destination.profileHash ||\n existingMarker.profileHash === migrationPlan.destination.profileHash);\n\n if (markerMatchesDestination) {\n // Already at destination - return success with no operations\n const dbInitResult: DbInitResult = {\n ok: true,\n mode: options.plan ? 'plan' : 'apply',\n plan: {\n targetId: migrationPlan.targetId,\n destination: migrationPlan.destination,\n operations: [],\n },\n ...(options.plan\n ? {}\n : {\n execution: { operationsPlanned: 0, operationsExecuted: 0 },\n marker: {\n coreHash: existingMarker.coreHash,\n profileHash: existingMarker.profileHash,\n },\n }),\n summary: 'Database already at target contract state',\n timings: { total: Date.now() - startTime },\n };\n return dbInitResult;\n }\n\n // Marker exists but doesn't match destination - fail\n const coreHashMismatch = existingMarker.coreHash !== migrationPlan.destination.coreHash;\n const profileHashMismatch =\n migrationPlan.destination.profileHash &&\n existingMarker.profileHash !== migrationPlan.destination.profileHash;\n\n const mismatchParts: string[] = [];\n if (coreHashMismatch) {\n mismatchParts.push(\n `coreHash (marker: ${existingMarker.coreHash}, destination: ${migrationPlan.destination.coreHash})`,\n );\n }\n if (profileHashMismatch) {\n mismatchParts.push(\n `profileHash (marker: ${existingMarker.profileHash}, destination: ${migrationPlan.destination.profileHash})`,\n );\n }\n\n throw errorRuntime(\n `Existing contract marker does not match plan destination. Mismatch in ${mismatchParts.join(' and ')}.`,\n {\n why: 'Database has an existing contract marker that does not match the target contract',\n fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',\n meta: {\n code: 'MARKER_ORIGIN_MISMATCH',\n markerCoreHash: existingMarker.coreHash,\n destinationCoreHash: migrationPlan.destination.coreHash,\n ...(existingMarker.profileHash\n ? { markerProfileHash: existingMarker.profileHash }\n : {}),\n ...(migrationPlan.destination.profileHash\n ? { destinationProfileHash: migrationPlan.destination.profileHash }\n : {}),\n },\n },\n );\n }\n\n // Plan mode - don't execute\n if (options.plan) {\n const dbInitResult: DbInitResult = {\n ok: true,\n mode: 'plan',\n plan: {\n targetId: migrationPlan.targetId,\n destination: migrationPlan.destination,\n operations: migrationPlan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n },\n summary: `Planned ${migrationPlan.operations.length} operation(s)`,\n timings: { total: Date.now() - startTime },\n };\n return dbInitResult;\n }\n\n // Apply mode - execute runner\n // Log main message once, then show individual operations via callbacks\n if (!flags.quiet && flags.json !== 'object') {\n console.log('Applying migration plan and verifying schema...');\n }\n\n const callbacks = {\n onOperationStart: (op: MigrationPlanOperation) => {\n if (!flags.quiet && flags.json !== 'object') {\n console.log(` → ${op.label}...`);\n }\n },\n onOperationComplete: (_op: MigrationPlanOperation) => {\n // Could log completion if needed\n },\n };\n\n const runnerResult: MigrationRunnerResult = await runner.execute({\n plan: migrationPlan,\n driver,\n destinationContract: contractIR,\n policy,\n callbacks,\n // db init plans and applies back-to-back from a fresh introspection, so per-operation\n // pre/postchecks and the idempotency probe are usually redundant overhead. We still\n // enforce marker/origin compatibility and a full schema verification after apply.\n executionChecks: {\n prechecks: false,\n postchecks: false,\n idempotencyChecks: false,\n },\n frameworkComponents,\n });\n\n if (!runnerResult.ok) {\n const meta: Record<string, unknown> = {\n code: runnerResult.failure.code,\n ...(runnerResult.failure.meta ?? {}),\n };\n const sqlState = typeof meta['sqlState'] === 'string' ? meta['sqlState'] : undefined;\n const fix =\n sqlState === '42501'\n ? 'Grant the database user sufficient privileges (insufficient_privilege), or run db init as a more privileged role'\n : runnerResult.failure.code === 'SCHEMA_VERIFY_FAILED'\n ? 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`'\n : undefined;\n\n throw errorRuntime(runnerResult.failure.summary, {\n why:\n runnerResult.failure.why ?? `Migration runner failed: ${runnerResult.failure.code}`,\n ...(fix ? { fix } : {}),\n meta,\n });\n }\n\n const execution = runnerResult.value;\n\n const dbInitResult: DbInitResult = {\n ok: true,\n mode: 'apply',\n plan: {\n targetId: migrationPlan.targetId,\n destination: migrationPlan.destination,\n operations: migrationPlan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n },\n execution: {\n operationsPlanned: execution.operationsPlanned,\n operationsExecuted: execution.operationsExecuted,\n },\n marker: migrationPlan.destination.profileHash\n ? {\n coreHash: migrationPlan.destination.coreHash,\n profileHash: migrationPlan.destination.profileHash,\n }\n : { coreHash: migrationPlan.destination.coreHash },\n summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,\n timings: { total: Date.now() - startTime },\n };\n return dbInitResult;\n } finally {\n await driver.close();\n }\n });\n\n // Handle result\n const exitCode = handleResult(result, flags, (dbInitResult) => {\n if (flags.json === 'object') {\n console.log(formatDbInitJson(dbInitResult));\n } else {\n const output =\n dbInitResult.mode === 'plan'\n ? formatDbInitPlanOutput(dbInitResult, flags)\n : formatDbInitApplyOutput(dbInitResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAOlC,SAAS,+BAA+B;AACxC,SAAS,yBAAyB;AAClC,SAAS,eAAe;AA+CjB,SAAS,sBAA+B;AAC7C,QAAM,UAAU,IAAI,QAAQ,MAAM;AAClC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAKF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,UAAU,+CAA+C,KAAK,EACrE,OAAO,mBAAmB,2BAA2B,KAAK,EAC1D,OAAO,eAAe,yBAAyB,EAC/C,OAAO,iBAAiB,qCAAqC,EAC7D,OAAO,gBAAgB,4CAA4C,EACnE,OAAO,gBAAgB,0BAA0B,EACjD,OAAO,WAAW,oBAAoB,EACtC,OAAO,cAAc,sBAAsB,EAC3C,OAAO,OAAO,YAA2B;AACxC,UAAM,QAAQ,iBAAiB,OAAO;AACtC,UAAM,YAAY,KAAK,IAAI;AAE3B,UAAM,SAAS,MAAM,cAAc,YAAY;AAC7C,UAAI,MAAM,SAAS,UAAU;AAC3B,cAAM,4BAA4B;AAAA,UAChC,SAAS;AAAA,UACT,QAAQ;AAAA,UACR,kBAAkB,CAAC,QAAQ;AAAA,QAC7B,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A,EACvB,CAAC;AAEH,SAAO;AACT;","names":["dbInitResult"]}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-init.ts","../../src/utils/progress-adapter.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { DbInitFailure } from '../control-api/types';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorJsonFormatNotSupported,\n errorMigrationPlanningFailed,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n type DbInitResult,\n formatCommandHelp,\n formatDbInitApplyOutput,\n formatDbInitJson,\n formatDbInitPlanOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\n\ninterface DbInitOptions {\n readonly db?: string;\n readonly config?: string;\n readonly plan?: boolean;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\n/**\n * Maps a DbInitFailure to a CliStructuredError for consistent error handling.\n */\nfunction mapDbInitFailure(failure: DbInitFailure): CliStructuredError {\n if (failure.code === 'PLANNING_FAILED') {\n return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });\n }\n\n if (failure.code === 'MARKER_ORIGIN_MISMATCH') {\n const mismatchParts: string[] = [];\n if (\n failure.marker?.coreHash !== failure.destination?.coreHash &&\n failure.marker?.coreHash &&\n failure.destination?.coreHash\n ) {\n mismatchParts.push(\n `coreHash (marker: ${failure.marker.coreHash}, destination: ${failure.destination.coreHash})`,\n );\n }\n if (\n failure.marker?.profileHash !== failure.destination?.profileHash &&\n failure.marker?.profileHash &&\n failure.destination?.profileHash\n ) {\n mismatchParts.push(\n `profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`,\n );\n }\n\n return errorRuntime(\n `Existing contract marker does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(' and ')}.` : ''}`,\n {\n why: 'Database has an existing contract marker that does not match the target contract',\n fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',\n meta: {\n code: 'MARKER_ORIGIN_MISMATCH',\n ...(failure.marker?.coreHash ? { markerCoreHash: failure.marker.coreHash } : {}),\n ...(failure.destination?.coreHash\n ? { destinationCoreHash: failure.destination.coreHash }\n : {}),\n ...(failure.marker?.profileHash ? { markerProfileHash: failure.marker.profileHash } : {}),\n ...(failure.destination?.profileHash\n ? { destinationProfileHash: failure.destination.profileHash }\n : {}),\n },\n },\n );\n }\n\n if (failure.code === 'RUNNER_FAILED') {\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`',\n meta: {\n code: 'RUNNER_FAILED',\n ...(failure.meta ?? {}),\n },\n });\n }\n\n // Exhaustive check - TypeScript will error if a new code is added but not handled\n const exhaustive: never = failure.code;\n throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);\n}\n\n/**\n * Executes the db init command and returns a structured Result.\n */\nasync function executeDbInitCommand(\n options: DbInitOptions,\n flags: GlobalFlags,\n startTime: number,\n): Promise<Result<DbInitResult, CliStructuredError>> {\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n if (options.plan) {\n details.push({ label: 'mode', value: 'plan (dry run)' });\n }\n const header = formatStyledHeader({\n command: 'db init',\n description: 'Bootstrap a database to match the current contract',\n url: 'https://pris.ly/db-init',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for db init (set db.connection in ${configPath}, or pass --db <url>)`,\n }),\n );\n }\n\n // Check for driver\n if (!config.driver) {\n return notOk(errorDriverRequired({ why: 'Config.driver is required for db init' }));\n }\n\n // Check target supports migrations via the migrations capability\n if (!config.target.migrations) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n // Create control client\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ flags });\n\n try {\n // Call dbInit with connection and progress callback\n // Connection happens inside dbInit with a 'connect' progress span\n const result = await client.dbInit({\n contractIR: contractJson,\n mode: options.plan ? 'plan' : 'apply',\n connection: dbConnection,\n onProgress,\n });\n\n // Handle failures by mapping to CLI structured error\n if (!result.ok) {\n return notOk(mapDbInitFailure(result.failure));\n }\n\n // Convert success result to CLI output format\n const profileHash = result.value.marker?.profileHash;\n const dbInitResult: DbInitResult = {\n ok: true,\n mode: result.value.mode,\n plan: {\n targetId: config.target.targetId,\n destination: {\n coreHash: result.value.marker?.coreHash ?? '',\n ...(profileHash ? { profileHash } : {}),\n },\n operations: result.value.plan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n },\n ...(result.value.execution\n ? {\n execution: {\n operationsPlanned: result.value.execution.operationsPlanned,\n operationsExecuted: result.value.execution.operationsExecuted,\n },\n }\n : {}),\n ...(result.value.marker\n ? {\n marker: {\n coreHash: result.value.marker.coreHash,\n ...(result.value.marker.profileHash\n ? { profileHash: result.value.marker.profileHash }\n : {}),\n },\n }\n : {}),\n summary: result.value.summary,\n timings: { total: Date.now() - startTime },\n };\n\n return ok(dbInitResult);\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n // Use static type guard to work across module boundaries\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n // Wrap unexpected errors\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during db init: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Bootstrap a database to match the current contract and write the contract marker',\n 'Initializes a database to match your emitted contract using additive-only operations.\\n' +\n 'Creates any missing tables, columns, indexes, and constraints defined in your contract.\\n' +\n 'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\\n' +\n 'would be required, and writes a contract marker to track the database state. Use --plan to\\n' +\n 'preview changes without applying.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--plan', 'Preview planned operations without applying', false)\n .option('--json [format]', 'Output as JSON (object)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbInitOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n // Validate JSON format option\n if (flags.json === 'ndjson') {\n const result = notOk(\n errorJsonFormatNotSupported({\n command: 'db init',\n format: 'ndjson',\n supportedFormats: ['object'],\n }),\n );\n const exitCode = handleResult(result, flags);\n process.exit(exitCode);\n }\n\n const result = await executeDbInitCommand(options, flags, startTime);\n\n const exitCode = handleResult(result, flags, (dbInitResult) => {\n if (flags.json === 'object') {\n console.log(formatDbInitJson(dbInitResult));\n } else {\n const output =\n dbInitResult.mode === 'plan'\n ? formatDbInitPlanOutput(dbInitResult, flags)\n : formatDbInitApplyOutput(dbInitResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n","import ora from 'ora';\nimport type { ControlProgressEvent, OnControlProgress } from '../control-api/types';\nimport type { GlobalFlags } from './global-flags';\n\n/**\n * Options for creating a progress adapter.\n */\ninterface ProgressAdapterOptions {\n /**\n * Global flags that control progress output behavior (quiet, json, color).\n */\n readonly flags: GlobalFlags;\n}\n\n/**\n * State for tracking active spans in the progress adapter.\n */\ninterface SpanState {\n readonly spinner: ReturnType<typeof ora>;\n readonly startTime: number;\n}\n\n/**\n * Creates a progress adapter that converts control-api progress events\n * into CLI spinner/progress output.\n *\n * The adapter:\n * - Starts/succeeds spinners for top-level span boundaries\n * - Prints per-operation lines for nested spans (e.g., migration operations under 'apply')\n * - Respects quiet/json/non-TTY flags (no-op in those cases)\n *\n * @param options - Progress adapter configuration\n * @returns An onProgress callback compatible with control-api operations\n */\nexport function createProgressAdapter(options: ProgressAdapterOptions): OnControlProgress {\n const { flags } = options;\n\n // Skip progress if quiet, JSON output, or non-TTY\n const shouldShowProgress = !flags.quiet && flags.json !== 'object' && process.stdout.isTTY;\n\n if (!shouldShowProgress) {\n // Return a no-op callback\n return () => {\n // No-op\n };\n }\n\n // Track active spans by spanId\n const activeSpans = new Map<string, SpanState>();\n\n return (event: ControlProgressEvent) => {\n if (event.kind === 'spanStart') {\n // Nested spans (with parentSpanId) are printed as lines, not spinners\n if (event.parentSpanId) {\n console.log(` → ${event.label}...`);\n return;\n }\n\n // Top-level spans get a spinner\n const spinner = ora({\n text: event.label,\n color: flags.color !== false ? 'cyan' : false,\n }).start();\n\n activeSpans.set(event.spanId, {\n spinner,\n startTime: Date.now(),\n });\n } else if (event.kind === 'spanEnd') {\n // Complete the spinner for this span (only top-level spans have spinners)\n const spanState = activeSpans.get(event.spanId);\n if (spanState) {\n const elapsed = Date.now() - spanState.startTime;\n if (event.outcome === 'error') {\n spanState.spinner.fail(`${spanState.spinner.text} (failed)`);\n } else if (event.outcome === 'skipped') {\n spanState.spinner.info(`${spanState.spinner.text} (skipped)`);\n } else {\n spanState.spinner.succeed(`${spanState.spinner.text} (${elapsed}ms)`);\n }\n activeSpans.delete(event.spanId);\n }\n // Nested span ends are no-ops (could log completion if needed)\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAClC,SAAS,OAAO,UAAuB;AACvC,SAAS,eAAe;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Aa,SAAS,SAClB,uBAAuB,cAAc,KAAK,IAC1C,wBAAwB,cAAc,KAAK;AACjD,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AAED,YAAQ,KAAK,QAAQ;AAAA,EACvB,CAAC;AAEH,SAAO;AACT;","names":["result","exitCode"]}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
assertContractRequirementsSatisfied
|
|
3
3
|
} from "../chunk-6EPKRATC.js";
|
|
4
|
+
import {
|
|
5
|
+
performAction,
|
|
6
|
+
withSpinner
|
|
7
|
+
} from "../chunk-5MPKZYVI.js";
|
|
4
8
|
import {
|
|
5
9
|
formatCommandHelp,
|
|
6
10
|
formatIntrospectJson,
|
|
@@ -8,10 +12,8 @@ import {
|
|
|
8
12
|
formatStyledHeader,
|
|
9
13
|
handleResult,
|
|
10
14
|
parseGlobalFlags,
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
withSpinner
|
|
14
|
-
} from "../chunk-DIJPT5TZ.js";
|
|
15
|
+
setCommandDescriptions
|
|
16
|
+
} from "../chunk-ZG5T6OB5.js";
|
|
15
17
|
import {
|
|
16
18
|
loadConfig
|
|
17
19
|
} from "../chunk-HWYQOCAJ.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-introspect.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { CoreSchemaView } from '@prisma-next/core-control-plane/schema-view';\nimport type { IntrospectSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { assertContractRequirementsSatisfied } from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatIntrospectJson,\n formatIntrospectOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbIntrospectOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbIntrospectCommand(): Command {\n const command = new Command('introspect');\n setCommandDescriptions(\n command,\n 'Inspect the database schema',\n 'Reads the live database schema and displays it as a tree structure. This command\\n' +\n 'does not check the schema against your contract - it only shows what exists in\\n' +\n 'the database. Use `db verify` or `db schema-verify` to compare against your contract.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbIntrospectOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n const startTime = Date.now();\n\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n\n // Optionally load contract if contract config exists\n let contractIR: unknown | undefined;\n if (config.contract?.output) {\n const contractPath = resolve(config.contract.output);\n try {\n const contractJsonContent = await readFile(contractPath, 'utf-8');\n contractIR = JSON.parse(contractJsonContent);\n } catch (error) {\n // Contract file is optional for introspection - don't fail if it doesn't exist\n if (error instanceof Error && (error as { code?: string }).code !== 'ENOENT') {\n throw errorUnexpected(error.message, {\n why: `Failed to read contract file: ${error.message}`,\n });\n }\n }\n }\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n ];\n if (options.db) {\n // Mask password in URL for security\n const maskedUrl = options.db.replace(/:([^:@]+)@/, ':****@');\n details.push({ label: 'database', value: maskedUrl });\n } else if (config.db?.connection && typeof config.db.connection === 'string') {\n // Mask password in URL for security\n const maskedUrl = config.db.connection.replace(/:([^:@]+)@/, ':****@');\n details.push({ label: 'database', value: maskedUrl });\n }\n const header = formatStyledHeader({\n command: 'db introspect',\n description: 'Inspect the database schema',\n url: 'https://pris.ly/db-introspect',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n // Create family instance\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract IR if we loaded it\n if (contractIR) {\n const validatedContract = familyInstance.validateContractIR(contractIR);\n assertContractRequirementsSatisfied({ contract: validatedContract, stack });\n contractIR = validatedContract;\n }\n\n // Call family instance introspect method\n let schemaIR: unknown;\n try {\n schemaIR = await withSpinner(\n () =>\n familyInstance.introspect({\n driver,\n contractIR,\n }),\n {\n message: 'Introspecting database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from introspect() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Optionally call toSchemaView if available\n let schemaView: CoreSchemaView | undefined;\n if (familyInstance.toSchemaView) {\n try {\n schemaView = familyInstance.toSchemaView(schemaIR);\n } catch (error) {\n // Schema view projection is optional - log but don't fail\n if (flags.verbose) {\n console.error(\n `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n const totalTime = Date.now() - startTime;\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n // Build result envelope\n // Get masked connection URL for meta (only for string connections)\n const connectionForMeta =\n typeof dbConnection === 'string'\n ? dbConnection.replace(/:([^:@]+)@/, ':****@')\n : undefined;\n\n const introspectResult: IntrospectSchemaResult<unknown> = {\n ok: true,\n summary: 'Schema introspected successfully',\n target: {\n familyId: config.family.familyId,\n id: config.target.targetId,\n },\n schema: schemaIR,\n ...(configPath || connectionForMeta\n ? {\n meta: {\n ...(configPath ? { configPath } : {}),\n ...(connectionForMeta ? { dbUrl: connectionForMeta } : {}),\n },\n }\n : {}),\n timings: {\n total: totalTime,\n },\n };\n\n return { introspectResult, schemaView };\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (value) => {\n const { introspectResult, schemaView } = value;\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatIntrospectJson(introspectResult));\n } else {\n // Human-readable output to stdout\n const output = formatIntrospectOutput(introspectResult, schemaView, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAClC;AAAA,E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YACP,OAAO;AAAA,UACT;AAAA,QACF;AAEA,eAAO,EAAE,kBAAkB,WAAW;AAAA,MACxC,UAAE;AAEA,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF,CAAC;AAGD,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,UAAU;AACtD,YAAM,EAAE,kBAAkB,WAAW,IAAI;AAEzC,UAAI,MAAM,SAAS,UAAU;AAE3B,gBAAQ,IAAI,qBAAqB,gBAAgB,CAAC;AAAA,MACpD,OAAO;AAEL,cAAM,SAAS,uBAAuB,kBAAkB,YAAY,KAAK;AACzE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AACD,YAAQ,KAAK,QAAQ;AAAA,EACvB,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-introspect.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { CoreSchemaView } from '@prisma-next/core-control-plane/schema-view';\nimport type { IntrospectSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { assertContractRequirementsSatisfied } from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatIntrospectJson,\n formatIntrospectOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbIntrospectOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbIntrospectCommand(): Command {\n const command = new Command('introspect');\n setCommandDescriptions(\n command,\n 'Inspect the database schema',\n 'Reads the live database schema and displays it as a tree structure. This command\\n' +\n 'does not check the schema against your contract - it only shows what exists in\\n' +\n 'the database. Use `db verify` or `db schema-verify` to compare against your contract.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbIntrospectOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n const startTime = Date.now();\n\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n\n // Optionally load contract if contract config exists\n let contractIR: unknown | undefined;\n if (config.contract?.output) {\n const contractPath = resolve(config.contract.output);\n try {\n const contractJsonContent = await readFile(contractPath, 'utf-8');\n contractIR = JSON.parse(contractJsonContent);\n } catch (error) {\n // Contract file is optional for introspection - don't fail if it doesn't exist\n if (error instanceof Error && (error as { code?: string }).code !== 'ENOENT') {\n throw errorUnexpected(error.message, {\n why: `Failed to read contract file: ${error.message}`,\n });\n }\n }\n }\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n ];\n if (options.db) {\n // Mask password in URL for security\n const maskedUrl = options.db.replace(/:([^:@]+)@/, ':****@');\n details.push({ label: 'database', value: maskedUrl });\n } else if (config.db?.connection && typeof config.db.connection === 'string') {\n // Mask password in URL for security\n const maskedUrl = config.db.connection.replace(/:([^:@]+)@/, ':****@');\n details.push({ label: 'database', value: maskedUrl });\n }\n const header = formatStyledHeader({\n command: 'db introspect',\n description: 'Inspect the database schema',\n url: 'https://pris.ly/db-introspect',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n // Create family instance\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract IR if we loaded it\n if (contractIR) {\n const validatedContract = familyInstance.validateContractIR(contractIR);\n assertContractRequirementsSatisfied({ contract: validatedContract, stack });\n contractIR = validatedContract;\n }\n\n // Call family instance introspect method\n let schemaIR: unknown;\n try {\n schemaIR = await withSpinner(\n () =>\n familyInstance.introspect({\n driver,\n contractIR,\n }),\n {\n message: 'Introspecting database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from introspect() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Optionally call toSchemaView if available\n let schemaView: CoreSchemaView | undefined;\n if (familyInstance.toSchemaView) {\n try {\n schemaView = familyInstance.toSchemaView(schemaIR);\n } catch (error) {\n // Schema view projection is optional - log but don't fail\n if (flags.verbose) {\n console.error(\n `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n const totalTime = Date.now() - startTime;\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n // Build result envelope\n // Get masked connection URL for meta (only for string connections)\n const connectionForMeta =\n typeof dbConnection === 'string'\n ? dbConnection.replace(/:([^:@]+)@/, ':****@')\n : undefined;\n\n const introspectResult: IntrospectSchemaResult<unknown> = {\n ok: true,\n summary: 'Schema introspected successfully',\n target: {\n familyId: config.family.familyId,\n id: config.target.targetId,\n },\n schema: schemaIR,\n ...(configPath || connectionForMeta\n ? {\n meta: {\n ...(configPath ? { configPath } : {}),\n ...(connectionForMeta ? { dbUrl: connectionForMeta } : {}),\n },\n }\n : {}),\n timings: {\n total: totalTime,\n },\n };\n\n return { introspectResult, schemaView };\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (value) => {\n const { introspectResult, schemaView } = value;\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatIntrospectJson(introspectResult));\n } else {\n // Human-readable output to stdout\n const output = formatIntrospectOutput(introspectResult, schemaView, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,+BAA+B;AACxC,SAAS,eAAe;AA8BjB,SAAS,4BAAqC;AACnD,QAAM,UAAU,IAAI,QAAQ,YAAY;AACxC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAGF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB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AAA,MACpD,OAAO;AAEL,cAAM,SAAS,uBAAuB,kBAAkB,YAAY,KAAK;AACzE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AACD,YAAQ,KAAK,QAAQ;AAAA,EACvB,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
@@ -2,6 +2,10 @@ import {
|
|
|
2
2
|
assertContractRequirementsSatisfied,
|
|
3
3
|
assertFrameworkComponentsCompatible
|
|
4
4
|
} from "../chunk-6EPKRATC.js";
|
|
5
|
+
import {
|
|
6
|
+
performAction,
|
|
7
|
+
withSpinner
|
|
8
|
+
} from "../chunk-5MPKZYVI.js";
|
|
5
9
|
import {
|
|
6
10
|
formatCommandHelp,
|
|
7
11
|
formatSchemaVerifyJson,
|
|
@@ -9,10 +13,8 @@ import {
|
|
|
9
13
|
formatStyledHeader,
|
|
10
14
|
handleResult,
|
|
11
15
|
parseGlobalFlags,
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
withSpinner
|
|
15
|
-
} from "../chunk-DIJPT5TZ.js";
|
|
16
|
+
setCommandDescriptions
|
|
17
|
+
} from "../chunk-ZG5T6OB5.js";
|
|
16
18
|
import {
|
|
17
19
|
loadConfig
|
|
18
20
|
} from "../chunk-HWYQOCAJ.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-schema-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSchemaVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly strict?: boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbSchemaVerifyCommand(): Command {\n const command = new Command('schema-verify');\n setCommandDescriptions(\n command,\n 'Check whether the database schema satisfies your contract',\n 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\\n' +\n 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\\n' +\n 'verification tree. This is a read-only operation that does not modify the database.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('--strict', 'Strict mode: extra schema elements cause failures', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSchemaVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db schema-verify',\n description: 'Check whether the database schema satisfies your contract',\n url: 'https://pris.ly/db-schema-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Check for driver (needed for family instance creation)\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create family instance (needed for contract validation)\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract using instance validator\n const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;\n\n // Validate contract requirements fail-fast before connecting to database\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Call family instance schemaVerify method\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n () =>\n familyInstance.schemaVerify({\n driver,\n contractIR,\n strict: options.strict ?? false,\n contractPath: contractPathAbsolute,\n configPath,\n frameworkComponents,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from schemaVerify() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n // Return result (don't throw for logical mismatches - handle exit code separately)\n return schemaVerifyResult;\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (schemaVerifyResult) => {\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n // Human-readable output to stdout\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n // For logical schema mismatches, check if verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && !result.value.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AAC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ile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSchemaVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly strict?: boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbSchemaVerifyCommand(): Command {\n const command = new Command('schema-verify');\n setCommandDescriptions(\n command,\n 'Check whether the database schema satisfies your contract',\n 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\\n' +\n 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\\n' +\n 'verification tree. This is a read-only operation that does not modify the database.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('--strict', 'Strict mode: extra schema elements cause failures', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSchemaVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db schema-verify',\n description: 'Check whether the database schema satisfies your contract',\n url: 'https://pris.ly/db-schema-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Check for driver (needed for family instance creation)\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create family instance (needed for contract validation)\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract using instance validator\n const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;\n\n // Validate contract requirements fail-fast before connecting to database\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Call family instance schemaVerify method\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n () =>\n familyInstance.schemaVerify({\n driver,\n contractIR,\n strict: options.strict ?? false,\n contractPath: contractPathAbsolute,\n configPath,\n frameworkComponents,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from schemaVerify() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n // Return result (don't throw for logical mismatches - handle exit code separately)\n return schemaVerifyResult;\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (schemaVerifyResult) => {\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n // Human-readable output to stdout\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n // For logical schema mismatches, check if verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && !result.value.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,eAAe;AAkCjB,SAAS,8BAAuC;AACrD,QAAM,UAAU,IAAI,QAAQ,eAAe;AAC3C;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAGF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,mBAAmB,qCAAqC,KAAK,EACpE,OAAO,YAAY,qDAAqD,KAAK,EAC7E,OAAO,eAAe,yBAAyB,EAC/C,OAAO,iBAAiB,qCAAqC,EAC7D,OAAO,gBAAgB,4CAA4C,EACnE,OAAO,gBAAgB,0BAA0B,EACjD,OAAO,WAAW,oBAAoB,EACtC,OAAO,cAAc,sBAAsB,EAC3C,OAAO,OAAO,YAAmC;AAChD,UAAM,QAAQ,iBAAiB,OAAO;AAEtC,UAAM,SAAS,MAAM,cAAc,YAAY;AAE7C,YAAM,SAAS,MAAM,WAAW,QAAQ,MAAM;AAE9C,YAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,IAAI,GAAG,QAAQ,QAAQ,MAAM,CAAC,IAC/C;AACJ,YAAM,uBAAuB,OAAO,UAAU,SAC1C,QAAQ,OAAO,SAAS,MAAM,IAC9B,QAAQ,0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oBAAoB,KAAK;AACjE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AAID,QAAI,OAAO,MAAM,CAAC,OAAO,MAAM,IAAI;AAEjC,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AAEL,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;","names":[]}
|
package/dist/commands/db-sign.js
CHANGED
|
@@ -2,6 +2,10 @@ import {
|
|
|
2
2
|
assertContractRequirementsSatisfied,
|
|
3
3
|
assertFrameworkComponentsCompatible
|
|
4
4
|
} from "../chunk-6EPKRATC.js";
|
|
5
|
+
import {
|
|
6
|
+
performAction,
|
|
7
|
+
withSpinner
|
|
8
|
+
} from "../chunk-5MPKZYVI.js";
|
|
5
9
|
import {
|
|
6
10
|
formatCommandHelp,
|
|
7
11
|
formatSchemaVerifyJson,
|
|
@@ -11,10 +15,8 @@ import {
|
|
|
11
15
|
formatStyledHeader,
|
|
12
16
|
handleResult,
|
|
13
17
|
parseGlobalFlags,
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
withSpinner
|
|
17
|
-
} from "../chunk-DIJPT5TZ.js";
|
|
18
|
+
setCommandDescriptions
|
|
19
|
+
} from "../chunk-ZG5T6OB5.js";
|
|
18
20
|
import {
|
|
19
21
|
loadConfig
|
|
20
22
|
} from "../chunk-HWYQOCAJ.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-sign.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type {\n SignDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatSignJson,\n formatSignOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSignOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbSignCommand(): Command {\n const command = new Command('sign');\n setCommandDescriptions(\n command,\n 'Sign the database with your contract so you can safely run queries',\n 'Verifies that your database schema satisfies the emitted contract, and if so, writes or\\n' +\n 'updates the contract marker in the database. This command is idempotent and safe to run\\n' +\n 'in CI/deployment pipelines. The marker records that this database instance is aligned\\n' +\n 'with a specific contract version.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSignOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db sign',\n description: 'Sign the database with your contract so you can safely run queries',\n url: 'https://pris.ly/db-sign',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create family instance (needed for contract validation - no DB connection required)\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract using instance validator (fail-fast before DB connection)\n const contractIR = familyInstance.validateContractIR(contractJson);\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Create driver (expensive operation - done after validation)\n const driver = await driverDescriptor.create(dbConnection);\n\n try {\n // Schema verification precondition with spinner\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n () =>\n familyInstance.schemaVerify({\n driver,\n contractIR,\n strict: false,\n contractPath: contractPathAbsolute,\n configPath,\n frameworkComponents,\n }),\n {\n message: 'Verifying database satisfies contract',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from schemaVerify() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // If schema verification failed, return both results for handling outside performAction\n if (!schemaVerifyResult.ok) {\n return { schemaVerifyResult, signResult: undefined };\n }\n\n // Schema verification passed - proceed with signing\n let signResult: SignDatabaseResult;\n try {\n signResult = await withSpinner(\n () =>\n familyInstance.sign({\n driver,\n contractIR,\n contractPath: contractPathAbsolute,\n configPath,\n }),\n {\n message: 'Signing database...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from sign() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n return { schemaVerifyResult: undefined, signResult };\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (value) => {\n const { schemaVerifyResult, signResult } = value;\n\n // If schema verification failed, format and print schema verification output\n if (schemaVerifyResult && !schemaVerifyResult.ok) {\n if (flags.json === 'object') {\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n // Don't proceed to sign output formatting\n return;\n }\n\n // Schema verification passed - format sign output\n if (signResult) {\n if (flags.json === 'object') {\n console.log(formatSignJson(signResult));\n } else {\n const output = formatSignOutput(signResult, flags);\n if (output) {\n console.log(output);\n }\n }\n }\n });\n\n // For logical schema mismatches, check if schema verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,+BAA+B;AACxC,SAAS,eAAe;AAmCjB,SAAS,sBAA+B;AAC7C,QAAM,UAAU,IAAI,QAAQ,MAAM;AAClC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAIF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,mBAAmB,qCAAqC,KAAK,EACpE,OAAO,eAAe,yBAAyB,EAC/C,OAAO,iBAAiB,qCAAqC,EAC7D,OAAO,gBAAgB,4CAA4C,EACnE,OAAO,gBAAgB,0BAA0B,EACjD,OAAO,WAAW,oBAAoB,EACtC,OAAO,cAAc,sBAAsB,EAC3C,OAAO,OAAO,YAA2B;AACxC,UAAM,QAAQ,iBAAiB,OAAO;AAEtC,UAAM,SAAS,MAAM,cAAc,YAAY;AAE7C,YAAM,SAAS,MAAM,WAAW,QAAQ,MAA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sources":["../../src/commands/db-sign.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type {\n SignDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatSignJson,\n formatSignOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSignOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbSignCommand(): Command {\n const command = new Command('sign');\n setCommandDescriptions(\n command,\n 'Sign the database with your contract so you can safely run queries',\n 'Verifies that your database schema satisfies the emitted contract, and if so, writes or\\n' +\n 'updates the contract marker in the database. This command is idempotent and safe to run\\n' +\n 'in CI/deployment pipelines. The marker records that this database instance is aligned\\n' +\n 'with a specific contract version.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSignOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db sign',\n description: 'Sign the database with your contract so you can safely run queries',\n url: 'https://pris.ly/db-sign',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create family instance (needed for contract validation - no DB connection required)\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract using instance validator (fail-fast before DB connection)\n const contractIR = familyInstance.validateContractIR(contractJson);\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Create driver (expensive operation - done after validation)\n const driver = await driverDescriptor.create(dbConnection);\n\n try {\n // Schema verification precondition with spinner\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n () =>\n familyInstance.schemaVerify({\n driver,\n contractIR,\n strict: false,\n contractPath: contractPathAbsolute,\n configPath,\n frameworkComponents,\n }),\n {\n message: 'Verifying database satisfies contract',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from schemaVerify() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // If schema verification failed, return both results for handling outside performAction\n if (!schemaVerifyResult.ok) {\n return { schemaVerifyResult, signResult: undefined };\n }\n\n // Schema verification passed - proceed with signing\n let signResult: SignDatabaseResult;\n try {\n signResult = await withSpinner(\n () =>\n familyInstance.sign({\n driver,\n contractIR,\n contractPath: contractPathAbsolute,\n configPath,\n }),\n {\n message: 'Signing database...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from sign() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n return { schemaVerifyResult: undefined, signResult };\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (value) => {\n const { schemaVerifyResult, signResult } = value;\n\n // If schema verification failed, format and print schema verification output\n if (schemaVerifyResult && !schemaVerifyResult.ok) {\n if (flags.json === 'object') {\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n // Don't proceed to sign output formatting\n return;\n }\n\n // Schema verification passed - format sign output\n if (signResult) {\n if (flags.json === 'object') {\n console.log(formatSignJson(signResult));\n } else {\n const output = formatSignOutput(signResult, flags);\n if (output) {\n console.log(output);\n }\n }\n }\n });\n\n // For logical schema mismatches, check if schema verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,+BAA+B;AACxC,SAAS,eAAe;AAmCjB,SAAS,sBAA+B;AAC7C,QAAM,UAAU,IAAI,QAAQ,MAAM;AAClC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAIF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,mBAAmB,qCAAqC,KAAK,EACpE,OAA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;AACV,oBAAQ,IAAI,MAAM;AAAA,UACpB;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAID,QAAI,OAAO,MAAM,OAAO,MAAM,sBAAsB,CAAC,OAAO,MAAM,mBAAmB,IAAI;AAEvF,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AAEL,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
assertContractRequirementsSatisfied
|
|
3
3
|
} from "../chunk-6EPKRATC.js";
|
|
4
|
+
import {
|
|
5
|
+
performAction,
|
|
6
|
+
withSpinner
|
|
7
|
+
} from "../chunk-5MPKZYVI.js";
|
|
4
8
|
import {
|
|
5
9
|
formatCommandHelp,
|
|
6
10
|
formatStyledHeader,
|
|
@@ -8,10 +12,8 @@ import {
|
|
|
8
12
|
formatVerifyOutput,
|
|
9
13
|
handleResult,
|
|
10
14
|
parseGlobalFlags,
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
withSpinner
|
|
14
|
-
} from "../chunk-DIJPT5TZ.js";
|
|
15
|
+
setCommandDescriptions
|
|
16
|
+
} from "../chunk-ZG5T6OB5.js";
|
|
15
17
|
import {
|
|
16
18
|
loadConfig
|
|
17
19
|
} from "../chunk-HWYQOCAJ.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorHashMismatch,\n errorMarkerMissing,\n errorRuntime,\n errorTargetMismatch,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { assertContractRequirementsSatisfied } from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatStyledHeader,\n formatVerifyJson,\n formatVerifyOutput,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbVerifyCommand(): Command {\n const command = new Command('verify');\n setCommandDescriptions(\n command,\n 'Check whether the database has been signed with your contract',\n 'Verifies that your database schema matches the emitted contract. Checks table structures,\\n' +\n 'column types, constraints, and codec coverage. Reports any mismatches or missing codecs.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db verify',\n description: 'Check whether the database has been signed with your contract',\n url: 'https://pris.ly/db-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n // Create family instance\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract using instance validator\n const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n // Call family instance verify method\n let verifyResult: VerifyDatabaseResult;\n try {\n verifyResult = await withSpinner(\n () =>\n familyInstance.verify({\n driver,\n contractIR,\n expectedTargetId: config.target.targetId,\n contractPath: contractPathAbsolute,\n configPath,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from verify() in structured error\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // If verification failed, throw structured error\n if (!verifyResult.ok && verifyResult.code) {\n if (verifyResult.code === 'PN-RTM-3001') {\n throw errorMarkerMissing();\n }\n if (verifyResult.code === 'PN-RTM-3002') {\n throw errorHashMismatch({\n expected: verifyResult.contract.coreHash,\n ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),\n });\n }\n if (verifyResult.code === 'PN-RTM-3003') {\n throw errorTargetMismatch(\n verifyResult.target.expected,\n verifyResult.target.actual ?? 'unknown',\n );\n }\n throw errorRuntime(verifyResult.summary);\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n return verifyResult;\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (verifyResult) => {\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatVerifyJson(verifyResult));\n } else {\n // Human-readable output to stdout\n const output = formatVerifyOutput(verifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,eAAe;AA8BjB,SAAS,wBAAiC;AAC/C,QAAM,UAAU,IAAI,QAAQ,QAAQ;AACpC;AAAA,IACE;AAAA,IACA;AAAA,IAC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"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorHashMismatch,\n errorMarkerMissing,\n errorRuntime,\n errorTargetMismatch,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { assertContractRequirementsSatisfied } from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatStyledHeader,\n formatVerifyJson,\n formatVerifyOutput,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbVerifyCommand(): Command {\n const command = new Command('verify');\n setCommandDescriptions(\n command,\n 'Check whether the database has been signed with your contract',\n 'Verifies that your database schema matches the emitted contract. Checks table structures,\\n' +\n 'column types, constraints, and codec coverage. Reports any mismatches or missing codecs.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db verify',\n description: 'Check whether the database has been signed with your contract',\n url: 'https://pris.ly/db-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n // Create family instance\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract using instance validator\n const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n // Call family instance verify method\n let verifyResult: VerifyDatabaseResult;\n try {\n verifyResult = await withSpinner(\n () =>\n familyInstance.verify({\n driver,\n contractIR,\n expectedTargetId: config.target.targetId,\n contractPath: contractPathAbsolute,\n configPath,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from verify() in structured error\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // If verification failed, throw structured error\n if (!verifyResult.ok && verifyResult.code) {\n if (verifyResult.code === 'PN-RTM-3001') {\n throw errorMarkerMissing();\n }\n if (verifyResult.code === 'PN-RTM-3002') {\n throw errorHashMismatch({\n expected: verifyResult.contract.coreHash,\n ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),\n });\n }\n if (verifyResult.code === 'PN-RTM-3003') {\n throw errorTargetMismatch(\n verifyResult.target.expected,\n verifyResult.target.actual ?? 'unknown',\n );\n }\n throw errorRuntime(verifyResult.summary);\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n return verifyResult;\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (verifyResult) => {\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatVerifyJson(verifyResult));\n } else {\n // Human-readable output to stdout\n const output = formatVerifyOutput(verifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"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UAAI,MAAM,SAAS,UAAU;AAE3B,gBAAQ,IAAI,iBAAiB,YAAY,CAAC;AAAA,MAC5C,OAAO;AAEL,cAAM,SAAS,mBAAmB,cAAc,KAAK;AACrD,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AACD,YAAQ,KAAK,QAAQ;AAAA,EACvB,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { TargetBoundComponentDescriptor } from '@prisma-next/contract/framework-components';
|
|
2
2
|
import type { ContractIR } from '@prisma-next/contract/ir';
|
|
3
3
|
import type { ControlDriverInstance, ControlFamilyInstance, TargetMigrationsCapability } from '@prisma-next/core-control-plane/types';
|
|
4
|
-
import type { DbInitResult } from '../types';
|
|
4
|
+
import type { DbInitResult, OnControlProgress } from '../types';
|
|
5
5
|
/**
|
|
6
6
|
* Options for executing dbInit operation.
|
|
7
7
|
*/
|
|
@@ -12,6 +12,8 @@ export interface ExecuteDbInitOptions<TFamilyId extends string, TTargetId extend
|
|
|
12
12
|
readonly mode: 'plan' | 'apply';
|
|
13
13
|
readonly migrations: TargetMigrationsCapability<TFamilyId, TTargetId, ControlFamilyInstance<TFamilyId>>;
|
|
14
14
|
readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;
|
|
15
|
+
/** Optional progress callback for observing operation progress */
|
|
16
|
+
readonly onProgress?: OnControlProgress;
|
|
15
17
|
}
|
|
16
18
|
/**
|
|
17
19
|
* Executes the dbInit operation.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db-init.d.ts","sourceRoot":"","sources":["../../../src/control-api/operations/db-init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AACjG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,KAAK,E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