@prisma-next/cli 0.16.0-dev.3 → 0.16.0-dev.31
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/README.md +44 -45
- package/dist/cli.mjs +13 -13
- package/dist/{client-KuBQftxz.mjs → client-B1UjQc_x.mjs} +50 -58
- package/dist/client-B1UjQc_x.mjs.map +1 -0
- package/dist/{command-helpers-Cpq44aVa.mjs → command-helpers-D-jBl0Qt.mjs} +16 -8
- package/dist/command-helpers-D-jBl0Qt.mjs.map +1 -0
- package/dist/commands/contract-emit.mjs +1 -1
- package/dist/commands/contract-infer.mjs +1 -1
- package/dist/commands/db-init.d.mts.map +1 -1
- package/dist/commands/db-init.mjs +8 -6
- package/dist/commands/db-init.mjs.map +1 -1
- package/dist/commands/db-schema.mjs +3 -3
- package/dist/commands/db-sign.d.mts.map +1 -1
- package/dist/commands/db-sign.mjs +11 -12
- package/dist/commands/db-sign.mjs.map +1 -1
- package/dist/commands/db-update.d.mts.map +1 -1
- package/dist/commands/db-update.mjs +14 -15
- package/dist/commands/db-update.mjs.map +1 -1
- package/dist/commands/db-verify.mjs +1 -1
- package/dist/commands/migrate.d.mts +1 -1
- package/dist/commands/migrate.d.mts.map +1 -1
- package/dist/commands/migrate.mjs +13 -13
- package/dist/commands/migrate.mjs.map +1 -1
- package/dist/commands/migration-check.d.mts +4 -2
- package/dist/commands/migration-check.d.mts.map +1 -1
- package/dist/commands/migration-check.mjs +1 -1
- package/dist/commands/migration-graph.d.mts +1 -1
- package/dist/commands/migration-graph.mjs +4 -4
- package/dist/commands/migration-list.d.mts +1 -1
- package/dist/commands/migration-list.d.mts.map +1 -1
- package/dist/commands/migration-list.mjs +1 -1
- package/dist/commands/migration-log.d.mts +1 -1
- package/dist/commands/migration-log.mjs +1 -1
- package/dist/commands/migration-new.d.mts.map +1 -1
- package/dist/commands/migration-new.mjs +16 -40
- package/dist/commands/migration-new.mjs.map +1 -1
- package/dist/commands/migration-plan.d.mts +3 -4
- package/dist/commands/migration-plan.d.mts.map +1 -1
- package/dist/commands/migration-plan.mjs +1 -1
- package/dist/commands/migration-show.mjs +5 -5
- package/dist/commands/migration-show.mjs.map +1 -1
- package/dist/commands/migration-status.d.mts +1 -1
- package/dist/commands/migration-status.d.mts.map +1 -1
- package/dist/commands/migration-status.mjs +1 -1
- package/dist/commands/ref.d.mts +1 -1
- package/dist/commands/ref.d.mts.map +1 -1
- package/dist/commands/ref.mjs +13 -18
- package/dist/commands/ref.mjs.map +1 -1
- package/dist/commands/telemetry/index.mjs +1 -1
- package/dist/contract-at-errors-DvZ_DzJK.mjs +36 -0
- package/dist/contract-at-errors-DvZ_DzJK.mjs.map +1 -0
- package/dist/{contract-emit-CgnXSANN.mjs → contract-emit-BT46Mu8Q.mjs} +3 -3
- package/dist/{contract-emit-CgnXSANN.mjs.map → contract-emit-BT46Mu8Q.mjs.map} +1 -1
- package/dist/{contract-emit-cJQBlvGb.mjs → contract-emit-hVdlaF2U.mjs} +6 -7
- package/dist/{contract-emit-cJQBlvGb.mjs.map → contract-emit-hVdlaF2U.mjs.map} +1 -1
- package/dist/{contract-enrichment-gn9sWbPw.mjs → contract-enrichment-JUhLv-BX.mjs} +8 -8
- package/dist/{contract-enrichment-gn9sWbPw.mjs.map → contract-enrichment-JUhLv-BX.mjs.map} +1 -1
- package/dist/{contract-infer-Cg8evbeg.mjs → contract-infer-DpqTQECL.mjs} +3 -3
- package/dist/{contract-infer-Cg8evbeg.mjs.map → contract-infer-DpqTQECL.mjs.map} +1 -1
- package/dist/{contract-space-aggregate-loader-D_3VeHVb.mjs → contract-space-aggregate-loader-CNd-ZB6C.mjs} +14 -14
- package/dist/contract-space-aggregate-loader-CNd-ZB6C.mjs.map +1 -0
- package/dist/{db-verify-BEclUzki.mjs → db-verify-FEN6k1m7.mjs} +10 -8
- package/dist/db-verify-FEN6k1m7.mjs.map +1 -0
- package/dist/exports/control-api.d.mts +4 -4
- package/dist/exports/control-api.d.mts.map +1 -1
- package/dist/exports/control-api.mjs +3 -3
- package/dist/exports/index.d.mts +2 -1
- package/dist/exports/index.d.mts.map +1 -1
- package/dist/exports/index.mjs +61 -21
- package/dist/exports/index.mjs.map +1 -1
- package/dist/exports/init-output.d.mts.map +1 -1
- package/dist/exports/init-output.mjs +1 -1
- package/dist/{format-DAUAZqPt.mjs → format-DI5qVr22.mjs} +8 -7
- package/dist/format-DI5qVr22.mjs.map +1 -0
- package/dist/{framework-components-CnbUbiJw.mjs → framework-components-C4XACYNB.mjs} +3 -3
- package/dist/framework-components-C4XACYNB.mjs.map +1 -0
- package/dist/{init-C3JhkHg-.mjs → init-ClrRkbwd.mjs} +77 -67
- package/dist/init-ClrRkbwd.mjs.map +1 -0
- package/dist/{inspect-live-schema-CX7EA5C3.mjs → inspect-live-schema-C0Rgdtw_.mjs} +4 -4
- package/dist/{inspect-live-schema-CX7EA5C3.mjs.map → inspect-live-schema-C0Rgdtw_.mjs.map} +1 -1
- package/dist/{migration-check-MHT3w7_v.mjs → migration-check-zEkHpPDT.mjs} +58 -30
- package/dist/migration-check-zEkHpPDT.mjs.map +1 -0
- package/dist/{migration-command-scaffold-CRyYrHZ9.mjs → migration-command-scaffold-CkNsp9g1.mjs} +4 -4
- package/dist/{migration-command-scaffold-CRyYrHZ9.mjs.map → migration-command-scaffold-CkNsp9g1.mjs.map} +1 -1
- package/dist/{migration-graph-command-render-B83xrnNy.mjs → migration-graph-command-render-DEwFpx-w.mjs} +5 -4
- package/dist/migration-graph-command-render-DEwFpx-w.mjs.map +1 -0
- package/dist/{migration-list-BAKujUjh.mjs → migration-list-BkafFVXS.mjs} +6 -6
- package/dist/migration-list-BkafFVXS.mjs.map +1 -0
- package/dist/{migration-log-C_xam2HZ.mjs → migration-log-BxhAtbhA.mjs} +5 -5
- package/dist/{migration-log-C_xam2HZ.mjs.map → migration-log-BxhAtbhA.mjs.map} +1 -1
- package/dist/{migration-path-target-DpPTsRCg.mjs → migration-path-target-B5HkjSTO.mjs} +2 -2
- package/dist/{migration-path-target-DpPTsRCg.mjs.map → migration-path-target-B5HkjSTO.mjs.map} +1 -1
- package/dist/{migration-plan-CreSVtWZ.mjs → migration-plan-Bk2pbPQH.mjs} +64 -74
- package/dist/migration-plan-Bk2pbPQH.mjs.map +1 -0
- package/dist/{migration-status-YgEvXf-u.mjs → migration-status-BzlARseq.mjs} +13 -12
- package/dist/migration-status-BzlARseq.mjs.map +1 -0
- package/dist/{output-mEQ74_nd.mjs → output-DWNYqZGc.mjs} +5 -6
- package/dist/output-DWNYqZGc.mjs.map +1 -0
- package/dist/{ref-advancement-BkXlikCA.mjs → ref-advancement-BCz7X7qJ.mjs} +13 -6
- package/dist/ref-advancement-BCz7X7qJ.mjs.map +1 -0
- package/dist/{telemetry-DVr6RFnq.mjs → telemetry-BbniBUbP.mjs} +2 -2
- package/dist/{telemetry-DVr6RFnq.mjs.map → telemetry-BbniBUbP.mjs.map} +1 -1
- package/dist/{types-D4r_HI9-.d.mts → types-DgXprE3w.d.mts} +3 -3
- package/dist/types-DgXprE3w.d.mts.map +1 -0
- package/dist/{verify-CgDVZjhc.mjs → verify-BSaNeaSL.mjs} +2 -2
- package/dist/{verify-CgDVZjhc.mjs.map → verify-BSaNeaSL.mjs.map} +1 -1
- package/package.json +21 -21
- package/src/commands/db-init.ts +5 -3
- package/src/commands/db-sign.ts +9 -7
- package/src/commands/db-update.ts +18 -9
- package/src/commands/db-verify.ts +4 -4
- package/src/commands/format.ts +1 -1
- package/src/commands/init/hygiene-gitattributes.ts +37 -21
- package/src/commands/init/init.ts +6 -6
- package/src/commands/init/output.ts +4 -5
- package/src/commands/init/probe-db.ts +9 -2
- package/src/commands/init/reinit-cleanup.ts +16 -17
- package/src/commands/init/templates/render.ts +2 -1
- package/src/commands/inspect-live-schema.ts +1 -1
- package/src/commands/migrate.ts +6 -5
- package/src/commands/migration-check.ts +72 -34
- package/src/commands/migration-list.ts +1 -5
- package/src/commands/migration-log.ts +1 -1
- package/src/commands/migration-new.ts +17 -41
- package/src/commands/migration-plan.ts +64 -88
- package/src/commands/migration-show.ts +2 -2
- package/src/commands/migration-status.ts +6 -7
- package/src/commands/ref.ts +19 -14
- package/src/control-api/client.ts +43 -25
- package/src/control-api/contract-enrichment.ts +7 -7
- package/src/control-api/operations/contract-emit.ts +2 -3
- package/src/control-api/operations/db-init.ts +3 -3
- package/src/control-api/operations/db-run.ts +8 -7
- package/src/control-api/operations/db-update.ts +2 -2
- package/src/control-api/operations/db-verify.ts +4 -4
- package/src/control-api/operations/format.ts +5 -4
- package/src/control-api/operations/migrate.ts +6 -5
- package/src/control-api/operations/run-migration.ts +2 -1
- package/src/control-api/types.ts +1 -1
- package/src/load-ts-contract.ts +81 -16
- package/src/utils/cli-errors.ts +15 -7
- package/src/utils/combine-verify-results.ts +2 -1
- package/src/utils/command-helpers.ts +15 -5
- package/src/utils/contract-at-errors.ts +13 -22
- package/src/utils/contract-space-aggregate-loader.ts +8 -8
- package/src/utils/contract-space-seed-phase.ts +11 -9
- package/src/utils/extension-pack-inputs.ts +8 -8
- package/src/utils/formatters/migration-graph-grid-layout.ts +2 -1
- package/src/utils/formatters/migration-graph-labels.ts +1 -2
- package/src/utils/formatters/migration-list-data-column.ts +1 -2
- package/src/utils/framework-components.ts +9 -9
- package/src/utils/integrity-violation-to-check-failure.ts +3 -3
- package/src/utils/migration-command-scaffold.ts +1 -1
- package/src/utils/plan-resolution.ts +7 -10
- package/src/utils/ref-advancement.ts +22 -3
- package/dist/client-KuBQftxz.mjs.map +0 -1
- package/dist/command-helpers-Cpq44aVa.mjs.map +0 -1
- package/dist/contract-at-errors-D9gEjYtg.mjs +0 -42
- package/dist/contract-at-errors-D9gEjYtg.mjs.map +0 -1
- package/dist/contract-space-aggregate-loader-D_3VeHVb.mjs.map +0 -1
- package/dist/db-verify-BEclUzki.mjs.map +0 -1
- package/dist/format-DAUAZqPt.mjs.map +0 -1
- package/dist/framework-components-CnbUbiJw.mjs.map +0 -1
- package/dist/init-C3JhkHg-.mjs.map +0 -1
- package/dist/migration-check-MHT3w7_v.mjs.map +0 -1
- package/dist/migration-graph-command-render-B83xrnNy.mjs.map +0 -1
- package/dist/migration-list-BAKujUjh.mjs.map +0 -1
- package/dist/migration-plan-CreSVtWZ.mjs.map +0 -1
- package/dist/migration-status-YgEvXf-u.mjs.map +0 -1
- package/dist/output-mEQ74_nd.mjs.map +0 -1
- package/dist/ref-advancement-BkXlikCA.mjs.map +0 -1
- package/dist/types-D4r_HI9-.d.mts.map +0 -1
- package/src/control-api/errors.ts +0 -9
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as formatStyledHeader, B as errorContractValidationFailed, F as CliStructuredError, G as errorHashMismatch, U as errorDriverRequired, V as errorDatabaseConnectionRequired, W as errorFileNotFound, Y as errorMarkerMissing, _ as createTerminalUI, ct as errorUnexpected, g as parseGlobalFlagsOrExit, i as maskConnectionUrl, l as setCommandDescriptions, o as resolveContractPath, rt as errorRuntime, s as resolveMigrationPaths, st as errorTargetMismatch, t as addGlobalOptions, u as setCommandExamples, y as handleResult } from "./command-helpers-
|
|
1
|
+
import { A as formatStyledHeader, B as errorContractValidationFailed, F as CliStructuredError, G as errorHashMismatch, U as errorDriverRequired, V as errorDatabaseConnectionRequired, W as errorFileNotFound, Y as errorMarkerMissing, _ as createTerminalUI, ct as errorUnexpected, g as parseGlobalFlagsOrExit, i as maskConnectionUrl, l as setCommandDescriptions, o as resolveContractPath, rt as errorRuntime, s as resolveMigrationPaths, st as errorTargetMismatch, t as addGlobalOptions, u as setCommandExamples, y as handleResult } from "./command-helpers-D-jBl0Qt.mjs";
|
|
2
2
|
import { t as createProgressAdapter } from "./progress-adapter-CjAeTxY_.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import { c as formatVerifyOutput, i as formatSchemaVerifyOutput, r as formatSchemaVerifyJson, s as formatVerifyJson } from "./verify-
|
|
3
|
+
import { t as createControlClient } from "./client-B1UjQc_x.mjs";
|
|
4
|
+
import { c as formatVerifyOutput, i as formatSchemaVerifyOutput, r as formatSchemaVerifyJson, s as formatVerifyJson } from "./verify-BSaNeaSL.mjs";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
import { loadConfig } from "@prisma-next/config-loader";
|
|
7
7
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
@@ -9,6 +9,8 @@ import { notOk, ok } from "@prisma-next/utils/result";
|
|
|
9
9
|
import { relative, resolve } from "pathe";
|
|
10
10
|
import { readFile } from "node:fs/promises";
|
|
11
11
|
import { VERIFY_CODE_HASH_MISMATCH, VERIFY_CODE_MARKER_MISSING, VERIFY_CODE_TARGET_MISMATCH, createControlStack } from "@prisma-next/framework-components/control";
|
|
12
|
+
import { InternalError } from "@prisma-next/utils/internal-error";
|
|
13
|
+
import { isStructuredError } from "@prisma-next/utils/structured-error";
|
|
12
14
|
//#region src/utils/combine-verify-results.ts
|
|
13
15
|
/**
|
|
14
16
|
* Collapse the aggregate verifier's per-space contract-satisfaction results
|
|
@@ -36,7 +38,7 @@ import { VERIFY_CODE_HASH_MISMATCH, VERIFY_CODE_MARKER_MISSING, VERIFY_CODE_TARG
|
|
|
36
38
|
*/
|
|
37
39
|
function combineVerifyResults(perSpace, appSpaceId, strict, unclaimed) {
|
|
38
40
|
const appResult = perSpace.get(appSpaceId) ?? perSpace.values().next().value;
|
|
39
|
-
if (appResult === void 0) throw new
|
|
41
|
+
if (appResult === void 0) throw new InternalError("Aggregate verifier returned no per-space verify results — this is a wiring bug.");
|
|
40
42
|
let okAll = true;
|
|
41
43
|
let firstFailure;
|
|
42
44
|
let issues = [];
|
|
@@ -192,7 +194,7 @@ async function resolveVerifySetup(paths, options, mode) {
|
|
|
192
194
|
try {
|
|
193
195
|
contractJson = familyInstance.deserializeContract(JSON.parse(contractJsonContent));
|
|
194
196
|
} catch (error) {
|
|
195
|
-
if (error
|
|
197
|
+
if (isStructuredError(error) && error.code === "CONTRACT.VALIDATION_FAILED") return notOk(errorContractValidationFailed(`Contract validation failed: ${error.message}`, { where: { path: contractPathAbsolute } }));
|
|
196
198
|
return notOk(errorContractValidationFailed(`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`, { where: { path: contractPathAbsolute } }));
|
|
197
199
|
}
|
|
198
200
|
const dbConnection = options.db ?? config.db?.connection;
|
|
@@ -214,12 +216,12 @@ function createVerifyClient(setup) {
|
|
|
214
216
|
target: setup.config.target,
|
|
215
217
|
adapter: setup.config.adapter,
|
|
216
218
|
driver: setup.config.driver,
|
|
217
|
-
|
|
219
|
+
extensions: setup.config.extensions ?? []
|
|
218
220
|
});
|
|
219
221
|
}
|
|
220
222
|
function wrapVerifyError(error, contractPathAbsolute, modeLabel) {
|
|
221
223
|
if (CliStructuredError.is(error)) return notOk(error);
|
|
222
|
-
if (error
|
|
224
|
+
if (isStructuredError(error) && error.code === "CONTRACT.VALIDATION_FAILED") return notOk(errorContractValidationFailed(`Contract validation failed: ${error.message}`, { where: { path: contractPathAbsolute } }));
|
|
223
225
|
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Unexpected error during ${modeLabel}: ${error instanceof Error ? error.message : String(error)}` }));
|
|
224
226
|
}
|
|
225
227
|
/**
|
|
@@ -393,4 +395,4 @@ function createDbVerifyCommand() {
|
|
|
393
395
|
//#endregion
|
|
394
396
|
export { createDbVerifyCommand as t };
|
|
395
397
|
|
|
396
|
-
//# sourceMappingURL=db-verify-
|
|
398
|
+
//# sourceMappingURL=db-verify-FEN6k1m7.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db-verify-FEN6k1m7.mjs","names":[],"sources":["../src/utils/combine-verify-results.ts","../src/commands/db-verify.ts"],"sourcesContent":["import type { VerifyDatabaseSchemaResult } from '@prisma-next/framework-components/control';\nimport { InternalError } from '@prisma-next/utils/internal-error';\n\n/**\n * The combined per-space contract-satisfaction result plus the standalone\n * unclaimed-elements list, reported once. The CLI renders\n * both; `unclaimed` is never folded into the combined tree or its issues.\n */\nexport interface CombinedVerifyResult {\n readonly result: VerifyDatabaseSchemaResult;\n readonly unclaimed: readonly string[];\n}\n\n/**\n * Collapse the aggregate verifier's per-space contract-satisfaction results\n * into a single {@link VerifyDatabaseSchemaResult} for the CLI display\n * surface, and carry the deduplicated unclaimed-elements list alongside it.\n * Concatenates the issue lists across spaces; uses the app space's result as\n * the structural envelope (storage hash, target). Extras are already\n * stripped from each per-space result, so nothing here duplicates an\n * unclaimed element per space.\n *\n * **Unclaimed disposition.** In strict mode a non-empty `unclaimed` list fails\n * the combined verdict (`ok: false`); in lenient mode it is carried for\n * informational rendering only. The list itself is returned unchanged for the\n * renderer.\n *\n * **Summary policy.** Preserve the per-family phrasing whenever the\n * combined `ok` flag agrees with the app space's `ok` flag — this is\n * the common case (single-family deployments, single-app deployments)\n * and the family's \"satisfies / does not satisfy contract\" phrasing\n * stays user-visible. When the app passes but an extension fails (or\n * vice versa) the app's summary contradicts the envelope, so fall back\n * to the first failing space's summary. This keeps family phrasing\n * intact and the envelope internally consistent (`ok: false` ↔ failure\n * summary).\n */\nexport function combineVerifyResults(\n perSpace: ReadonlyMap<string, VerifyDatabaseSchemaResult>,\n appSpaceId: string,\n strict: boolean,\n unclaimed: readonly string[],\n): CombinedVerifyResult {\n const appResult = perSpace.get(appSpaceId) ?? perSpace.values().next().value;\n if (appResult === undefined) {\n throw new InternalError(\n 'Aggregate verifier returned no per-space verify results — this is a wiring bug.',\n );\n }\n\n let okAll = true;\n let firstFailure: VerifyDatabaseSchemaResult | undefined;\n let issues: VerifyDatabaseSchemaResult['schema']['issues'] = [];\n let warningIssues: VerifyDatabaseSchemaResult['schema']['issues'] = [];\n for (const [, result] of perSpace) {\n if (!result.ok) {\n okAll = false;\n if (firstFailure === undefined) firstFailure = result;\n }\n issues = [...issues, ...result.schema.issues];\n warningIssues = [...warningIssues, ...(result.schema.warnings?.issues ?? [])];\n }\n\n const unclaimedFails = strict && unclaimed.length > 0;\n const ok = okAll && !unclaimedFails;\n\n // Prefer a failing space's family phrasing; else, when only the unclaimed list\n // fails the verdict, say so; else keep the app space's phrasing. When `okAll`\n // is false the loop assigned `firstFailure`, so the `?? appResult.summary`\n // fallback is unreachable — it exists only to keep the read cast-free.\n const summary = okAll\n ? unclaimedFails\n ? `Database schema has ${unclaimed.length} unclaimed element${unclaimed.length === 1 ? '' : 's'} (not in any contract)`\n : appResult.summary\n : appResult.ok\n ? (firstFailure?.summary ?? appResult.summary)\n : appResult.summary;\n\n return {\n result: {\n ok,\n ...(ok ? {} : { code: appResult.code ?? 'CONTRACT.MARKER_REQUIRED' }),\n summary,\n contract: appResult.contract,\n target: appResult.target,\n schema: {\n issues,\n warnings: { issues: warningIssues },\n },\n meta: { strict },\n timings: { total: 0 },\n },\n unclaimed,\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport { loadConfig } from '@prisma-next/config-loader';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { VerifyDatabaseResult } from '@prisma-next/framework-components/control';\nimport {\n createControlStack,\n VERIFY_CODE_HASH_MISMATCH,\n VERIFY_CODE_MARKER_MISSING,\n VERIFY_CODE_TARGET_MISMATCH,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { isStructuredError } from '@prisma-next/utils/structured-error';\nimport { Command } from 'commander';\nimport { relative, resolve } from 'pathe';\nimport { createControlClient } from '../control-api/client';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorHashMismatch,\n errorMarkerMissing,\n errorRuntime,\n errorTargetMismatch,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { type CombinedVerifyResult, combineVerifyResults } from '../utils/combine-verify-results';\nimport {\n addGlobalOptions,\n maskConnectionUrl,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport {\n type DbVerifyCommandSuccessResult,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatVerifyJson,\n formatVerifyOutput,\n} from '../utils/formatters/verify';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface DbVerifyOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly markerOnly?: boolean;\n readonly schemaOnly?: boolean;\n readonly strict?: boolean;\n}\n\ntype DbVerifyMode = 'full' | 'marker-only' | 'schema-only';\n\n/**\n * Maps a VerifyDatabaseResult failure to a CliStructuredError.\n */\nfunction mapVerifyFailure(verifyResult: VerifyDatabaseResult): CliStructuredError {\n if (!verifyResult.ok && verifyResult.code) {\n if (verifyResult.code === VERIFY_CODE_MARKER_MISSING) {\n return errorMarkerMissing();\n }\n if (verifyResult.code === VERIFY_CODE_HASH_MISMATCH) {\n const storageMatch = verifyResult.marker?.storageHash === verifyResult.contract.storageHash;\n const profileMatch =\n !verifyResult.contract.profileHash ||\n verifyResult.marker?.profileHash === verifyResult.contract.profileHash;\n\n if (!storageMatch) {\n return errorHashMismatch({\n why: 'Contract storageHash does not match database marker',\n expected: verifyResult.contract.storageHash,\n ...ifDefined('actual', verifyResult.marker?.storageHash),\n });\n }\n\n return errorHashMismatch({\n why: profileMatch\n ? 'Contract hash does not match database marker'\n : 'Contract profileHash does not match database marker',\n ...ifDefined('expected', verifyResult.contract.profileHash),\n ...ifDefined('actual', verifyResult.marker?.profileHash),\n });\n }\n if (verifyResult.code === VERIFY_CODE_TARGET_MISMATCH) {\n return errorTargetMismatch(\n verifyResult.target.expected,\n verifyResult.target.actual ?? 'unknown',\n );\n }\n // Unknown code - fall through to runtime error\n }\n return errorRuntime(verifyResult.summary);\n}\n\ntype DbVerifyFailure = CliStructuredError | CombinedVerifyResult;\n\nfunction errorInvalidVerifyMode(options: {\n readonly why: string;\n readonly fix: string;\n}): CliStructuredError {\n return new CliStructuredError('CLI.INVALID_VERIFY_MODE', 'Invalid verify mode', {\n why: options.why,\n fix: options.fix,\n docsUrl: 'https://pris.ly/db-verify',\n });\n}\n\nfunction resolveDbVerifyMode(options: DbVerifyOptions): Result<DbVerifyMode, CliStructuredError> {\n if (options.markerOnly && options.schemaOnly) {\n return notOk(\n errorInvalidVerifyMode({\n why: '`--marker-only` and `--schema-only` cannot be used together',\n fix: 'Choose one mode: omit both to check the marker and schema, use `--marker-only` to check only the marker, or use `--schema-only` to check only the live schema.',\n }),\n );\n }\n\n if (options.markerOnly && options.strict) {\n return notOk(\n errorInvalidVerifyMode({\n why: '`--strict` requires schema verification, but `--marker-only` skips it',\n fix: 'Remove `--strict`, or use `db verify` / `db verify --schema-only` when you want to check the live schema in strict mode.',\n }),\n );\n }\n\n if (options.schemaOnly) {\n return ok('schema-only');\n }\n\n if (options.markerOnly) {\n return ok('marker-only');\n }\n\n return ok('full');\n}\n\nfunction formatDbVerifyModeLabel(mode: DbVerifyMode, strict: boolean): string {\n if (mode === 'marker-only') {\n return 'marker only';\n }\n\n if (mode === 'schema-only') {\n return `schema only (${strict ? 'strict' : 'tolerant'})`;\n }\n\n return `full (marker + schema, ${strict ? 'strict' : 'tolerant'})`;\n}\n\nfunction formatDbVerifyInvocation(mode: DbVerifyMode, strict: boolean): string {\n const args = ['db verify'];\n\n if (mode === 'marker-only') {\n args.push('--marker-only');\n }\n\n if (mode === 'schema-only') {\n args.push('--schema-only');\n }\n\n if (strict) {\n args.push('--strict');\n }\n\n return args.join(' ');\n}\n\nfunction createDbVerifyConnectionRequiredError(options: {\n readonly configPath: string;\n readonly mode: DbVerifyMode;\n readonly strict: boolean;\n}): CliStructuredError {\n const invocation = formatDbVerifyInvocation(options.mode, options.strict);\n return errorDatabaseConnectionRequired({\n why: `Database connection is required for ${invocation} (set db.connection in ${options.configPath}, or pass --db <url>)`,\n retryCommand: `prisma-next ${invocation} --db <url>`,\n });\n}\n\nfunction renderVerifyHeader(\n paths: { configPath: string; contractPath: string },\n options: DbVerifyOptions,\n mode: DbVerifyMode,\n flags: GlobalFlags,\n ui: TerminalUI,\n): void {\n if (flags.json || flags.quiet) return;\n\n const description =\n mode === 'schema-only'\n ? 'Check whether the live database schema matches your contract'\n : mode === 'marker-only'\n ? 'Check whether the database marker matches your contract'\n : 'Check whether the database marker and live schema match your contract';\n\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: paths.configPath },\n { label: 'contract', value: paths.contractPath },\n { label: 'mode', value: formatDbVerifyModeLabel(mode, options.strict ?? false) },\n ];\n if (options.db) {\n details.push({ label: 'database', value: maskConnectionUrl(options.db) });\n }\n\n ui.stderr(\n formatStyledHeader({\n command: 'db verify',\n description,\n url: 'https://pris.ly/db-verify',\n details,\n flags,\n }),\n );\n}\n\nasync function resolveVerifyPaths(options: DbVerifyOptions) {\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 = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n return { config, configPath, contractPathAbsolute, contractPath };\n}\n\ntype VerifyPaths = Awaited<ReturnType<typeof resolveVerifyPaths>>;\n\ninterface VerifySetup extends VerifyPaths {\n readonly contractJson: Contract;\n readonly dbConnection: string;\n}\n\nasync function resolveVerifySetup(\n paths: VerifyPaths,\n options: DbVerifyOptions,\n mode: DbVerifyMode,\n): Promise<Result<VerifySetup, CliStructuredError>> {\n const { config, configPath, contractPathAbsolute, contractPath } = paths;\n\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 // Cross the family `deserializeContract` seam at the read site, just\n // like every other CLI on-disk read (TML-2536). The downstream\n // `dbVerify` op accepts the hydrated `Contract` directly and no\n // longer re-deserializes.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n\n let contractJson: Contract;\n try {\n contractJson = familyInstance.deserializeContract(JSON.parse(contractJsonContent) as unknown);\n } catch (error) {\n if (isStructuredError(error) && error.code === 'CONTRACT.VALIDATION_FAILED') {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\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 const dbConnection = options.db ?? config.db?.connection;\n if (typeof dbConnection !== 'string' || dbConnection.length === 0) {\n return notOk(\n createDbVerifyConnectionRequiredError({\n configPath,\n mode,\n strict: options.strict ?? false,\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: `Config.driver is required for ${formatDbVerifyInvocation(mode, options.strict ?? false)}`,\n }),\n );\n }\n\n return ok({ ...paths, contractJson, dbConnection });\n}\n\nfunction createVerifyClient(setup: VerifySetup) {\n return createControlClient({\n family: setup.config.family,\n target: setup.config.target,\n adapter: setup.config.adapter,\n driver: setup.config.driver!,\n extensions: setup.config.extensions ?? [],\n });\n}\n\nfunction wrapVerifyError(\n error: unknown,\n contractPathAbsolute: string,\n modeLabel: string,\n): Result<never, CliStructuredError> {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (isStructuredError(error) && error.code === 'CONTRACT.VALIDATION_FAILED') {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during ${modeLabel}: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n}\n\n/**\n * Executes the db verify command and returns a structured Result.\n */\nasync function executeDbVerifyCommand(\n options: DbVerifyOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n mode: Extract<DbVerifyMode, 'full' | 'marker-only'>,\n): Promise<Result<DbVerifyCommandSuccessResult, DbVerifyFailure>> {\n const startTime = Date.now();\n const paths = await resolveVerifyPaths(options);\n renderVerifyHeader(paths, options, mode, flags, ui);\n\n const setupResult = await resolveVerifySetup(paths, options, mode);\n if (!setupResult.ok) return setupResult;\n const { contractJson, dbConnection, contractPathAbsolute } = setupResult.value;\n const { migrationsDir } = resolveMigrationPaths(options.config, setupResult.value.config);\n\n const client = createVerifyClient(setupResult.value);\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n // Single-contract marker verification preserved for the existing\n // marker / target / hash failure surface (`CONTRACT.MARKER_MISSING/CONTRACT.MARKER_MISMATCH/CONTRACT.TARGET_MISMATCH`).\n // The aggregate verifier (run below for the per-space marker /\n // schema checks) does not duplicate this: it concerns itself with\n // marker-vs-on-disk and orphan-marker drift, not the\n // hash-mismatch-against-the-app-contract lane that today's\n // `client.verify` covers.\n const verifyResult = await client.verify({\n contract: contractJson,\n connection: dbConnection,\n onProgress,\n });\n\n if (!verifyResult.ok) {\n return notOk(mapVerifyFailure(verifyResult));\n }\n\n // Aggregate verifier (loader → verifier pipeline). Runs the layout\n // precheck, marker-aware per-space verifier, and (full mode only)\n // per-space pre-projected schema verification (closes F23).\n const aggregateResult = await client.dbVerify({\n contract: contractJson,\n migrationsDir,\n strict: options.strict ?? false,\n skipSchema: mode === 'marker-only',\n skipMarker: false,\n onProgress,\n });\n if (!aggregateResult.ok) return notOk(aggregateResult.failure);\n\n if (mode === 'marker-only') {\n return ok({\n ok: true,\n mode: 'marker-only',\n summary: 'Database marker matches contract',\n contract: verifyResult.contract,\n marker: verifyResult.marker,\n target: verifyResult.target,\n ...ifDefined('missingCodecs', verifyResult.missingCodecs),\n ...ifDefined('codecCoverageSkipped', verifyResult.codecCoverageSkipped),\n warning: 'Schema verification skipped because --marker-only was provided',\n meta: {\n ...(verifyResult.meta ?? {}),\n schemaVerification: 'skipped',\n },\n timings: { total: Date.now() - startTime },\n });\n }\n\n const combined = combineVerifyResults(\n aggregateResult.value.schemaResults,\n aggregateResult.value.appSpaceId,\n options.strict ?? false,\n aggregateResult.value.unclaimed,\n );\n if (!combined.result.ok) {\n return notOk(combined);\n }\n\n return ok({\n ok: true,\n mode: 'full',\n summary: 'Database marker and schema match contract',\n contract: verifyResult.contract,\n marker: verifyResult.marker,\n target: verifyResult.target,\n ...ifDefined('missingCodecs', verifyResult.missingCodecs),\n ...ifDefined('codecCoverageSkipped', verifyResult.codecCoverageSkipped),\n schema: {\n summary: combined.result.summary,\n strict: combined.result.meta?.strict ?? false,\n warnings: (combined.result.schema.warnings?.issues ?? []).map((issue) =>\n issue.path.join('/'),\n ),\n },\n unclaimed: combined.unclaimed,\n meta: {\n ...(verifyResult.meta ?? {}),\n schemaVerification: 'performed',\n },\n timings: { total: Date.now() - startTime },\n });\n } catch (error) {\n return wrapVerifyError(error, contractPathAbsolute, 'db verify');\n } finally {\n await client.close();\n }\n}\n\nasync function executeDbSchemaOnlyVerifyCommand(\n options: DbVerifyOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<CombinedVerifyResult, CliStructuredError>> {\n const paths = await resolveVerifyPaths(options);\n renderVerifyHeader(paths, options, 'schema-only', flags, ui);\n\n const setupResult = await resolveVerifySetup(paths, options, 'schema-only');\n if (!setupResult.ok) return setupResult;\n const { contractJson, dbConnection, contractPathAbsolute } = setupResult.value;\n const { migrationsDir } = resolveMigrationPaths(options.config, setupResult.value.config);\n\n const client = createVerifyClient(setupResult.value);\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n await client.connect(dbConnection);\n const aggregateResult = await client.dbVerify({\n contract: contractJson,\n migrationsDir,\n strict: options.strict ?? false,\n skipSchema: false,\n skipMarker: true,\n onProgress,\n });\n if (!aggregateResult.ok) return notOk(aggregateResult.failure);\n\n return ok(\n combineVerifyResults(\n aggregateResult.value.schemaResults,\n aggregateResult.value.appSpaceId,\n options.strict ?? false,\n aggregateResult.value.unclaimed,\n ),\n );\n } catch (error) {\n return wrapVerifyError(error, contractPathAbsolute, 'db verify --schema-only');\n } finally {\n await client.close();\n }\n}\n\nexport function createDbVerifyCommand(): Command {\n const command = new Command('verify');\n setCommandDescriptions(\n command,\n 'Check whether the database marker and live schema match your contract',\n 'Verifies the database marker first, then checks the database schema matches your contract.\\n' +\n 'Use `--marker-only` for marker-only verification, `--schema-only` to skip marker checks and\\n' +\n 'inspect only the live schema, and `--strict` to fail if the database includes elements\\n' +\n 'not present in the contract.',\n );\n setCommandExamples(command, [\n 'prisma-next db verify --db $DATABASE_URL',\n 'prisma-next db verify --db $DATABASE_URL --strict',\n 'prisma-next db verify --db $DATABASE_URL --schema-only',\n 'prisma-next db verify --db $DATABASE_URL --schema-only --strict',\n 'prisma-next db verify --db $DATABASE_URL --marker-only',\n 'prisma-next db verify --db $DATABASE_URL --json',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--marker-only', 'Skip schema verification and only check the database marker')\n .option(\n '--schema-only',\n 'Skip marker verification and only check whether the live schema satisfies the contract',\n )\n .option(\n '--strict',\n 'Strict mode: schema elements not present in the contract are considered an error',\n false,\n )\n .action(async (options: DbVerifyOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n\n const modeResult = resolveDbVerifyMode(options);\n if (!modeResult.ok) {\n const exitCode = handleResult(modeResult as Result<never, CliStructuredError>, flags, ui);\n process.exit(exitCode);\n }\n\n const mode = modeResult.value;\n\n if (mode === 'schema-only') {\n const result = await executeDbSchemaOnlyVerifyCommand(options, flags, ui);\n const exitCode = handleResult(result, flags, ui, (combined) => {\n if (flags.json) {\n ui.output(formatSchemaVerifyJson(combined.result, combined.unclaimed));\n } else {\n // Always show schema-drift failures, even in quiet mode — exiting 1\n // without diagnostics is unhelpful (same policy as the full-mode\n // failure branch below).\n const renderFlags = combined.result.ok ? flags : { ...flags, quiet: false };\n const output = formatSchemaVerifyOutput(\n combined.result,\n renderFlags,\n combined.unclaimed,\n );\n if (output) {\n ui.log(output);\n }\n }\n });\n\n if (result.ok && !result.value.result.ok) {\n process.exit(1);\n }\n\n process.exit(exitCode);\n }\n\n const result = await executeDbVerifyCommand(options, flags, ui, mode);\n\n if (result.ok) {\n if (flags.json) {\n ui.output(formatVerifyJson(result.value));\n } else {\n const output = formatVerifyOutput(result.value, flags);\n if (output) {\n ui.log(output);\n }\n }\n process.exit(0);\n }\n\n if (CliStructuredError.is(result.failure)) {\n const exitCode = handleResult(result as Result<never, CliStructuredError>, flags, ui);\n process.exit(exitCode);\n }\n\n if (flags.json) {\n ui.output(formatSchemaVerifyJson(result.failure.result, result.failure.unclaimed));\n } else {\n // Always show schema-drift failures, even in quiet mode — exiting 1 without\n // diagnostics is unhelpful.\n const output = formatSchemaVerifyOutput(\n result.failure.result,\n { ...flags, quiet: false },\n result.failure.unclaimed,\n );\n if (output) {\n ui.log(output);\n }\n }\n process.exit(1);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,qBACd,UACA,YACA,QACA,WACsB;CACtB,MAAM,YAAY,SAAS,IAAI,UAAU,KAAK,SAAS,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;CACvE,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,cACR,iFACF;CAGF,IAAI,QAAQ;CACZ,IAAI;CACJ,IAAI,SAAyD,CAAC;CAC9D,IAAI,gBAAgE,CAAC;CACrE,KAAK,MAAM,GAAG,WAAW,UAAU;EACjC,IAAI,CAAC,OAAO,I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ChE;KAIL,MAAM,cAAc,SAAS,OAAO,KAAK,QAAQ;MAAE,GAAG;MAAO,OAAO;KAAM;KAC1E,MAAM,SAAS,yBACb,SAAS,QACT,aACA,SAAS,SACX;KACA,IAAI,QACF,GAAG,IAAI,MAAM;IAEjB;GACF,CAAC;GAED,IAAI,OAAO,MAAM,CAAC,OAAO,MAAM,OAAO,IACpC,QAAQ,KAAK,CAAC;GAGhB,QAAQ,KAAK,QAAQ;EACvB;EAEA,MAAM,SAAS,MAAM,uBAAuB,SAAS,OAAO,IAAI,IAAI;EAEpE,IAAI,OAAO,IAAI;GACb,IAAI,MAAM,MACR,GAAG,OAAO,iBAAiB,OAAO,KAAK,CAAC;QACnC;IACL,MAAM,SAAS,mBAAmB,OAAO,OAAO,KAAK;IACrD,IAAI,QACF,GAAG,IAAI,MAAM;GAEjB;GACA,QAAQ,KAAK,CAAC;EAChB;EAEA,IAAI,mBAAmB,GAAG,OAAO,OAAO,GAAG;GACzC,MAAM,WAAW,aAAa,QAA6C,OAAO,EAAE;GACpF,QAAQ,KAAK,QAAQ;EACvB;EAEA,IAAI,MAAM,MACR,GAAG,OAAO,uBAAuB,OAAO,QAAQ,QAAQ,OAAO,QAAQ,SAAS,CAAC;OAC5E;GAGL,MAAM,SAAS,yBACb,OAAO,QAAQ,QACf;IAAE,GAAG;IAAO,OAAO;GAAM,GACzB,OAAO,QAAQ,SACjB;GACA,IAAI,QACF,GAAG,IAAI,MAAM;EAEjB;EACA,QAAQ,KAAK,CAAC;CAChB,CAAC;CAEH,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as ExecuteDbVerifyOptions, C as IntrospectOptions, D as SchemaVerifyOptions, M as executeDbVerify, O as SignOptions, S as EmitSuccess, T as OnControlProgress, _ as EmitContractConfig, a as ControlClientOptions, b as EmitOptions, c as DbInitFailureCode, d as DbInitSuccess, f as DbUpdateFailure, g as DbUpdateSuccess, h as DbUpdateResult, i as ControlClient, j as ExecuteDbVerifyResult, k as VerifyOptions, l as DbInitOptions, m as DbUpdateOptions, n as ContractEmitResult, o as ControlProgressEvent, p as DbUpdateFailureCode, r as ControlActionName, s as DbInitFailure, t as ContractEmitOptions, u as DbInitResult, v as EmitFailure, x as EmitResult, y as EmitFailureCode } from "../types-
|
|
1
|
+
import { A as ExecuteDbVerifyOptions, C as IntrospectOptions, D as SchemaVerifyOptions, M as executeDbVerify, O as SignOptions, S as EmitSuccess, T as OnControlProgress, _ as EmitContractConfig, a as ControlClientOptions, b as EmitOptions, c as DbInitFailureCode, d as DbInitSuccess, f as DbUpdateFailure, g as DbUpdateSuccess, h as DbUpdateResult, i as ControlClient, j as ExecuteDbVerifyResult, k as VerifyOptions, l as DbInitOptions, m as DbUpdateOptions, n as ContractEmitResult, o as ControlProgressEvent, p as DbUpdateFailureCode, r as ControlActionName, s as DbInitFailure, t as ContractEmitOptions, u as DbInitResult, v as EmitFailure, x as EmitResult, y as EmitFailureCode } from "../types-DgXprE3w.mjs";
|
|
2
2
|
import { ControlAdapterInstance, ControlDriverInstance, ControlExtensionDescriptor, ControlFamilyInstance, ControlStack, SignDatabaseResult, TargetMigrationsCapability, VerifyDatabaseResult, VerifyDatabaseSchemaResult } from "@prisma-next/framework-components/control";
|
|
3
3
|
import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
|
|
4
4
|
import { Contract } from "@prisma-next/contract/types";
|
|
@@ -59,7 +59,7 @@ declare function executeContractEmit(options: ContractEmitOptions): Promise<Cont
|
|
|
59
59
|
* 3. The runner's `execute` applies the per-space plans
|
|
60
60
|
* inside one outer transaction.
|
|
61
61
|
*
|
|
62
|
-
* `
|
|
62
|
+
* `extensions` mirrors `Config.extensions` (descriptor list).
|
|
63
63
|
* The loader (sub-spec § Loader) is the sole descriptor-import boundary.
|
|
64
64
|
*/
|
|
65
65
|
interface ExecuteDbInitOptions<TFamilyId extends string, TTargetId extends string> {
|
|
@@ -85,7 +85,7 @@ interface ExecuteDbInitOptions<TFamilyId extends string, TTargetId extends strin
|
|
|
85
85
|
* routes through the same loader → planner → runner pipeline with no
|
|
86
86
|
* extension spaces in the aggregate.
|
|
87
87
|
*/
|
|
88
|
-
readonly
|
|
88
|
+
readonly extensions?: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;
|
|
89
89
|
/** Optional progress callback for observing operation progress */
|
|
90
90
|
readonly onProgress?: OnControlProgress;
|
|
91
91
|
}
|
|
@@ -119,7 +119,7 @@ interface ExecuteDbUpdateOptions<TFamilyId extends string, TTargetId extends str
|
|
|
119
119
|
readonly acceptDataLoss?: boolean;
|
|
120
120
|
readonly migrationsDir: string;
|
|
121
121
|
readonly targetId: TTargetId;
|
|
122
|
-
readonly
|
|
122
|
+
readonly extensions?: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;
|
|
123
123
|
readonly onProgress?: OnControlProgress;
|
|
124
124
|
}
|
|
125
125
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"control-api.d.mts","names":[],"sources":["../../src/control-api/client.ts","../../src/control-api/contract-enrichment.ts","../../src/control-api/operations/contract-emit.ts","../../src/control-api/operations/db-init.ts","../../src/control-api/operations/db-update.ts","../../src/utils/emit-queue.ts"],"mappings":";;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"control-api.d.mts","names":[],"sources":["../../src/control-api/client.ts","../../src/control-api/contract-enrichment.ts","../../src/control-api/operations/contract-emit.ts","../../src/control-api/operations/db-init.ts","../../src/control-api/operations/db-update.ts","../../src/utils/emit-queue.ts"],"mappings":";;;;;;;;;;;;;;;iBAwEgB,oBAAoB,SAAS,uBAAuB;;;;;;iBCXpD,eACd,IAAI,UACJ,YAAY,cAAc,kDACzB;;;;;;;;;;;;;;;;;;;;;;;iBCwFmB,oBACpB,SAAS,sBACR,QAAQ;;;;;;;;;;;;;;;;;;;;UC5HM,qBAAqB,0BAA0B;WACrD,QAAQ,sBAAsB,WAAW;WACzC,SAAS,uBAAuB,WAAW;WAC3C,gBAAgB,sBAAsB;WACtC,UAAU;WACV;WACA,YAAY,2BACnB,WACA,WACA,sBAAsB;WAEf,qBAAqB,cAAc,+BAA+B,WAAW;;;;;WAK7E;;;;;WAKA,UAAU;;;;;;WAMV,aAAa,cAAc,2BAA2B,WAAW;;WAEjE,aAAa;;;;;;;;;iBAUF,cAAc,0BAA0B,0BAC5D,SAAS,qBAAqB,WAAW,aACxC,QAAQ;;;;;;;;;;;;UC5CM,uBAAuB,0BAA0B;WACvD,QAAQ,sBAAsB,WAAW;WACzC,SAAS,uBAAuB,WAAW;WAC3C,gBAAgB,sBAAsB;WACtC,UAAU;WACV;WACA,YAAY,2BACnB,WACA,WACA,sBAAsB;WAEf,qBAAqB,cAAc,+BAA+B,WAAW;WAC7E;WACA;WACA,UAAU;WACV,aAAa,cAAc,2BAA2B,WAAW;WACjE,aAAa;;;;;;;;;;;iBAYF,gBAAgB,0BAA0B,0BAC9D,SAAS,uBAAuB,WAAW,aAC1C,QAAQ;;;iBClCK,iBAAiB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as executeContractEmit, r as disposeEmitQueue } from "../contract-emit-
|
|
2
|
-
import { t as enrichContract } from "../contract-enrichment-
|
|
3
|
-
import { a as executeDbInit, i as executeDbUpdate, r as executeDbVerify, t as createControlClient } from "../client-
|
|
1
|
+
import { n as executeContractEmit, r as disposeEmitQueue } from "../contract-emit-hVdlaF2U.mjs";
|
|
2
|
+
import { t as enrichContract } from "../contract-enrichment-JUhLv-BX.mjs";
|
|
3
|
+
import { a as executeDbInit, i as executeDbUpdate, r as executeDbVerify, t as createControlClient } from "../client-B1UjQc_x.mjs";
|
|
4
4
|
export { createControlClient, disposeEmitQueue, enrichContract, executeContractEmit, executeDbInit, executeDbUpdate, executeDbVerify };
|
package/dist/exports/index.d.mts
CHANGED
|
@@ -21,7 +21,8 @@ interface LoadTsContractOptions {
|
|
|
21
21
|
* @param entryPath - Path to the TypeScript contract file
|
|
22
22
|
* @param options - Optional configuration (import allowlist)
|
|
23
23
|
* @returns The contract as Contract (should already be normalized)
|
|
24
|
-
* @throws
|
|
24
|
+
* @throws structured errors: `CLI.FILE_NOT_FOUND`, `CONTRACT.SOURCE_LOAD_FAILED`,
|
|
25
|
+
* `CONTRACT.SOURCE_IMPORT_DISALLOWED`, `CONTRACT.MODULE_EXPORT_MISSING`, `CONTRACT.EXPORT_INVALID`
|
|
25
26
|
*/
|
|
26
27
|
declare function loadContractFromTs(entryPath: string, options?: LoadTsContractOptions): Promise<Contract>;
|
|
27
28
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/commands/format.ts","../../src/load-ts-contract.ts"],"mappings":";;;;iBAmBgB,uBAAuB;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/commands/format.ts","../../src/load-ts-contract.ts"],"mappings":";;;;iBAmBgB,uBAAuB;;;UCTtB;WACN,YAAY;;;;;;;;;;;;;;;;;;iBAyKD,mBACpB,mBACA,UAAU,wBACT,QAAQ"}
|
package/dist/exports/index.mjs
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
|
-
import { t as createContractEmitCommand } from "../contract-emit-
|
|
2
|
-
import { t as createFormatCommand } from "../format-
|
|
1
|
+
import { t as createContractEmitCommand } from "../contract-emit-BT46Mu8Q.mjs";
|
|
2
|
+
import { t as createFormatCommand } from "../format-DI5qVr22.mjs";
|
|
3
|
+
import { CliStructuredError } from "@prisma-next/errors/control";
|
|
3
4
|
import { join, resolve } from "pathe";
|
|
4
5
|
import { existsSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { InternalError } from "@prisma-next/utils/internal-error";
|
|
5
7
|
import { tmpdir } from "node:os";
|
|
6
8
|
import { pathToFileURL } from "node:url";
|
|
7
9
|
import { build } from "esbuild";
|
|
8
10
|
//#region src/load-ts-contract.ts
|
|
11
|
+
function contractSourceError(code, message, options) {
|
|
12
|
+
const error = new CliStructuredError(code, message, options?.meta !== void 0 ? { meta: options.meta } : void 0);
|
|
13
|
+
if (options?.cause !== void 0) error.cause = options.cause;
|
|
14
|
+
return error;
|
|
15
|
+
}
|
|
9
16
|
const DEFAULT_ALLOWLIST = ["@prisma-next/*", "node:crypto"];
|
|
10
17
|
function isAllowedImport(importPath, allowlist) {
|
|
11
18
|
for (const pattern of allowlist) if (pattern.endsWith("/*")) {
|
|
@@ -17,18 +24,29 @@ function isAllowedImport(importPath, allowlist) {
|
|
|
17
24
|
} else if (importPath === pattern) return true;
|
|
18
25
|
return false;
|
|
19
26
|
}
|
|
20
|
-
function validatePurity(value) {
|
|
27
|
+
function validatePurity(value, entryPath) {
|
|
21
28
|
if (typeof value !== "object" || value === null) return;
|
|
22
29
|
const path = /* @__PURE__ */ new WeakSet();
|
|
23
30
|
function check(value) {
|
|
24
31
|
if (value === null || typeof value !== "object") return;
|
|
25
|
-
if (path.has(value)) throw
|
|
32
|
+
if (path.has(value)) throw contractSourceError("CONTRACT.EXPORT_INVALID", "Contract export contains circular references", { meta: {
|
|
33
|
+
path: entryPath,
|
|
34
|
+
reason: "circular"
|
|
35
|
+
} });
|
|
26
36
|
path.add(value);
|
|
27
37
|
try {
|
|
28
38
|
for (const key in value) {
|
|
29
39
|
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
30
|
-
if (descriptor && (descriptor.get || descriptor.set)) throw
|
|
31
|
-
|
|
40
|
+
if (descriptor && (descriptor.get || descriptor.set)) throw contractSourceError("CONTRACT.EXPORT_INVALID", `Contract export contains getter/setter at key "${key}"`, { meta: {
|
|
41
|
+
path: entryPath,
|
|
42
|
+
reason: "getter",
|
|
43
|
+
key
|
|
44
|
+
} });
|
|
45
|
+
if (descriptor && typeof descriptor.value === "function") throw contractSourceError("CONTRACT.EXPORT_INVALID", `Contract export contains function at key "${key}"`, { meta: {
|
|
46
|
+
path: entryPath,
|
|
47
|
+
reason: "function",
|
|
48
|
+
key
|
|
49
|
+
} });
|
|
32
50
|
check(value[key]);
|
|
33
51
|
}
|
|
34
52
|
} finally {
|
|
@@ -41,9 +59,18 @@ function validatePurity(value) {
|
|
|
41
59
|
} catch (error) {
|
|
42
60
|
if (error instanceof Error) {
|
|
43
61
|
if (error.message.includes("getter") || error.message.includes("circular")) throw error;
|
|
44
|
-
throw
|
|
62
|
+
throw contractSourceError("CONTRACT.EXPORT_INVALID", `Contract export is not JSON-serializable: ${error.message}`, {
|
|
63
|
+
meta: {
|
|
64
|
+
path: entryPath,
|
|
65
|
+
reason: "not-json-serializable"
|
|
66
|
+
},
|
|
67
|
+
cause: error
|
|
68
|
+
});
|
|
45
69
|
}
|
|
46
|
-
throw
|
|
70
|
+
throw contractSourceError("CONTRACT.EXPORT_INVALID", "Contract export is not JSON-serializable", { meta: {
|
|
71
|
+
path: entryPath,
|
|
72
|
+
reason: "not-json-serializable"
|
|
73
|
+
} });
|
|
47
74
|
}
|
|
48
75
|
}
|
|
49
76
|
function createImportAllowlistPlugin(allowlist, entryPath, collected) {
|
|
@@ -81,11 +108,12 @@ function createImportAllowlistPlugin(allowlist, entryPath, collected) {
|
|
|
81
108
|
* @param entryPath - Path to the TypeScript contract file
|
|
82
109
|
* @param options - Optional configuration (import allowlist)
|
|
83
110
|
* @returns The contract as Contract (should already be normalized)
|
|
84
|
-
* @throws
|
|
111
|
+
* @throws structured errors: `CLI.FILE_NOT_FOUND`, `CONTRACT.SOURCE_LOAD_FAILED`,
|
|
112
|
+
* `CONTRACT.SOURCE_IMPORT_DISALLOWED`, `CONTRACT.MODULE_EXPORT_MISSING`, `CONTRACT.EXPORT_INVALID`
|
|
85
113
|
*/
|
|
86
114
|
async function loadContractFromTs(entryPath, options) {
|
|
87
115
|
const allowlist = options?.allowlist ?? DEFAULT_ALLOWLIST;
|
|
88
|
-
if (!existsSync(entryPath)) throw new
|
|
116
|
+
if (!existsSync(entryPath)) throw new CliStructuredError("CLI.FILE_NOT_FOUND", `Contract file not found: ${entryPath}`, { where: { path: entryPath } });
|
|
89
117
|
const tempFile = join(tmpdir(), `prisma-next-contract-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`);
|
|
90
118
|
const disallowedFromEntry = /* @__PURE__ */ new Set();
|
|
91
119
|
try {
|
|
@@ -101,14 +129,17 @@ async function loadContractFromTs(entryPath, options) {
|
|
|
101
129
|
plugins: [createImportAllowlistPlugin(allowlist, entryPath, disallowedFromEntry)],
|
|
102
130
|
logLevel: "error"
|
|
103
131
|
});
|
|
104
|
-
if (result.errors.length > 0) {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
}
|
|
108
|
-
if (!result.outputFiles || result.outputFiles.length === 0) throw new
|
|
109
|
-
if (disallowedFromEntry.size > 0) throw
|
|
132
|
+
if (result.errors.length > 0) throw contractSourceError("CONTRACT.SOURCE_LOAD_FAILED", `Failed to bundle contract file: ${result.errors.map((e) => e.text).join("\n")}`, { meta: {
|
|
133
|
+
path: entryPath,
|
|
134
|
+
stage: "bundle"
|
|
135
|
+
} });
|
|
136
|
+
if (!result.outputFiles || result.outputFiles.length === 0) throw new InternalError("No output files generated from bundling");
|
|
137
|
+
if (disallowedFromEntry.size > 0) throw contractSourceError("CONTRACT.SOURCE_IMPORT_DISALLOWED", `Disallowed imports detected. Only imports matching the allowlist are permitted:\n Allowlist: ${allowlist.join(", ")}\n Disallowed imports: ${[...disallowedFromEntry].join(", ")}`, { meta: {
|
|
138
|
+
allowlist: [...allowlist],
|
|
139
|
+
disallowed: [...disallowedFromEntry]
|
|
140
|
+
} });
|
|
110
141
|
const bundleContent = result.outputFiles[0]?.text;
|
|
111
|
-
if (bundleContent === void 0) throw new
|
|
142
|
+
if (bundleContent === void 0) throw new InternalError("Bundle content is undefined");
|
|
112
143
|
writeFileSync(tempFile, bundleContent, "utf-8");
|
|
113
144
|
const module = await import(
|
|
114
145
|
/* @vite-ignore */
|
|
@@ -118,16 +149,25 @@ async function loadContractFromTs(entryPath, options) {
|
|
|
118
149
|
let contract;
|
|
119
150
|
if (module.default !== void 0) contract = module.default;
|
|
120
151
|
else if (module.contract !== void 0) contract = module.contract;
|
|
121
|
-
else throw new
|
|
122
|
-
if (typeof contract !== "object" || contract === null) throw
|
|
123
|
-
|
|
152
|
+
else throw new CliStructuredError("CONTRACT.MODULE_EXPORT_MISSING", `Contract file must export a contract as default export or named export 'contract'. Found exports: ${Object.keys(module).join(", ") || "none"}`, { where: { path: entryPath } });
|
|
153
|
+
if (typeof contract !== "object" || contract === null) throw contractSourceError("CONTRACT.EXPORT_INVALID", `Contract export must be an object, got ${typeof contract}`, { meta: {
|
|
154
|
+
path: entryPath,
|
|
155
|
+
reason: "not-object"
|
|
156
|
+
} });
|
|
157
|
+
validatePurity(contract, entryPath);
|
|
124
158
|
return contract;
|
|
125
159
|
} catch (error) {
|
|
126
160
|
try {
|
|
127
161
|
if (tempFile) unlinkSync(tempFile);
|
|
128
162
|
} catch {}
|
|
129
163
|
if (error instanceof Error) throw error;
|
|
130
|
-
throw
|
|
164
|
+
throw contractSourceError("CONTRACT.SOURCE_LOAD_FAILED", `Failed to load contract from ${entryPath}: ${String(error)}`, {
|
|
165
|
+
meta: {
|
|
166
|
+
path: entryPath,
|
|
167
|
+
stage: "import"
|
|
168
|
+
},
|
|
169
|
+
cause: error
|
|
170
|
+
});
|
|
131
171
|
}
|
|
132
172
|
}
|
|
133
173
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["resolvePath"],"sources":["../../src/load-ts-contract.ts"],"sourcesContent":["import { existsSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { pathToFileURL } from 'node:url';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { Plugin } from 'esbuild';\nimport { build } from 'esbuild';\nimport { join, resolve as resolvePath } from 'pathe';\n\nexport interface LoadTsContractOptions {\n readonly allowlist?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_ALLOWLIST = ['@prisma-next/*', 'node:crypto'];\n\nfunction isAllowedImport(importPath: string, allowlist: ReadonlyArray<string>): boolean {\n for (const pattern of allowlist) {\n if (pattern.endsWith('/*')) {\n const prefix = pattern.slice(0, -2);\n if (importPath === prefix || importPath.startsWith(`${prefix}/`)) {\n return true;\n }\n } else if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n if (importPath.startsWith(prefix)) {\n return true;\n }\n } else if (importPath === pattern) {\n return true;\n }\n }\n return false;\n}\n\nfunction validatePurity(value: unknown): void {\n if (typeof value !== 'object' || value === null) {\n return;\n }\n\n const path = new WeakSet();\n\n function check(value: unknown): void {\n if (value === null || typeof value !== 'object') {\n return;\n }\n\n if (path.has(value)) {\n throw new Error('Contract export contains circular references');\n }\n path.add(value);\n\n try {\n for (const key in value) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && (descriptor.get || descriptor.set)) {\n throw new Error(`Contract export contains getter/setter at key \"${key}\"`);\n }\n if (descriptor && typeof descriptor.value === 'function') {\n throw new Error(`Contract export contains function at key \"${key}\"`);\n }\n check((value as Record<string, unknown>)[key]);\n }\n } finally {\n path.delete(value);\n }\n }\n\n try {\n check(value);\n JSON.stringify(value);\n } catch (error) {\n if (error instanceof Error) {\n if (error.message.includes('getter') || error.message.includes('circular')) {\n throw error;\n }\n throw new Error(`Contract export is not JSON-serializable: ${error.message}`);\n }\n throw new Error('Contract export is not JSON-serializable');\n }\n}\n\nfunction createImportAllowlistPlugin(\n allowlist: ReadonlyArray<string>,\n entryPath: string,\n collected: Set<string>,\n): Plugin {\n // Match against several path forms that esbuild may use as the importer:\n // the absolute resolved entry, the value the caller passed (which may be\n // relative), and the conventional `<stdin>` placeholder. This is more\n // forgiving than `===` against a single form, which broke when esbuild\n // resolved the entry to an absolute path while the caller passed a\n // relative one (or vice versa).\n const entryAbs = resolvePath(entryPath);\n function isFromEntry(importer: string): boolean {\n return importer === entryAbs || importer === entryPath || importer === '<stdin>';\n }\n return {\n name: 'import-allowlist',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === 'entry-point') {\n return undefined;\n }\n if (args.path.startsWith('.') || args.path.startsWith('/')) {\n return undefined;\n }\n if (isFromEntry(args.importer) && !isAllowedImport(args.path, allowlist)) {\n collected.add(args.path);\n return {\n path: args.path,\n external: true,\n };\n }\n return undefined;\n });\n },\n };\n}\n\n/**\n * Loads a contract from a TypeScript file and returns it as Contract.\n *\n * **Responsibility: Parsing Only**\n * This function loads and parses a TypeScript contract file. It does NOT normalize the contract.\n * The contract should already be normalized if it was built using the contract builder.\n *\n * Normalization must happen in the contract builder when the contract is created.\n * This function only validates that the contract is JSON-serializable and returns it as-is.\n *\n * @param entryPath - Path to the TypeScript contract file\n * @param options - Optional configuration (import allowlist)\n * @returns The contract as Contract (should already be normalized)\n * @throws Error if the contract cannot be loaded or is not JSON-serializable\n */\nexport async function loadContractFromTs(\n entryPath: string,\n options?: LoadTsContractOptions,\n): Promise<Contract> {\n const allowlist = options?.allowlist ?? DEFAULT_ALLOWLIST;\n\n if (!existsSync(entryPath)) {\n throw new Error(`Contract file not found: ${entryPath}`);\n }\n\n const tempFile = join(\n tmpdir(),\n `prisma-next-contract-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n // Disallowed imports are collected by the allowlist resolver plugin itself,\n // which has the `importer` context to distinguish entry-direct imports from\n // transitive imports made inside allowlisted (`@prisma-next/*`) dependencies.\n // The metafile is intentionally not re-walked: it would surface internal\n // `node:*` imports inside framework code as false positives.\n const disallowedFromEntry = new Set<string>();\n\n try {\n const result = await build({\n entryPoints: [entryPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'es2022',\n outfile: tempFile,\n write: false,\n metafile: true,\n plugins: [createImportAllowlistPlugin(allowlist, entryPath, disallowedFromEntry)],\n logLevel: 'error',\n });\n\n if (result.errors.length > 0) {\n const errorMessages = result.errors.map((e: { text: string }) => e.text).join('\\n');\n throw new Error(`Failed to bundle contract file: ${errorMessages}`);\n }\n\n if (!result.outputFiles || result.outputFiles.length === 0) {\n throw new Error('No output files generated from bundling');\n }\n\n if (disallowedFromEntry.size > 0) {\n throw new Error(\n `Disallowed imports detected. Only imports matching the allowlist are permitted:\\n Allowlist: ${allowlist.join(', ')}\\n Disallowed imports: ${[...disallowedFromEntry].join(', ')}`,\n );\n }\n\n const bundleContent = result.outputFiles[0]?.text;\n if (bundleContent === undefined) {\n throw new Error('Bundle content is undefined');\n }\n writeFileSync(tempFile, bundleContent, 'utf-8');\n\n const module = (await import(/* @vite-ignore */ pathToFileURL(tempFile).href)) as {\n default?: unknown;\n contract?: unknown;\n };\n unlinkSync(tempFile);\n\n let contract: unknown;\n\n if (module.default !== undefined) {\n contract = module.default;\n } else if (module.contract !== undefined) {\n contract = module.contract;\n } else {\n throw new Error(\n `Contract file must export a contract as default export or named export 'contract'. Found exports: ${Object.keys(module as Record<string, unknown>).join(', ') || 'none'}`,\n );\n }\n\n if (typeof contract !== 'object' || contract === null) {\n throw new Error(`Contract export must be an object, got ${typeof contract}`);\n }\n\n validatePurity(contract);\n\n // Blind cast: the loaded module was authored by user code\n // (typically via `defineContract` / a contract builder) and\n // its runtime shape is structurally a `Contract`, but the\n // dynamic import collapses the source typing. The contract\n // structural validation that asserts the shape happens\n // downstream at the `familyInstance.deserializeContract` seam\n // (e.g. in `executeContractEmit`); this helper only checks\n // purity here.\n return contract as unknown as Contract;\n } catch (error) {\n try {\n if (tempFile) {\n unlinkSync(tempFile);\n }\n } catch {\n // Ignore cleanup errors\n }\n\n if (error instanceof Error) {\n throw error;\n }\n throw new Error(`Failed to load contract from ${entryPath}: ${String(error)}`);\n }\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,oBAAoB,CAAC,kBAAkB,aAAa;AAE1D,SAAS,gBAAgB,YAAoB,WAA2C;CACtF,KAAK,MAAM,WAAW,WACpB,IAAI,QAAQ,SAAS,IAAI,GAAG;EAC1B,MAAM,SAAS,QAAQ,MAAM,GAAG,EAAE;EAClC,IAAI,eAAe,UAAU,WAAW,WAAW,GAAG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AC,GAAG,mBAAmB,CAAC,CAAC,KAAK,IAAI,GACpL;EAGF,MAAM,gBAAgB,OAAO,YAAY,EAAE,EAAE;EAC7C,IAAI,kBAAkB,KAAA,GACpB,MAAM,IAAI,MAAM,6BAA6B;EAE/C,cAAc,UAAU,eAAe,OAAO;EAE9C,MAAM,SAAU,MAAM;;GAA0B,cAAc,QAAQ,CAAC,CAAC;;EAIxE,WAAW,QAAQ;EAEnB,IAAI;EAEJ,IAAI,OAAO,YAAY,KAAA,GACrB,WAAW,OAAO;OACb,IAAI,OAAO,aAAa,KAAA,GAC7B,WAAW,OAAO;OAElB,MAAM,IAAI,MACR,qGAAqG,OAAO,KAAK,MAAiC,CAAC,CAAC,KAAK,IAAI,KAAK,QACpK;EAGF,IAAI,OAAO,aAAa,YAAY,aAAa,MAC/C,MAAM,IAAI,MAAM,0CAA0C,OAAO,UAAU;EAG7E,eAAe,QAAQ;EAUvB,OAAO;CACT,SAAS,OAAO;EACd,IAAI;GACF,IAAI,UACF,WAAW,QAAQ;EAEvB,QAAQ,CAER;EAEA,IAAI,iBAAiB,OACnB,MAAM;EAER,MAAM,IAAI,MAAM,gCAAgC,UAAU,IAAI,OAAO,KAAK,GAAG;CAC/E;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["resolvePath"],"sources":["../../src/load-ts-contract.ts"],"sourcesContent":["import { existsSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { pathToFileURL } from 'node:url';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { CliStructuredError } from '@prisma-next/errors/control';\nimport { InternalError } from '@prisma-next/utils/internal-error';\nimport type { Plugin } from 'esbuild';\nimport { build } from 'esbuild';\nimport { join, resolve as resolvePath } from 'pathe';\n\nexport interface LoadTsContractOptions {\n readonly allowlist?: ReadonlyArray<string>;\n}\n\ntype ContractSourceErrorCode =\n | 'CONTRACT.EXPORT_INVALID'\n | 'CONTRACT.SOURCE_LOAD_FAILED'\n | 'CONTRACT.SOURCE_IMPORT_DISALLOWED';\n\nfunction contractSourceError(\n code: ContractSourceErrorCode,\n message: string,\n options?: {\n readonly meta?: Record<string, unknown>;\n readonly cause?: unknown;\n },\n): CliStructuredError {\n const error = new CliStructuredError(\n code,\n message,\n options?.meta !== undefined ? { meta: options.meta } : undefined,\n );\n if (options?.cause !== undefined) {\n error.cause = options.cause;\n }\n return error;\n}\n\nconst DEFAULT_ALLOWLIST = ['@prisma-next/*', 'node:crypto'];\n\nfunction isAllowedImport(importPath: string, allowlist: ReadonlyArray<string>): boolean {\n for (const pattern of allowlist) {\n if (pattern.endsWith('/*')) {\n const prefix = pattern.slice(0, -2);\n if (importPath === prefix || importPath.startsWith(`${prefix}/`)) {\n return true;\n }\n } else if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n if (importPath.startsWith(prefix)) {\n return true;\n }\n } else if (importPath === pattern) {\n return true;\n }\n }\n return false;\n}\n\nfunction validatePurity(value: unknown, entryPath: string): void {\n if (typeof value !== 'object' || value === null) {\n return;\n }\n\n const path = new WeakSet();\n\n function check(value: unknown): void {\n if (value === null || typeof value !== 'object') {\n return;\n }\n\n if (path.has(value)) {\n throw contractSourceError(\n 'CONTRACT.EXPORT_INVALID',\n 'Contract export contains circular references',\n { meta: { path: entryPath, reason: 'circular' } },\n );\n }\n path.add(value);\n\n try {\n for (const key in value) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && (descriptor.get || descriptor.set)) {\n throw contractSourceError(\n 'CONTRACT.EXPORT_INVALID',\n `Contract export contains getter/setter at key \"${key}\"`,\n { meta: { path: entryPath, reason: 'getter', key } },\n );\n }\n if (descriptor && typeof descriptor.value === 'function') {\n throw contractSourceError(\n 'CONTRACT.EXPORT_INVALID',\n `Contract export contains function at key \"${key}\"`,\n { meta: { path: entryPath, reason: 'function', key } },\n );\n }\n check((value as Record<string, unknown>)[key]);\n }\n } finally {\n path.delete(value);\n }\n }\n\n try {\n check(value);\n JSON.stringify(value);\n } catch (error) {\n if (error instanceof Error) {\n if (error.message.includes('getter') || error.message.includes('circular')) {\n throw error;\n }\n throw contractSourceError(\n 'CONTRACT.EXPORT_INVALID',\n `Contract export is not JSON-serializable: ${error.message}`,\n { meta: { path: entryPath, reason: 'not-json-serializable' }, cause: error },\n );\n }\n throw contractSourceError(\n 'CONTRACT.EXPORT_INVALID',\n 'Contract export is not JSON-serializable',\n { meta: { path: entryPath, reason: 'not-json-serializable' } },\n );\n }\n}\n\nfunction createImportAllowlistPlugin(\n allowlist: ReadonlyArray<string>,\n entryPath: string,\n collected: Set<string>,\n): Plugin {\n // Match against several path forms that esbuild may use as the importer:\n // the absolute resolved entry, the value the caller passed (which may be\n // relative), and the conventional `<stdin>` placeholder. This is more\n // forgiving than `===` against a single form, which broke when esbuild\n // resolved the entry to an absolute path while the caller passed a\n // relative one (or vice versa).\n const entryAbs = resolvePath(entryPath);\n function isFromEntry(importer: string): boolean {\n return importer === entryAbs || importer === entryPath || importer === '<stdin>';\n }\n return {\n name: 'import-allowlist',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === 'entry-point') {\n return undefined;\n }\n if (args.path.startsWith('.') || args.path.startsWith('/')) {\n return undefined;\n }\n if (isFromEntry(args.importer) && !isAllowedImport(args.path, allowlist)) {\n collected.add(args.path);\n return {\n path: args.path,\n external: true,\n };\n }\n return undefined;\n });\n },\n };\n}\n\n/**\n * Loads a contract from a TypeScript file and returns it as Contract.\n *\n * **Responsibility: Parsing Only**\n * This function loads and parses a TypeScript contract file. It does NOT normalize the contract.\n * The contract should already be normalized if it was built using the contract builder.\n *\n * Normalization must happen in the contract builder when the contract is created.\n * This function only validates that the contract is JSON-serializable and returns it as-is.\n *\n * @param entryPath - Path to the TypeScript contract file\n * @param options - Optional configuration (import allowlist)\n * @returns The contract as Contract (should already be normalized)\n * @throws structured errors: `CLI.FILE_NOT_FOUND`, `CONTRACT.SOURCE_LOAD_FAILED`,\n * `CONTRACT.SOURCE_IMPORT_DISALLOWED`, `CONTRACT.MODULE_EXPORT_MISSING`, `CONTRACT.EXPORT_INVALID`\n */\nexport async function loadContractFromTs(\n entryPath: string,\n options?: LoadTsContractOptions,\n): Promise<Contract> {\n const allowlist = options?.allowlist ?? DEFAULT_ALLOWLIST;\n\n if (!existsSync(entryPath)) {\n throw new CliStructuredError('CLI.FILE_NOT_FOUND', `Contract file not found: ${entryPath}`, {\n where: { path: entryPath },\n });\n }\n\n const tempFile = join(\n tmpdir(),\n `prisma-next-contract-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n // Disallowed imports are collected by the allowlist resolver plugin itself,\n // which has the `importer` context to distinguish entry-direct imports from\n // transitive imports made inside allowlisted (`@prisma-next/*`) dependencies.\n // The metafile is intentionally not re-walked: it would surface internal\n // `node:*` imports inside framework code as false positives.\n const disallowedFromEntry = new Set<string>();\n\n try {\n const result = await build({\n entryPoints: [entryPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'es2022',\n outfile: tempFile,\n write: false,\n metafile: true,\n plugins: [createImportAllowlistPlugin(allowlist, entryPath, disallowedFromEntry)],\n logLevel: 'error',\n });\n\n if (result.errors.length > 0) {\n const errorMessages = result.errors.map((e: { text: string }) => e.text).join('\\n');\n throw contractSourceError(\n 'CONTRACT.SOURCE_LOAD_FAILED',\n `Failed to bundle contract file: ${errorMessages}`,\n { meta: { path: entryPath, stage: 'bundle' } },\n );\n }\n\n if (!result.outputFiles || result.outputFiles.length === 0) {\n throw new InternalError('No output files generated from bundling');\n }\n\n if (disallowedFromEntry.size > 0) {\n throw contractSourceError(\n 'CONTRACT.SOURCE_IMPORT_DISALLOWED',\n `Disallowed imports detected. Only imports matching the allowlist are permitted:\\n Allowlist: ${allowlist.join(', ')}\\n Disallowed imports: ${[...disallowedFromEntry].join(', ')}`,\n { meta: { allowlist: [...allowlist], disallowed: [...disallowedFromEntry] } },\n );\n }\n\n const bundleContent = result.outputFiles[0]?.text;\n if (bundleContent === undefined) {\n throw new InternalError('Bundle content is undefined');\n }\n writeFileSync(tempFile, bundleContent, 'utf-8');\n\n const module = (await import(/* @vite-ignore */ pathToFileURL(tempFile).href)) as {\n default?: unknown;\n contract?: unknown;\n };\n unlinkSync(tempFile);\n\n let contract: unknown;\n\n if (module.default !== undefined) {\n contract = module.default;\n } else if (module.contract !== undefined) {\n contract = module.contract;\n } else {\n throw new CliStructuredError(\n 'CONTRACT.MODULE_EXPORT_MISSING',\n `Contract file must export a contract as default export or named export 'contract'. Found exports: ${Object.keys(module as Record<string, unknown>).join(', ') || 'none'}`,\n { where: { path: entryPath } },\n );\n }\n\n if (typeof contract !== 'object' || contract === null) {\n throw contractSourceError(\n 'CONTRACT.EXPORT_INVALID',\n `Contract export must be an object, got ${typeof contract}`,\n { meta: { path: entryPath, reason: 'not-object' } },\n );\n }\n\n validatePurity(contract, entryPath);\n\n // Blind cast: the loaded module was authored by user code\n // (typically via `defineContract` / a contract builder) and\n // its runtime shape is structurally a `Contract`, but the\n // dynamic import collapses the source typing. The contract\n // structural validation that asserts the shape happens\n // downstream at the `familyInstance.deserializeContract` seam\n // (e.g. in `executeContractEmit`); this helper only checks\n // purity here.\n return contract as unknown as Contract;\n } catch (error) {\n try {\n if (tempFile) {\n unlinkSync(tempFile);\n }\n } catch {\n // Ignore cleanup errors\n }\n\n if (error instanceof Error) {\n throw error;\n }\n throw contractSourceError(\n 'CONTRACT.SOURCE_LOAD_FAILED',\n `Failed to load contract from ${entryPath}: ${String(error)}`,\n { meta: { path: entryPath, stage: 'import' }, cause: error },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAS,oBACP,MACA,SACA,SAIoB;CACpB,MAAM,QAAQ,IAAI,mBAChB,MACA,SACA,SAAS,SAAS,KAAA,IAAY,EAAE,MAAM,QAAQ,KAAK,IAAI,KAAA,CACzD;CACA,IAAI,SAAS,UAAU,KAAA,GACrB,MAAM,QAAQ,QAAQ;CAExB,OAAO;AACT;AAEA,MAAM,oBAAoB,CAAC,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AC/C,MAAM,oBACJ,2BACA,0CAA0C,OAAO,YACjD,EAAE,MAAM;GAAE,MAAM;GAAW,QAAQ;EAAa,EAAE,CACpD;EAGF,eAAe,UAAU,SAAS;EAUlC,OAAO;CACT,SAAS,OAAO;EACd,IAAI;GACF,IAAI,UACF,WAAW,QAAQ;EAEvB,QAAQ,CAER;EAEA,IAAI,iBAAiB,OACnB,MAAM;EAER,MAAM,oBACJ,+BACA,gCAAgC,UAAU,IAAI,OAAO,KAAK,KAC1D;GAAE,MAAM;IAAE,MAAM;IAAW,OAAO;GAAS;GAAG,OAAO;EAAM,CAC7D;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init-output.d.mts","names":[],"sources":["../../src/commands/init/output.ts"],"mappings":";;;;;;;;;;;;;;;;cAkBa,gEAAgB;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"init-output.d.mts","names":[],"sources":["../../src/commands/init/output.ts"],"mappings":";;;;;;;;;;;;;;;;cAkBa,gEAAgB;;;;;;;;;;;;;;;;KAuBjB,oBAAoB,iBAAiB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as InitOutputSchema } from "../output-
|
|
1
|
+
import { t as InitOutputSchema } from "../output-DWNYqZGc.mjs";
|
|
2
2
|
export { InitOutputSchema };
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { A as formatStyledHeader, F as CliStructuredError, _ as createTerminalUI, ct as errorUnexpected, g as parseGlobalFlagsOrExit, l as setCommandDescriptions, rt as errorRuntime, t as addGlobalOptions, u as setCommandExamples, y as handleResult } from "./command-helpers-
|
|
1
|
+
import { A as formatStyledHeader, F as CliStructuredError, _ as createTerminalUI, ct as errorUnexpected, g as parseGlobalFlagsOrExit, l as setCommandDescriptions, rt as errorRuntime, t as addGlobalOptions, u as setCommandExamples, y as handleResult } from "./command-helpers-D-jBl0Qt.mjs";
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import { loadConfig } from "@prisma-next/config-loader";
|
|
4
4
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
5
5
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
6
6
|
import { relative, resolve } from "pathe";
|
|
7
7
|
import { readFile, writeFile } from "node:fs/promises";
|
|
8
|
+
import { isStructuredError } from "@prisma-next/utils/structured-error";
|
|
8
9
|
import { EOL } from "node:os";
|
|
9
|
-
import {
|
|
10
|
+
import { format } from "@prisma-next/psl-parser/format";
|
|
10
11
|
//#region src/control-api/operations/format.ts
|
|
11
12
|
function resolveNewline(formatterNewline, eol) {
|
|
12
13
|
if (formatterNewline !== void 0) return formatterNewline;
|
|
@@ -22,7 +23,7 @@ async function executeFormat(options) {
|
|
|
22
23
|
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error)));
|
|
23
24
|
}
|
|
24
25
|
const source = config.contract?.source;
|
|
25
|
-
if (source?.
|
|
26
|
+
if (source?.format !== "psl") return ok({ formatted: false });
|
|
26
27
|
const inputPath = source.inputs?.[0];
|
|
27
28
|
if (inputPath === void 0) return ok({ formatted: false });
|
|
28
29
|
let contents;
|
|
@@ -42,10 +43,10 @@ async function executeFormat(options) {
|
|
|
42
43
|
try {
|
|
43
44
|
formatted = format(contents, formatOptions);
|
|
44
45
|
} catch (error) {
|
|
45
|
-
if (error
|
|
46
|
+
if (isStructuredError(error) && error.code === "PSL.PARSE_FAILED") return notOk(errorRuntime("Cannot format PSL with parse errors", {
|
|
46
47
|
why: error.message,
|
|
47
48
|
fix: "Fix the parse errors in your schema and try again.",
|
|
48
|
-
meta: { diagnostics: error.diagnostics }
|
|
49
|
+
meta: { diagnostics: error.meta?.["diagnostics"] }
|
|
49
50
|
}));
|
|
50
51
|
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error)));
|
|
51
52
|
}
|
|
@@ -66,7 +67,7 @@ async function executeFormat(options) {
|
|
|
66
67
|
//#region src/commands/format.ts
|
|
67
68
|
function createFormatCommand() {
|
|
68
69
|
const command = new Command("format");
|
|
69
|
-
setCommandDescriptions(command, "Format your PSL contract source", "Formats the Prisma schema (PSL) contract source declared in your config\n(contract.source.inputs[0]) in place. Only runs when contract.source.
|
|
70
|
+
setCommandDescriptions(command, "Format your PSL contract source", "Formats the Prisma schema (PSL) contract source declared in your config\n(contract.source.inputs[0]) in place. Only runs when contract.source.format\nis 'psl'; a TypeScript or unset source is left untouched. Indent and newline are\nread from the optional formatter config section, defaulting to two spaces and the\nsystem newline.");
|
|
70
71
|
setCommandExamples(command, ["prisma-next format", "prisma-next format --config ./custom-config.ts"]);
|
|
71
72
|
addGlobalOptions(command).option("--config <path>", "Path to prisma-next.config.ts").action(async (options) => {
|
|
72
73
|
const flags = parseGlobalFlagsOrExit(options);
|
|
@@ -99,4 +100,4 @@ function createFormatCommand() {
|
|
|
99
100
|
//#endregion
|
|
100
101
|
export { createFormatCommand as t };
|
|
101
102
|
|
|
102
|
-
//# sourceMappingURL=format-
|
|
103
|
+
//# sourceMappingURL=format-DI5qVr22.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format-DI5qVr22.mjs","names":[],"sources":["../src/control-api/operations/format.ts","../src/commands/format.ts"],"sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { EOL } from 'node:os';\nimport { loadConfig } from '@prisma-next/config-loader';\nimport { type FormatOptions, format } from '@prisma-next/psl-parser/format';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { isStructuredError } from '@prisma-next/utils/structured-error';\nimport { CliStructuredError, errorRuntime, errorUnexpected } from '../../utils/cli-errors';\n\nexport interface FormatOperationOptions {\n readonly configPath?: string;\n readonly eol?: string;\n}\n\nexport interface FormatOperationResult {\n readonly formatted: boolean;\n readonly path?: string;\n}\n\nexport function resolveNewline(\n formatterNewline: 'LF' | 'CRLF' | undefined,\n eol: string,\n): 'LF' | 'CRLF' {\n if (formatterNewline !== undefined) {\n return formatterNewline;\n }\n return eol === '\\r\\n' ? 'CRLF' : 'LF';\n}\n\nexport async function executeFormat(\n options: FormatOperationOptions,\n): Promise<Result<FormatOperationResult, CliStructuredError>> {\n const eol = options.eol ?? EOL;\n\n let config: Awaited<ReturnType<typeof loadConfig>>;\n try {\n config = await loadConfig(options.configPath);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(errorUnexpected(error instanceof Error ? error.message : String(error)));\n }\n\n const source = config.contract?.source;\n if (source?.format !== 'psl') {\n return ok({ formatted: false });\n }\n\n const inputPath = source.inputs?.[0];\n if (inputPath === undefined) {\n return ok({ formatted: false });\n }\n\n let contents: string;\n try {\n contents = await readFile(inputPath, 'utf-8');\n } catch (error) {\n return notOk(\n errorRuntime('Failed to read contract source file', {\n why: error instanceof Error ? error.message : String(error),\n fix: `Check that ${inputPath} exists and is readable.`,\n }),\n );\n }\n\n const formatOptions: FormatOptions = {\n indent: config.formatter?.indent ?? 2,\n newline: resolveNewline(config.formatter?.newline, eol),\n };\n\n let formatted: string;\n try {\n formatted = format(contents, formatOptions);\n } catch (error) {\n if (isStructuredError(error) && error.code === 'PSL.PARSE_FAILED') {\n return notOk(\n errorRuntime('Cannot format PSL with parse errors', {\n why: error.message,\n fix: 'Fix the parse errors in your schema and try again.',\n meta: { diagnostics: error.meta?.['diagnostics'] },\n }),\n );\n }\n return notOk(errorUnexpected(error instanceof Error ? error.message : String(error)));\n }\n\n try {\n await writeFile(inputPath, formatted, 'utf-8');\n } catch (error) {\n return notOk(\n errorRuntime('Failed to write formatted contract source file', {\n why: error instanceof Error ? error.message : String(error),\n fix: `Check that ${inputPath} is writable.`,\n }),\n );\n }\n\n return ok({ formatted: true, path: inputPath });\n}\n","import { ifDefined } from '@prisma-next/utils/defined';\nimport { Command } from 'commander';\nimport { relative, resolve } from 'pathe';\nimport { executeFormat } from '../control-api/operations/format';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI } from '../utils/terminal-ui';\n\ninterface FormatCommandOptions extends CommonCommandOptions {\n readonly config?: string;\n}\n\nexport function createFormatCommand(): Command {\n const command = new Command('format');\n setCommandDescriptions(\n command,\n 'Format your PSL contract source',\n 'Formats the Prisma schema (PSL) contract source declared in your config\\n' +\n '(contract.source.inputs[0]) in place. Only runs when contract.source.format\\n' +\n \"is 'psl'; a TypeScript or unset source is left untouched. Indent and newline are\\n\" +\n 'read from the optional formatter config section, defaulting to two spaces and the\\n' +\n 'system newline.',\n );\n setCommandExamples(command, [\n 'prisma-next format',\n 'prisma-next format --config ./custom-config.ts',\n ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: FormatCommandOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n\n if (!flags.json && !flags.quiet) {\n const displayConfigPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n ui.stderr(\n formatStyledHeader({\n command: 'format',\n description: 'Format your PSL contract source',\n details: [{ label: 'config', value: displayConfigPath }],\n flags,\n }),\n );\n }\n\n const result = await executeFormat({ ...ifDefined('configPath', options.config) });\n\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n return;\n }\n if (flags.quiet) {\n return;\n }\n if (value.formatted) {\n ui.success(`Formatted ${relative(process.cwd(), value.path ?? '')}`);\n } else {\n ui.info('Nothing to format (contract source is not PSL).');\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;AAkBA,SAAgB,eACd,kBACA,KACe;CACf,IAAI,qBAAqB,KAAA,GACvB,OAAO;CAET,OAAO,QAAQ,SAAS,SAAS;AACnC;AAEA,eAAsB,cACpB,SAC4D;CAC5D,MAAM,MAAM,QAAQ,OA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CAAC,CACH;CACF;CAEA,OAAO,GAAG;EAAE,WAAW;EAAM,MAAM;CAAU,CAAC;AAChD;;;AC/EA,SAAgB,sBAA+B;CAC7C,MAAM,UAAU,IAAI,QAAQ,QAAQ;CACpC,uBACE,SACA,mCACA,4UAKF;CACA,mBAAmB,SAAS,CAC1B,sBACA,gDACF,CAAC;CACD,iBAAiB,OAAO,CAAC,CACtB,OAAO,mBAAmB,+BAA+B,CAAC,CAC1D,OAAO,OAAO,YAAkC;EAC/C,MAAM,QAAQ,uBAAuB,OAAO;EAC5C,MAAM,KAAK,iBAAiB,KAAK;EAEjC,IAAI,CAAC,MAAM,QAAQ,CAAC,MAAM,OAAO;GAC/B,MAAM,oBAAoB,QAAQ,SAC9B,SAAS,QAAQ,IAAI,GAAG,QAAQ,QAAQ,MAAM,CAAC,IAC/C;GACJ,GAAG,OACD,mBAAmB;IACjB,SAAS;IACT,aAAa;IACb,SAAS,CAAC;KAAE,OAAO;KAAU,OAAO;IAAkB,CAAC;IACvD;GACF,CAAC,CACH;EACF;EAIA,MAAM,WAAW,aAAa,MAFT,cAAc,EAAE,GAAG,UAAU,cAAc,QAAQ,MAAM,EAAE,CAAC,GAE3C,OAAO,KAAK,UAAU;GAC1D,IAAI,MAAM,MAAM;IACd,GAAG,OAAO,KAAK,UAAU,KAAK,CAAC;IAC/B;GACF;GACA,IAAI,MAAM,OACR;GAEF,IAAI,MAAM,WACR,GAAG,QAAQ,aAAa,SAAS,QAAQ,IAAI,GAAG,MAAM,QAAQ,EAAE,GAAG;QAEnE,GAAG,KAAK,iDAAiD;EAE7D,CAAC;EACD,QAAQ,KAAK,QAAQ;CACvB,CAAC;CAEH,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as errorConfigValidation } from "./command-helpers-
|
|
1
|
+
import { R as errorConfigValidation } from "./command-helpers-D-jBl0Qt.mjs";
|
|
2
2
|
import "@prisma-next/framework-components/components";
|
|
3
3
|
//#region src/utils/framework-components.ts
|
|
4
4
|
/**
|
|
@@ -22,7 +22,7 @@ import "@prisma-next/framework-components/components";
|
|
|
22
22
|
* @example
|
|
23
23
|
* ```ts
|
|
24
24
|
* const config = await loadConfig();
|
|
25
|
-
* const frameworkComponents = [config.target, config.adapter, ...(config.
|
|
25
|
+
* const frameworkComponents = [config.target, config.adapter, ...(config.extensions ?? [])];
|
|
26
26
|
*
|
|
27
27
|
* // Validate and type-narrow components before passing to planner
|
|
28
28
|
* const typedComponents = assertFrameworkComponentsCompatible(
|
|
@@ -55,4 +55,4 @@ function assertFrameworkComponentsCompatible(expectedFamilyId, expectedTargetId,
|
|
|
55
55
|
//#endregion
|
|
56
56
|
export { assertFrameworkComponentsCompatible as t };
|
|
57
57
|
|
|
58
|
-
//# sourceMappingURL=framework-components-
|
|
58
|
+
//# sourceMappingURL=framework-components-C4XACYNB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"framework-components-C4XACYNB.mjs","names":[],"sources":["../src/utils/framework-components.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n checkContractComponentRequirements,\n type TargetBoundComponentDescriptor,\n} from '@prisma-next/framework-components/components';\nimport type { ControlStack } from '@prisma-next/framework-components/control';\nimport { errorConfigValidation, errorContractMissingExtensions } from './cli-errors';\n\n/**\n * Asserts that all framework components are compatible with the expected family and target.\n *\n * This function validates that each component in the framework components array:\n * - Has kind 'target', 'adapter', 'extension', or 'driver'\n * - Has familyId matching expectedFamilyId\n * - Has targetId matching expectedTargetId\n *\n * This validation happens at the CLI composition boundary, before passing components\n * to typed planner/runner instances. It fills the gap between runtime validation\n * (via `validateConfig()`) and compile-time type enforcement.\n *\n * @param expectedFamilyId - The expected family ID (e.g., 'sql')\n * @param expectedTargetId - The expected target ID (e.g., 'postgres')\n * @param frameworkComponents - Array of framework components to validate\n * @returns The same array typed as TargetBoundComponentDescriptor\n * @throws CliStructuredError if any component is incompatible\n *\n * @example\n * ```ts\n * const config = await loadConfig();\n * const frameworkComponents = [config.target, config.adapter, ...(config.extensions ?? [])];\n *\n * // Validate and type-narrow components before passing to planner\n * const typedComponents = assertFrameworkComponentsCompatible(\n * config.family.familyId,\n * config.target.targetId,\n * frameworkComponents\n * );\n *\n * const planner = target.migrations.createPlanner(familyInstance);\n * planner.plan({ contract, schema, policy, frameworkComponents: typedComponents });\n * ```\n */\nexport function assertFrameworkComponentsCompatible<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n expectedFamilyId: TFamilyId,\n expectedTargetId: TTargetId,\n frameworkComponents: ReadonlyArray<unknown>,\n): ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>> {\n for (let i = 0; i < frameworkComponents.length; i++) {\n const component = frameworkComponents[i];\n\n // Check that component is an object\n if (typeof component !== 'object' || component === null) {\n throw errorConfigValidation('frameworkComponents[]', {\n why: `Framework component at index ${i} must be an object`,\n });\n }\n\n const record = component as Record<string, unknown>;\n\n // Check kind\n if (!Object.hasOwn(record, 'kind')) {\n throw errorConfigValidation('frameworkComponents[].kind', {\n why: `Framework component at index ${i} must have 'kind' property`,\n });\n }\n\n const kind = record['kind'];\n if (kind !== 'target' && kind !== 'adapter' && kind !== 'extension' && kind !== 'driver') {\n throw errorConfigValidation('frameworkComponents[].kind', {\n why: `Framework component at index ${i} has invalid kind '${String(kind)}' (must be 'target', 'adapter', 'extension', or 'driver')`,\n });\n }\n\n // Check familyId\n if (!Object.hasOwn(record, 'familyId')) {\n throw errorConfigValidation('frameworkComponents[].familyId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'familyId' property`,\n });\n }\n\n const familyId = record['familyId'];\n if (familyId !== expectedFamilyId) {\n throw errorConfigValidation('frameworkComponents[].familyId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) has familyId '${String(familyId)}' but expected '${expectedFamilyId}'`,\n });\n }\n\n // Check targetId\n if (!Object.hasOwn(record, 'targetId')) {\n throw errorConfigValidation('frameworkComponents[].targetId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'targetId' property`,\n });\n }\n\n const targetId = record['targetId'];\n if (targetId !== expectedTargetId) {\n throw errorConfigValidation('frameworkComponents[].targetId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) has targetId '${String(targetId)}' but expected '${expectedTargetId}'`,\n });\n }\n }\n\n // Type assertion is safe because we've validated all components above\n return frameworkComponents as ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n}\n\n/**\n * Validates that a contract is compatible with the configured target, adapter,\n * and extension packs. Throws on family/target mismatches or missing extension packs.\n *\n * This check ensures the emitted contract matches the CLI config before running\n * commands that depend on the contract (e.g., db verify, db sign).\n *\n * @param contract - The contract to validate (must include targetFamily, target, extensions).\n * @param stack - The control plane stack (target, adapter, driver, extensions).\n *\n * @throws {CliStructuredError} errorConfigValidation when contract.targetFamily or contract.target\n * doesn't match the configured family/target.\n * @throws {CliStructuredError} errorContractMissingExtensions when the contract requires\n * extension packs that are not provided in the config (includes all missing packs in error.meta).\n *\n * @example\n * ```ts\n * import { assertContractRequirementsSatisfied } from './framework-components';\n *\n * const config = await loadConfig();\n * const contract = await loadContractJson(config.contract.output);\n * const stack = createControlStack({ family: config.family, target: config.target, adapter: config.adapter, ... });\n *\n * // Throws if contract is incompatible with config\n * assertContractRequirementsSatisfied({ contract, stack });\n * ```\n */\nexport function assertContractRequirementsSatisfied<\n TFamilyId extends string,\n TTargetId extends string,\n>({\n contract,\n stack,\n}: {\n readonly contract: Pick<Contract, 'targetFamily' | 'target' | 'extensions'>;\n readonly stack: ControlStack<TFamilyId, TTargetId>;\n}): void {\n const providedComponentIds = new Set<string>([\n stack.target.id,\n ...(stack.adapter ? [stack.adapter.id] : []),\n ]);\n for (const extension of stack.extensions) {\n providedComponentIds.add(extension.id);\n }\n\n const result = checkContractComponentRequirements({\n contract,\n expectedTargetFamily: stack.target.familyId,\n expectedTargetId: stack.target.targetId,\n providedComponentIds,\n });\n\n if (result.familyMismatch) {\n throw errorConfigValidation('contract.targetFamily', {\n why: `Contract was emitted for family '${result.familyMismatch.actual}' but CLI config is wired to '${result.familyMismatch.expected}'.`,\n });\n }\n\n if (result.targetMismatch) {\n throw errorConfigValidation('contract.target', {\n why: `Contract target '${result.targetMismatch.actual}' does not match CLI target '${result.targetMismatch.expected}'.`,\n });\n }\n\n if (result.missingExtensionPackIds.length > 0) {\n throw errorContractMissingExtensions({\n missingExtensions: result.missingExtensionPackIds,\n providedComponentIds: [...providedComponentIds],\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,oCAId,kBACA,kBACA,qBACqE;CACrE,KAAK,IAAI,IAAI,GAAG,IAAI,oBAAoB,QAAQ,KAAK;EACnD,MAAM,YAAY,oBAAoB;EAGtC,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,sBAAsB,yBAAyB,EACnD,KAAK,gCAAgC,EAAE,oBACzC,CAAC;EAGH,MAAM,SAAS;EAGf,IAAI,CAAC,OAAO,OAAO,QAAQ,MAAM,GAC/B,MAAM,sBAAsB,8BAA8B,EACxD,KAAK,gCAAgC,EAAE,4BACzC,CAAC;EAGH,MAAM,OAAO,OAAO;EACpB,IAAI,SAAS,YAAY,SAAS,aAAa,SAAS,eAAe,SAAS,UAC9E,MAAM,sBAAsB,8BAA8B,EACxD,KAAK,gCAAgC,EAAE,qBAAqB,OAAO,IAAI,EAAE,2DAC3E,CAAC;EAIH,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,GACnC,MAAM,sBAAsB,kCAAkC,EAC5D,KAAK,gCAAgC,EAAE,UAAU,OAAO,IAAI,EAAE,iCAChE,CAAC;EAGH,MAAM,WAAW,OAAO;EACxB,IAAI,aAAa,kBACf,MAAM,sBAAsB,kCAAkC,EAC5D,KAAK,gCAAgC,EAAE,UAAU,OAAO,IAAI,EAAE,kBAAkB,OAAO,QAAQ,EAAE,kBAAkB,iBAAiB,GACtI,CAAC;EAIH,IAAI,CA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