@prisma-next/cli 0.3.0-pr.99.6 → 0.4.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +381 -128
- package/dist/agent-skill-mongo.md +106 -0
- package/dist/agent-skill-postgres.md +106 -0
- package/dist/cli-errors-BDCYR5ap.mjs +4 -0
- package/dist/cli-errors-DStABy9d.d.mts +3 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.js +1 -2910
- package/dist/cli.mjs +254 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/client-DiUkJAeN.mjs +987 -0
- package/dist/client-DiUkJAeN.mjs.map +1 -0
- package/dist/commands/contract-emit.d.mts +7 -0
- package/dist/commands/contract-emit.d.mts.map +1 -0
- package/dist/commands/contract-emit.mjs +4 -0
- package/dist/commands/contract-infer.d.mts +7 -0
- package/dist/commands/contract-infer.d.mts.map +1 -0
- package/dist/commands/contract-infer.mjs +4 -0
- package/dist/commands/db-init.d.mts +7 -0
- package/dist/commands/db-init.d.mts.map +1 -0
- package/dist/commands/db-init.mjs +125 -0
- package/dist/commands/db-init.mjs.map +1 -0
- package/dist/commands/db-schema.d.mts +7 -0
- package/dist/commands/db-schema.d.mts.map +1 -0
- package/dist/commands/db-schema.mjs +53 -0
- package/dist/commands/db-schema.mjs.map +1 -0
- package/dist/commands/db-sign.d.mts +7 -0
- package/dist/commands/db-sign.d.mts.map +1 -0
- package/dist/commands/db-sign.mjs +136 -0
- package/dist/commands/db-sign.mjs.map +1 -0
- package/dist/commands/db-update.d.mts +7 -0
- package/dist/commands/db-update.d.mts.map +1 -0
- package/dist/commands/db-update.mjs +122 -0
- package/dist/commands/db-update.mjs.map +1 -0
- package/dist/commands/db-verify.d.mts +7 -0
- package/dist/commands/db-verify.d.mts.map +1 -0
- package/dist/commands/db-verify.mjs +322 -0
- package/dist/commands/db-verify.mjs.map +1 -0
- package/dist/commands/migration-apply.d.mts +36 -0
- package/dist/commands/migration-apply.d.mts.map +1 -0
- package/dist/commands/migration-apply.mjs +244 -0
- package/dist/commands/migration-apply.mjs.map +1 -0
- package/dist/commands/migration-new.d.mts +8 -0
- package/dist/commands/migration-new.d.mts.map +1 -0
- package/dist/commands/migration-new.mjs +152 -0
- package/dist/commands/migration-new.mjs.map +1 -0
- package/dist/commands/migration-plan.d.mts +47 -0
- package/dist/commands/migration-plan.d.mts.map +1 -0
- package/dist/commands/migration-plan.mjs +313 -0
- package/dist/commands/migration-plan.mjs.map +1 -0
- package/dist/commands/migration-ref.d.mts +43 -0
- package/dist/commands/migration-ref.d.mts.map +1 -0
- package/dist/commands/migration-ref.mjs +195 -0
- package/dist/commands/migration-ref.mjs.map +1 -0
- package/dist/commands/migration-show.d.mts +28 -0
- package/dist/commands/migration-show.d.mts.map +1 -0
- package/dist/commands/migration-show.mjs +140 -0
- package/dist/commands/migration-show.mjs.map +1 -0
- package/dist/commands/migration-status.d.mts +86 -0
- package/dist/commands/migration-status.d.mts.map +1 -0
- package/dist/commands/migration-status.mjs +4 -0
- package/dist/commands/migration-verify.d.mts +16 -0
- package/dist/commands/migration-verify.d.mts.map +1 -0
- package/dist/commands/migration-verify.mjs +110 -0
- package/dist/commands/migration-verify.mjs.map +1 -0
- package/dist/config-loader-C4VXKl8f.mjs +43 -0
- package/dist/config-loader-C4VXKl8f.mjs.map +1 -0
- package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
- package/dist/config-loader.d.mts.map +1 -0
- package/dist/config-loader.mjs +3 -0
- package/dist/contract-emit-D2wDXfyo.mjs +191 -0
- package/dist/contract-emit-D2wDXfyo.mjs.map +1 -0
- package/dist/contract-emit-D9WOShFz.mjs +4 -0
- package/dist/contract-emit-Zm_sd1wQ.mjs +112 -0
- package/dist/contract-emit-Zm_sd1wQ.mjs.map +1 -0
- package/dist/contract-enrichment-CGW6mm-E.mjs +79 -0
- package/dist/contract-enrichment-CGW6mm-E.mjs.map +1 -0
- package/dist/contract-infer-DozZT511.mjs +90 -0
- package/dist/contract-infer-DozZT511.mjs.map +1 -0
- package/dist/exports/config-types.d.mts +2 -0
- package/dist/exports/config-types.mjs +3 -0
- package/dist/exports/control-api.d.mts +624 -0
- package/dist/exports/control-api.d.mts.map +1 -0
- package/dist/exports/control-api.mjs +6 -0
- package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +12 -7
- package/dist/exports/index.d.mts.map +1 -0
- package/dist/exports/index.mjs +137 -0
- package/dist/exports/index.mjs.map +1 -0
- package/dist/extract-operation-statements-DZUJNmL3.mjs +13 -0
- package/dist/extract-operation-statements-DZUJNmL3.mjs.map +1 -0
- package/dist/extract-sql-ddl-DDMX-9mz.mjs +26 -0
- package/dist/extract-sql-ddl-DDMX-9mz.mjs.map +1 -0
- package/dist/framework-components-BAsliT4V.mjs +59 -0
- package/dist/framework-components-BAsliT4V.mjs.map +1 -0
- package/dist/init-DQ8auNB4.mjs +430 -0
- package/dist/init-DQ8auNB4.mjs.map +1 -0
- package/dist/inspect-live-schema-BYnhztxZ.mjs +91 -0
- package/dist/inspect-live-schema-BYnhztxZ.mjs.map +1 -0
- package/dist/migration-command-scaffold-CntCcntR.mjs +105 -0
- package/dist/migration-command-scaffold-CntCcntR.mjs.map +1 -0
- package/dist/migration-status-CJANY4yr.mjs +1583 -0
- package/dist/migration-status-CJANY4yr.mjs.map +1 -0
- package/dist/migrations-DTZBYXm1.mjs +173 -0
- package/dist/migrations-DTZBYXm1.mjs.map +1 -0
- package/dist/progress-adapter-B-YvmcDu.mjs +43 -0
- package/dist/progress-adapter-B-YvmcDu.mjs.map +1 -0
- package/dist/quick-reference-mongo.md +93 -0
- package/dist/quick-reference-postgres.md +91 -0
- package/dist/result-handler-oK_vA-Fn.mjs +697 -0
- package/dist/result-handler-oK_vA-Fn.mjs.map +1 -0
- package/dist/terminal-ui-C5k88MmW.mjs +274 -0
- package/dist/terminal-ui-C5k88MmW.mjs.map +1 -0
- package/dist/validate-contract-deps-esa-VQ0h.mjs +37 -0
- package/dist/validate-contract-deps-esa-VQ0h.mjs.map +1 -0
- package/dist/verify-DlFQ2FOw.mjs +385 -0
- package/dist/verify-DlFQ2FOw.mjs.map +1 -0
- package/package.json +87 -40
- package/src/cli.ts +118 -58
- package/src/commands/contract-emit.ts +101 -78
- package/src/commands/contract-infer-paths.ts +32 -0
- package/src/commands/contract-infer.ts +143 -0
- package/src/commands/db-init.ts +97 -219
- package/src/commands/db-schema.ts +77 -0
- package/src/commands/db-sign.ts +46 -73
- package/src/commands/db-update.ts +236 -0
- package/src/commands/db-verify.ts +409 -119
- package/src/commands/init/detect-package-manager.ts +47 -0
- package/src/commands/init/index.ts +21 -0
- package/src/commands/init/init.ts +203 -0
- package/src/commands/init/templates/agent-skill-mongo.md +106 -0
- package/src/commands/init/templates/agent-skill-postgres.md +106 -0
- package/src/commands/init/templates/agent-skill.ts +19 -0
- package/src/commands/init/templates/code-templates.ts +168 -0
- package/src/commands/init/templates/quick-reference-mongo.md +93 -0
- package/src/commands/init/templates/quick-reference-postgres.md +91 -0
- package/src/commands/init/templates/quick-reference.ts +19 -0
- package/src/commands/init/templates/render.ts +20 -0
- package/src/commands/init/templates/tsconfig.ts +35 -0
- package/src/commands/inspect-live-schema.ts +170 -0
- package/src/commands/migration-apply.ts +427 -0
- package/src/commands/migration-new.ts +260 -0
- package/src/commands/migration-plan.ts +519 -0
- package/src/commands/migration-ref.ts +305 -0
- package/src/commands/migration-show.ts +246 -0
- package/src/commands/migration-status.ts +864 -0
- package/src/commands/migration-verify.ts +180 -0
- package/src/config-loader.ts +13 -3
- package/src/control-api/client.ts +205 -183
- package/src/control-api/contract-enrichment.ts +119 -0
- package/src/control-api/errors.ts +9 -0
- package/src/control-api/operations/contract-emit.ts +181 -0
- package/src/control-api/operations/db-init.ts +53 -49
- package/src/control-api/operations/db-update.ts +220 -0
- package/src/control-api/operations/extract-operation-statements.ts +14 -0
- package/src/control-api/operations/extract-sql-ddl.ts +47 -0
- package/src/control-api/operations/migration-apply.ts +191 -0
- package/src/control-api/operations/migration-helpers.ts +49 -0
- package/src/control-api/types.ts +274 -52
- package/src/exports/config-types.ts +4 -3
- package/src/exports/control-api.ts +15 -5
- package/src/load-ts-contract.ts +30 -19
- package/src/utils/cli-errors.ts +14 -8
- package/src/utils/command-helpers.ts +302 -3
- package/src/utils/formatters/emit.ts +67 -0
- package/src/utils/formatters/errors.ts +82 -0
- package/src/utils/formatters/graph-migration-mapper.ts +240 -0
- package/src/utils/formatters/graph-render.ts +1323 -0
- package/src/utils/formatters/graph-types.ts +120 -0
- package/src/utils/formatters/help.ts +380 -0
- package/src/utils/formatters/helpers.ts +28 -0
- package/src/utils/formatters/migrations.ts +346 -0
- package/src/utils/formatters/styled.ts +212 -0
- package/src/utils/formatters/verify.ts +621 -0
- package/src/utils/framework-components.ts +13 -10
- package/src/utils/global-flags.ts +41 -23
- package/src/utils/migration-command-scaffold.ts +184 -0
- package/src/utils/migration-types.ts +12 -0
- package/src/utils/progress-adapter.ts +18 -29
- package/src/utils/result-handler.ts +12 -13
- package/src/utils/shutdown.ts +92 -0
- package/src/utils/suggest-command.ts +31 -0
- package/src/utils/terminal-ui.ts +276 -0
- package/src/utils/validate-contract-deps.ts +49 -0
- package/dist/chunk-AGOTG4L3.js +0 -965
- package/dist/chunk-AGOTG4L3.js.map +0 -1
- package/dist/chunk-HLLI4YL7.js +0 -180
- package/dist/chunk-HLLI4YL7.js.map +0 -1
- package/dist/chunk-HWYQOCAJ.js +0 -47
- package/dist/chunk-HWYQOCAJ.js.map +0 -1
- package/dist/chunk-VG2R7DGF.js +0 -735
- package/dist/chunk-VG2R7DGF.js.map +0 -1
- package/dist/cli.d.ts +0 -2
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/commands/contract-emit.d.ts +0 -3
- package/dist/commands/contract-emit.d.ts.map +0 -1
- package/dist/commands/contract-emit.js +0 -10
- package/dist/commands/contract-emit.js.map +0 -1
- package/dist/commands/db-init.d.ts +0 -3
- package/dist/commands/db-init.d.ts.map +0 -1
- package/dist/commands/db-init.js +0 -257
- package/dist/commands/db-init.js.map +0 -1
- package/dist/commands/db-introspect.d.ts +0 -3
- package/dist/commands/db-introspect.d.ts.map +0 -1
- package/dist/commands/db-introspect.js +0 -155
- package/dist/commands/db-introspect.js.map +0 -1
- package/dist/commands/db-schema-verify.d.ts +0 -3
- package/dist/commands/db-schema-verify.d.ts.map +0 -1
- package/dist/commands/db-schema-verify.js +0 -171
- package/dist/commands/db-schema-verify.js.map +0 -1
- package/dist/commands/db-sign.d.ts +0 -3
- package/dist/commands/db-sign.d.ts.map +0 -1
- package/dist/commands/db-sign.js +0 -195
- package/dist/commands/db-sign.js.map +0 -1
- package/dist/commands/db-verify.d.ts +0 -3
- package/dist/commands/db-verify.d.ts.map +0 -1
- package/dist/commands/db-verify.js +0 -193
- package/dist/commands/db-verify.js.map +0 -1
- package/dist/config-loader.d.ts.map +0 -1
- package/dist/config-loader.js +0 -7
- package/dist/config-loader.js.map +0 -1
- package/dist/control-api/client.d.ts +0 -13
- package/dist/control-api/client.d.ts.map +0 -1
- package/dist/control-api/operations/db-init.d.ts +0 -29
- package/dist/control-api/operations/db-init.d.ts.map +0 -1
- package/dist/control-api/types.d.ts +0 -387
- package/dist/control-api/types.d.ts.map +0 -1
- package/dist/exports/config-types.d.ts +0 -3
- package/dist/exports/config-types.d.ts.map +0 -1
- package/dist/exports/config-types.js +0 -6
- package/dist/exports/config-types.js.map +0 -1
- package/dist/exports/control-api.d.ts +0 -13
- package/dist/exports/control-api.d.ts.map +0 -1
- package/dist/exports/control-api.js +0 -7
- package/dist/exports/control-api.js.map +0 -1
- package/dist/exports/index.d.ts +0 -4
- package/dist/exports/index.d.ts.map +0 -1
- package/dist/exports/index.js +0 -176
- package/dist/exports/index.js.map +0 -1
- package/dist/load-ts-contract.d.ts.map +0 -1
- package/dist/utils/cli-errors.d.ts +0 -7
- package/dist/utils/cli-errors.d.ts.map +0 -1
- package/dist/utils/command-helpers.d.ts +0 -12
- package/dist/utils/command-helpers.d.ts.map +0 -1
- package/dist/utils/framework-components.d.ts +0 -70
- package/dist/utils/framework-components.d.ts.map +0 -1
- package/dist/utils/global-flags.d.ts +0 -25
- package/dist/utils/global-flags.d.ts.map +0 -1
- package/dist/utils/output.d.ts +0 -142
- package/dist/utils/output.d.ts.map +0 -1
- package/dist/utils/progress-adapter.d.ts +0 -26
- package/dist/utils/progress-adapter.d.ts.map +0 -1
- package/dist/utils/result-handler.d.ts +0 -15
- package/dist/utils/result-handler.d.ts.map +0 -1
- package/src/commands/db-introspect.ts +0 -227
- package/src/commands/db-schema-verify.ts +0 -238
- package/src/utils/output.ts +0 -1471
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { t as loadConfig } from "../config-loader-C4VXKl8f.mjs";
|
|
2
|
+
import { _ as errorUnexpected, c as errorDriverRequired, h as errorTargetMigrationNotSupported, m as errorRuntime, o as errorDatabaseConnectionRequired, t as CliStructuredError } from "../cli-errors-BDCYR5ap.mjs";
|
|
3
|
+
import { t as createControlClient } from "../client-DiUkJAeN.mjs";
|
|
4
|
+
import { _ as formatStyledHeader, a as maskConnectionUrl, c as resolveMigrationPaths, d as setCommandExamples, f as targetSupportsMigrations, i as loadAllBundles, m as parseGlobalFlags, n as addGlobalOptions, o as readContractEnvelope, p as toPathDecisionResult, t as handleResult, u as setCommandDescriptions } from "../result-handler-oK_vA-Fn.mjs";
|
|
5
|
+
import { t as TerminalUI } from "../terminal-ui-C5k88MmW.mjs";
|
|
6
|
+
import { t as formatMigrationApplyCommandOutput } from "../migrations-DTZBYXm1.mjs";
|
|
7
|
+
import { Command } from "commander";
|
|
8
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
9
|
+
import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
|
|
10
|
+
import { findPathWithDecision } from "@prisma-next/migration-tools/dag";
|
|
11
|
+
import { MigrationToolsError } from "@prisma-next/migration-tools/types";
|
|
12
|
+
import { readRefs, resolveRef } from "@prisma-next/migration-tools/refs";
|
|
13
|
+
|
|
14
|
+
//#region src/commands/migration-apply.ts
|
|
15
|
+
function mapMigrationToolsError(error) {
|
|
16
|
+
if (MigrationToolsError.is(error)) return errorRuntime(error.message, {
|
|
17
|
+
why: error.why,
|
|
18
|
+
fix: error.fix,
|
|
19
|
+
meta: {
|
|
20
|
+
code: error.code,
|
|
21
|
+
...error.details ?? {}
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
return errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}` });
|
|
25
|
+
}
|
|
26
|
+
function mapApplyFailure(failure) {
|
|
27
|
+
return errorRuntime(failure.summary, {
|
|
28
|
+
why: failure.why ?? "Migration runner failed",
|
|
29
|
+
fix: "Fix the issue and re-run `prisma-next migration apply` — previously applied migrations are preserved.",
|
|
30
|
+
meta: failure.meta ?? {}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function packageToStep(pkg) {
|
|
34
|
+
return {
|
|
35
|
+
dirName: pkg.dirName,
|
|
36
|
+
from: pkg.manifest.from,
|
|
37
|
+
to: pkg.manifest.to,
|
|
38
|
+
toContract: pkg.manifest.toContract,
|
|
39
|
+
operations: pkg.ops
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async function executeMigrationApplyCommand(options, flags, ui, startTime) {
|
|
43
|
+
const config = await loadConfig(options.config);
|
|
44
|
+
const { configPath, migrationsDir, migrationsRelative, refsPath } = resolveMigrationPaths(options.config, config);
|
|
45
|
+
const dbConnection = options.db ?? config.db?.connection;
|
|
46
|
+
if (!dbConnection) return notOk(errorDatabaseConnectionRequired({
|
|
47
|
+
why: `Database connection is required for migration apply (set db.connection in ${configPath}, or pass --db <url>)`,
|
|
48
|
+
commandName: "migration apply"
|
|
49
|
+
}));
|
|
50
|
+
if (!config.driver) return notOk(errorDriverRequired({ why: "Config.driver is required for migration apply" }));
|
|
51
|
+
if (!targetSupportsMigrations(config.target)) return notOk(errorTargetMigrationNotSupported({ why: `Target "${config.target.id}" does not support migrations` }));
|
|
52
|
+
let destinationHash;
|
|
53
|
+
let refName;
|
|
54
|
+
if (options.ref) {
|
|
55
|
+
refName = options.ref;
|
|
56
|
+
try {
|
|
57
|
+
destinationHash = resolveRef(await readRefs(refsPath), refName);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
} else try {
|
|
63
|
+
destinationHash = (await readContractEnvelope(config)).storageHash;
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return notOk(errorRuntime("Current contract is unavailable", {
|
|
66
|
+
why: `Failed to read contract: ${error instanceof Error ? error.message : String(error)}`,
|
|
67
|
+
fix: "Run `prisma-next contract emit` to generate a valid contract.json, then retry apply."
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
if (!flags.json && !flags.quiet) {
|
|
71
|
+
const details = [{
|
|
72
|
+
label: "config",
|
|
73
|
+
value: configPath
|
|
74
|
+
}, {
|
|
75
|
+
label: "migrations",
|
|
76
|
+
value: migrationsRelative
|
|
77
|
+
}];
|
|
78
|
+
if (typeof dbConnection === "string") details.push({
|
|
79
|
+
label: "database",
|
|
80
|
+
value: maskConnectionUrl(dbConnection)
|
|
81
|
+
});
|
|
82
|
+
if (refName) details.push({
|
|
83
|
+
label: "ref",
|
|
84
|
+
value: refName
|
|
85
|
+
});
|
|
86
|
+
const header = formatStyledHeader({
|
|
87
|
+
command: "migration apply",
|
|
88
|
+
description: "Apply planned migrations to the database",
|
|
89
|
+
url: "https://pris.ly/migration-apply",
|
|
90
|
+
details,
|
|
91
|
+
flags
|
|
92
|
+
});
|
|
93
|
+
ui.stderr(header);
|
|
94
|
+
}
|
|
95
|
+
let migrations;
|
|
96
|
+
try {
|
|
97
|
+
migrations = await loadAllBundles(migrationsDir);
|
|
98
|
+
if (migrations.drafts.length > 0 && !flags.quiet) ui.warn(`${migrations.drafts.length} draft migration(s) found: ${migrations.drafts.map((d) => d.dirName).join(", ")}. Run 'prisma-next migration verify --dir <path>' to attest before applying.`);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
const client = createControlClient({
|
|
104
|
+
family: config.family,
|
|
105
|
+
target: config.target,
|
|
106
|
+
adapter: config.adapter,
|
|
107
|
+
driver: config.driver,
|
|
108
|
+
extensionPacks: config.extensionPacks ?? []
|
|
109
|
+
});
|
|
110
|
+
try {
|
|
111
|
+
await client.connect(dbConnection);
|
|
112
|
+
const marker = await client.readMarker();
|
|
113
|
+
if (migrations.attested.length === 0) {
|
|
114
|
+
if (marker?.storageHash) return notOk(errorRuntime("Database has state but no migrations exist", {
|
|
115
|
+
why: `The database marker hash "${marker.storageHash}" exists but no attested migrations were found in ${migrationsRelative}`,
|
|
116
|
+
fix: "Ensure the migrations directory is correct. If the database was managed with `db init` or `db update`, run `prisma-next db sign` to update the marker.",
|
|
117
|
+
meta: {
|
|
118
|
+
markerHash: marker.storageHash,
|
|
119
|
+
migrationsDir: migrationsRelative
|
|
120
|
+
}
|
|
121
|
+
}));
|
|
122
|
+
if (destinationHash !== EMPTY_CONTRACT_HASH) return notOk(errorRuntime("Current contract has no planned migrations", {
|
|
123
|
+
why: `No attested migrations were found in ${migrationsRelative}, but current contract hash is "${destinationHash}"`,
|
|
124
|
+
fix: "Run `prisma-next migration plan` to create an attested migration for the current contract.",
|
|
125
|
+
meta: {
|
|
126
|
+
destinationHash,
|
|
127
|
+
migrationsDir: migrationsRelative
|
|
128
|
+
}
|
|
129
|
+
}));
|
|
130
|
+
return ok({
|
|
131
|
+
ok: true,
|
|
132
|
+
migrationsApplied: 0,
|
|
133
|
+
migrationsTotal: 0,
|
|
134
|
+
markerHash: EMPTY_CONTRACT_HASH,
|
|
135
|
+
applied: [],
|
|
136
|
+
summary: "No attested migrations found",
|
|
137
|
+
timings: { total: Date.now() - startTime }
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
if (marker?.storageHash === EMPTY_CONTRACT_HASH) return notOk(errorRuntime("Database marker contains the empty sentinel hash", {
|
|
141
|
+
why: `The marker row exists but contains the empty sentinel value "${EMPTY_CONTRACT_HASH}". This should never happen — the marker should contain the hash of the last applied contract.`,
|
|
142
|
+
fix: "The marker is corrupted. Run `prisma-next db sign` to overwrite it with the correct contract hash, or drop and recreate the database.",
|
|
143
|
+
meta: { markerHash: EMPTY_CONTRACT_HASH }
|
|
144
|
+
}));
|
|
145
|
+
const markerHash = marker?.storageHash;
|
|
146
|
+
if (markerHash !== void 0 && !migrations.graph.nodes.has(markerHash)) return notOk(errorRuntime("Database marker does not match any known migration", {
|
|
147
|
+
why: `The database marker hash "${markerHash}" is not found in the migration history at ${migrationsRelative}`,
|
|
148
|
+
fix: "Ensure the migrations directory matches this database. If the database was managed with `db init` or `db update`, run `prisma-next db sign` to update the marker.",
|
|
149
|
+
meta: {
|
|
150
|
+
markerHash,
|
|
151
|
+
knownNodes: [...migrations.graph.nodes]
|
|
152
|
+
}
|
|
153
|
+
}));
|
|
154
|
+
if (!migrations.graph.nodes.has(destinationHash)) {
|
|
155
|
+
const matchingDraft = migrations.drafts.find((d) => d.manifest.to === destinationHash);
|
|
156
|
+
return notOk(errorRuntime("Current contract has no planned migration path", {
|
|
157
|
+
why: matchingDraft ? `A draft migration exists at "${matchingDraft.dirName}" but has not been attested` : `Current contract hash "${destinationHash}" is not present in the migration history at ${migrationsRelative}`,
|
|
158
|
+
fix: matchingDraft ? `Run 'prisma-next migration verify --dir ${migrationsRelative}/${matchingDraft.dirName}' to attest, then re-run apply.` : "Run `prisma-next migration plan` to create a migration for the current contract, then re-run apply.",
|
|
159
|
+
meta: {
|
|
160
|
+
destinationHash,
|
|
161
|
+
knownNodes: [...migrations.graph.nodes]
|
|
162
|
+
}
|
|
163
|
+
}));
|
|
164
|
+
}
|
|
165
|
+
const originHash = markerHash ?? EMPTY_CONTRACT_HASH;
|
|
166
|
+
const decision = findPathWithDecision(migrations.graph, originHash, destinationHash, refName);
|
|
167
|
+
if (!decision) return notOk(errorRuntime("No migration path from current state to target", {
|
|
168
|
+
why: `Cannot find a path from "${originHash}" to target "${destinationHash}"`,
|
|
169
|
+
fix: "Check the migration history for gaps or inconsistencies.",
|
|
170
|
+
meta: {
|
|
171
|
+
markerHash: originHash,
|
|
172
|
+
destinationHash
|
|
173
|
+
}
|
|
174
|
+
}));
|
|
175
|
+
const pendingPath = decision.selectedPath;
|
|
176
|
+
const pathDecision = toPathDecisionResult(decision);
|
|
177
|
+
if (pendingPath.length === 0) return ok({
|
|
178
|
+
ok: true,
|
|
179
|
+
migrationsApplied: 0,
|
|
180
|
+
migrationsTotal: 0,
|
|
181
|
+
markerHash: originHash,
|
|
182
|
+
applied: [],
|
|
183
|
+
summary: "Already up to date",
|
|
184
|
+
pathDecision,
|
|
185
|
+
timings: { total: Date.now() - startTime }
|
|
186
|
+
});
|
|
187
|
+
const bundleByDir = new Map(migrations.attested.map((b) => [b.dirName, b]));
|
|
188
|
+
const pendingMigrations = [];
|
|
189
|
+
for (const migration of pendingPath) {
|
|
190
|
+
const pkg = bundleByDir.get(migration.dirName);
|
|
191
|
+
if (!pkg) return notOk(errorRuntime(`Migration package not found: ${migration.dirName}`, {
|
|
192
|
+
why: `The migration directory for path segment ${migration.from} → ${migration.to} was not found`,
|
|
193
|
+
fix: "Ensure all migration directories are present and intact."
|
|
194
|
+
}));
|
|
195
|
+
pendingMigrations.push(packageToStep(pkg));
|
|
196
|
+
}
|
|
197
|
+
if (!flags.quiet && !flags.json) for (const migration of pendingMigrations) ui.step(`Pending ${migration.dirName}`);
|
|
198
|
+
const applyResult = await client.migrationApply({
|
|
199
|
+
originHash,
|
|
200
|
+
destinationHash,
|
|
201
|
+
pendingMigrations
|
|
202
|
+
});
|
|
203
|
+
if (!applyResult.ok) return notOk(mapApplyFailure(applyResult.failure));
|
|
204
|
+
const { value } = applyResult;
|
|
205
|
+
return ok({
|
|
206
|
+
ok: true,
|
|
207
|
+
migrationsApplied: value.migrationsApplied,
|
|
208
|
+
migrationsTotal: pendingPath.length,
|
|
209
|
+
markerHash: value.markerHash,
|
|
210
|
+
applied: value.applied,
|
|
211
|
+
summary: value.summary,
|
|
212
|
+
pathDecision,
|
|
213
|
+
timings: { total: Date.now() - startTime }
|
|
214
|
+
});
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (CliStructuredError.is(error)) return notOk(error);
|
|
217
|
+
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}` }));
|
|
218
|
+
} finally {
|
|
219
|
+
await client.close();
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function createMigrationApplyCommand() {
|
|
223
|
+
const command = new Command("apply");
|
|
224
|
+
setCommandDescriptions(command, "Apply planned migrations to the database", "Applies previously planned migrations (created by `migration plan`) to a live database.\nCompares the database marker against the migration history to determine which\nmigrations are pending, then executes them sequentially. Each migration runs\nin its own transaction. Does not plan new migrations — run `migration plan` first.");
|
|
225
|
+
setCommandExamples(command, ["prisma-next migration apply --db $DATABASE_URL"]);
|
|
226
|
+
addGlobalOptions(command).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--ref <name>", "Target ref name from migrations/refs/").action(async (options) => {
|
|
227
|
+
const flags = parseGlobalFlags(options);
|
|
228
|
+
const startTime = Date.now();
|
|
229
|
+
const ui = new TerminalUI({
|
|
230
|
+
color: flags.color,
|
|
231
|
+
interactive: flags.interactive
|
|
232
|
+
});
|
|
233
|
+
const exitCode = handleResult(await executeMigrationApplyCommand(options, flags, ui, startTime), flags, ui, (applyResult) => {
|
|
234
|
+
if (flags.json) ui.output(JSON.stringify(applyResult, null, 2));
|
|
235
|
+
else if (!flags.quiet) ui.log(formatMigrationApplyCommandOutput(applyResult, flags));
|
|
236
|
+
});
|
|
237
|
+
process.exit(exitCode);
|
|
238
|
+
});
|
|
239
|
+
return command;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
//#endregion
|
|
243
|
+
export { createMigrationApplyCommand };
|
|
244
|
+
//# sourceMappingURL=migration-apply.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-apply.mjs","names":["destinationHash: string","refName: string | undefined","details: Array<{ label: string; value: string }>","migrations: MigrationBundleSet","pendingMigrations: MigrationApplyStep[]"],"sources":["../../src/commands/migration-apply.ts"],"sourcesContent":["import { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { findPathWithDecision } from '@prisma-next/migration-tools/dag';\nimport { readRefs, resolveRef } from '@prisma-next/migration-tools/refs';\nimport type { AttestedMigrationBundle } from '@prisma-next/migration-tools/types';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\n\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { MigrationApplyFailure, MigrationApplyStep } from '../control-api/types';\nimport {\n CliStructuredError,\n type CliStructuredError as CliStructuredErrorType,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n loadAllBundles,\n type MigrationBundleSet,\n maskConnectionUrl,\n readContractEnvelope,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n targetSupportsMigrations,\n toPathDecisionResult,\n} from '../utils/command-helpers';\nimport { formatMigrationApplyCommandOutput } from '../utils/formatters/migrations';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationApplyCommandOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly ref?: string;\n}\n\nexport interface MigrationApplyResult {\n readonly ok: boolean;\n readonly migrationsApplied: number;\n readonly migrationsTotal: number;\n readonly markerHash: string;\n readonly applied: readonly {\n readonly dirName: string;\n readonly from: string;\n readonly to: string;\n readonly operationsExecuted: number;\n }[];\n readonly summary: string;\n readonly pathDecision?: {\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n readonly selectedPath: readonly {\n readonly dirName: string;\n readonly migrationId: string | null;\n readonly from: string;\n readonly to: string;\n }[];\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nfunction mapMigrationToolsError(error: unknown): CliStructuredErrorType {\n if (MigrationToolsError.is(error)) {\n return errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code, ...(error.details ?? {}) },\n });\n }\n return errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\nfunction mapApplyFailure(failure: MigrationApplyFailure): CliStructuredErrorType {\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Fix the issue and re-run `prisma-next migration apply` — previously applied migrations are preserved.',\n meta: failure.meta ?? {},\n });\n}\n\nfunction packageToStep(pkg: AttestedMigrationBundle): MigrationApplyStep {\n return {\n dirName: pkg.dirName,\n from: pkg.manifest.from,\n to: pkg.manifest.to,\n toContract: pkg.manifest.toContract,\n operations: pkg.ops,\n };\n}\n\nasync function executeMigrationApplyCommand(\n options: MigrationApplyCommandOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationApplyResult, CliStructuredErrorType>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, migrationsRelative, refsPath } = resolveMigrationPaths(\n options.config,\n config,\n );\n\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for migration apply (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: 'migration apply',\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: 'Config.driver is required for migration apply',\n }),\n );\n }\n\n if (!targetSupportsMigrations(config.target)) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n let destinationHash: string;\n let refName: string | undefined;\n\n if (options.ref) {\n refName = options.ref;\n try {\n const refs = await readRefs(refsPath);\n destinationHash = resolveRef(refs, refName);\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n } else {\n try {\n const envelope = await readContractEnvelope(config);\n destinationHash = envelope.storageHash;\n } catch (error) {\n return notOk(\n errorRuntime('Current contract is unavailable', {\n why: `Failed to read contract: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to generate a valid contract.json, then retry apply.',\n }),\n );\n }\n }\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: migrationsRelative },\n ];\n if (typeof dbConnection === 'string') {\n details.push({\n label: 'database',\n value: maskConnectionUrl(dbConnection),\n });\n }\n if (refName) {\n details.push({ label: 'ref', value: refName });\n }\n const header = formatStyledHeader({\n command: 'migration apply',\n description: 'Apply planned migrations to the database',\n url: 'https://pris.ly/migration-apply',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // Read migrations and build migration chain model (offline — no DB needed)\n let migrations: MigrationBundleSet;\n try {\n migrations = await loadAllBundles(migrationsDir);\n if (migrations.drafts.length > 0 && !flags.quiet) {\n ui.warn(\n `${migrations.drafts.length} draft migration(s) found: ${migrations.drafts.map((d) => d.dirName).join(', ')}. ` +\n \"Run 'prisma-next migration verify --dir <path>' to attest before applying.\",\n );\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n try {\n await client.connect(dbConnection);\n const marker = await client.readMarker();\n\n // --- No attested migrations on disk ---\n if (migrations.attested.length === 0) {\n if (marker?.storageHash) {\n return notOk(\n errorRuntime('Database has state but no migrations exist', {\n why: `The database marker hash \"${marker.storageHash}\" exists but no attested migrations were found in ${migrationsRelative}`,\n fix: 'Ensure the migrations directory is correct. If the database was managed with `db init` or `db update`, run `prisma-next db sign` to update the marker.',\n meta: { markerHash: marker.storageHash, migrationsDir: migrationsRelative },\n }),\n );\n }\n // Non-empty contract + no migrations = user needs to plan first.\n if (destinationHash !== EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Current contract has no planned migrations', {\n why: `No attested migrations were found in ${migrationsRelative}, but current contract hash is \"${destinationHash}\"`,\n fix: 'Run `prisma-next migration plan` to create an attested migration for the current contract.',\n meta: { destinationHash, migrationsDir: migrationsRelative },\n }),\n );\n }\n // Empty contract + no migrations = nothing to do.\n return ok({\n ok: true,\n migrationsApplied: 0,\n migrationsTotal: 0,\n markerHash: EMPTY_CONTRACT_HASH,\n applied: [],\n summary: 'No attested migrations found',\n timings: { total: Date.now() - startTime },\n });\n }\n\n // --- Validate marker state ---\n\n // The empty sentinel should never appear in a real marker row — if it does,\n // the marker was corrupted and replaying all migrations would be dangerous.\n if (marker?.storageHash === EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Database marker contains the empty sentinel hash', {\n why: `The marker row exists but contains the empty sentinel value \"${EMPTY_CONTRACT_HASH}\". This should never happen — the marker should contain the hash of the last applied contract.`,\n fix: 'The marker is corrupted. Run `prisma-next db sign` to overwrite it with the correct contract hash, or drop and recreate the database.',\n meta: { markerHash: EMPTY_CONTRACT_HASH },\n }),\n );\n }\n\n const markerHash = marker?.storageHash;\n\n if (markerHash !== undefined && !migrations.graph.nodes.has(markerHash)) {\n return notOk(\n errorRuntime('Database marker does not match any known migration', {\n why: `The database marker hash \"${markerHash}\" is not found in the migration history at ${migrationsRelative}`,\n fix: 'Ensure the migrations directory matches this database. If the database was managed with `db init` or `db update`, run `prisma-next db sign` to update the marker.',\n meta: { markerHash, knownNodes: [...migrations.graph.nodes] },\n }),\n );\n }\n\n if (!migrations.graph.nodes.has(destinationHash)) {\n const matchingDraft = migrations.drafts.find((d) => d.manifest.to === destinationHash);\n return notOk(\n errorRuntime('Current contract has no planned migration path', {\n why: matchingDraft\n ? `A draft migration exists at \"${matchingDraft.dirName}\" but has not been attested`\n : `Current contract hash \"${destinationHash}\" is not present in the migration history at ${migrationsRelative}`,\n fix: matchingDraft\n ? `Run 'prisma-next migration verify --dir ${migrationsRelative}/${matchingDraft.dirName}' to attest, then re-run apply.`\n : 'Run `prisma-next migration plan` to create a migration for the current contract, then re-run apply.',\n meta: { destinationHash, knownNodes: [...migrations.graph.nodes] },\n }),\n );\n }\n\n // --- Resolve path and apply ---\n\n // \"No marker\" means the database is fresh — start from the empty contract hash.\n const originHash = markerHash ?? EMPTY_CONTRACT_HASH;\n\n const decision = findPathWithDecision(migrations.graph, originHash, destinationHash, refName);\n if (!decision) {\n return notOk(\n errorRuntime('No migration path from current state to target', {\n why: `Cannot find a path from \"${originHash}\" to target \"${destinationHash}\"`,\n fix: 'Check the migration history for gaps or inconsistencies.',\n meta: { markerHash: originHash, destinationHash },\n }),\n );\n }\n\n const pendingPath = decision.selectedPath;\n const pathDecision = toPathDecisionResult(decision);\n\n if (pendingPath.length === 0) {\n return ok({\n ok: true,\n migrationsApplied: 0,\n migrationsTotal: 0,\n markerHash: originHash,\n applied: [],\n summary: 'Already up to date',\n pathDecision,\n timings: { total: Date.now() - startTime },\n });\n }\n\n const bundleByDir = new Map(migrations.attested.map((b) => [b.dirName, b]));\n const pendingMigrations: MigrationApplyStep[] = [];\n for (const migration of pendingPath) {\n const pkg = bundleByDir.get(migration.dirName);\n if (!pkg) {\n return notOk(\n errorRuntime(`Migration package not found: ${migration.dirName}`, {\n why: `The migration directory for path segment ${migration.from} → ${migration.to} was not found`,\n fix: 'Ensure all migration directories are present and intact.',\n }),\n );\n }\n pendingMigrations.push(packageToStep(pkg));\n }\n\n if (!flags.quiet && !flags.json) {\n for (const migration of pendingMigrations) {\n ui.step(`Pending ${migration.dirName}`);\n }\n }\n\n const applyResult = await client.migrationApply({\n originHash,\n destinationHash,\n pendingMigrations,\n });\n\n if (!applyResult.ok) {\n return notOk(mapApplyFailure(applyResult.failure));\n }\n\n const { value } = applyResult;\n\n return ok({\n ok: true,\n migrationsApplied: value.migrationsApplied,\n migrationsTotal: pendingPath.length,\n markerHash: value.markerHash,\n applied: value.applied,\n summary: value.summary,\n pathDecision,\n timings: { total: Date.now() - startTime },\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createMigrationApplyCommand(): Command {\n const command = new Command('apply');\n setCommandDescriptions(\n command,\n 'Apply planned migrations to the database',\n 'Applies previously planned migrations (created by `migration plan`) to a live database.\\n' +\n 'Compares the database marker against the migration history to determine which\\n' +\n 'migrations are pending, then executes them sequentially. Each migration runs\\n' +\n 'in its own transaction. Does not plan new migrations — run `migration plan` first.',\n );\n setCommandExamples(command, ['prisma-next migration apply --db $DATABASE_URL']);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--ref <name>', 'Target ref name from migrations/refs/')\n .action(async (options: MigrationApplyCommandOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const ui = new TerminalUI({\n color: flags.color,\n interactive: flags.interactive,\n });\n\n const result = await executeMigrationApplyCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (applyResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(applyResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationApplyCommandOutput(applyResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;AA2EA,SAAS,uBAAuB,OAAwC;AACtE,KAAI,oBAAoB,GAAG,MAAM,CAC/B,QAAO,aAAa,MAAM,SAAS;EACjC,KAAK,MAAM;EACX,KAAK,MAAM;EACX,MAAM;GAAE,MAAM,MAAM;GAAM,GAAI,MAAM,WAAW,EAAE;GAAG;EACrD,CAAC;AAEJ,QAAO,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAAE,EAC7E,KAAK,4CAA4C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IACxG,CAAC;;AAGJ,SAAS,gBAAgB,SAAwD;AAC/E,QAAO,aAAa,QAAQ,SAAS;EACnC,KAAK,QAAQ,OAAO;EACpB,KAAK;EACL,MAAM,QAAQ,QAAQ,EAAE;EACzB,CAAC;;AAGJ,SAAS,cAAc,KAAkD;AACvE,QAAO;EACL,SAAS,IAAI;EACb,MAAM,IAAI,SAAS;EACnB,IAAI,IAAI,SAAS;EACjB,YAAY,IAAI,SAAS;EACzB,YAAY,IAAI;EACjB;;AAGH,eAAe,6BACb,SACA,OACA,IACA,WAC+D;CAC/D,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,EAAE,YAAY,eAAe,oBAAoB,aAAa,sBAClE,QAAQ,QACR,OACD;CAED,MAAM,eAAe,QAAQ,MAAM,OAAO,IAAI;AAC9C,KAAI,CAAC,aACH,QAAO,MACL,gCAAgC;EAC9B,KAAK,6EAA6E,WAAW;EAC7F,aAAa;EACd,CAAC,CACH;AAGH,KAAI,CAAC,OAAO,OACV,QAAO,MACL,oBAAoB,EAClB,KAAK,iDACN,CAAC,CACH;AAGH,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CAAC;YACtC,CAAC,MAAM,MAChB,IAAG,IAAI,kCAAkC,aAAa,MAAM,CAAC;IAE/D;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-new.d.mts","names":[],"sources":["../../src/commands/migration-new.ts"],"sourcesContent":[],"mappings":";;;;iBAiNgB,yBAAA,CAAA,GAA6B"}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { t as loadConfig } from "../config-loader-C4VXKl8f.mjs";
|
|
2
|
+
import { _ as errorUnexpected, m as errorRuntime } from "../cli-errors-BDCYR5ap.mjs";
|
|
3
|
+
import { _ as formatStyledHeader, c as resolveMigrationPaths, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions } from "../result-handler-oK_vA-Fn.mjs";
|
|
4
|
+
import { t as TerminalUI } from "../terminal-ui-C5k88MmW.mjs";
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
8
|
+
import { join, relative, resolve } from "pathe";
|
|
9
|
+
import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
|
|
10
|
+
import { findLatestMigration, reconstructGraph } from "@prisma-next/migration-tools/dag";
|
|
11
|
+
import { formatMigrationDirName, readMigrationsDir, writeMigrationPackage } from "@prisma-next/migration-tools/io";
|
|
12
|
+
import { MigrationToolsError, isAttested } from "@prisma-next/migration-tools/types";
|
|
13
|
+
import { scaffoldMigrationTs } from "@prisma-next/migration-tools/migration-ts";
|
|
14
|
+
|
|
15
|
+
//#region src/commands/migration-new.ts
|
|
16
|
+
/**
|
|
17
|
+
* `migration new` — scaffolds a migration package with a migration.ts file
|
|
18
|
+
* for manual authoring. The user writes operation descriptors and data
|
|
19
|
+
* transforms; `migration verify` resolves them to ops.json.
|
|
20
|
+
*/
|
|
21
|
+
async function executeMigrationNewCommand(options) {
|
|
22
|
+
const config = await loadConfig(options.config);
|
|
23
|
+
const { migrationsDir, migrationsRelative } = resolveMigrationPaths(options.config, config);
|
|
24
|
+
const contractPath = config.contract?.output ?? "contract.json";
|
|
25
|
+
const contractPathAbsolute = resolve(options.config ? resolve(options.config, "..") : process.cwd(), contractPath);
|
|
26
|
+
let contractJsonContent;
|
|
27
|
+
try {
|
|
28
|
+
contractJsonContent = readFileSync(contractPathAbsolute, "utf-8");
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (error instanceof Error && error.code === "ENOENT") return notOk(errorRuntime(`Contract file not found at ${contractPathAbsolute}`, {
|
|
31
|
+
why: `Contract file not found at ${contractPathAbsolute}`,
|
|
32
|
+
fix: "Run `prisma-next contract emit` first to generate the contract"
|
|
33
|
+
}));
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
let toContractJson;
|
|
37
|
+
try {
|
|
38
|
+
toContractJson = JSON.parse(contractJsonContent);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
return notOk(errorRuntime("Contract JSON is invalid", {
|
|
41
|
+
why: `Failed to parse ${contractPathAbsolute}: ${error instanceof Error ? error.message : String(error)}`,
|
|
42
|
+
fix: "Run `prisma-next contract emit` to regenerate the contract"
|
|
43
|
+
}));
|
|
44
|
+
}
|
|
45
|
+
const toStorageHash = toContractJson["storage"]?.["storageHash"];
|
|
46
|
+
if (!toStorageHash) return notOk(errorRuntime("Contract is missing storageHash", {
|
|
47
|
+
why: `Contract at ${contractPathAbsolute} has no storageHash`,
|
|
48
|
+
fix: "Run `prisma-next contract emit` to regenerate the contract"
|
|
49
|
+
}));
|
|
50
|
+
let fromContract = null;
|
|
51
|
+
let fromHash = EMPTY_CONTRACT_HASH;
|
|
52
|
+
try {
|
|
53
|
+
const attested = (await readMigrationsDir(migrationsDir)).filter(isAttested);
|
|
54
|
+
if (attested.length > 0) {
|
|
55
|
+
const graph = reconstructGraph(attested);
|
|
56
|
+
if (options.from) {
|
|
57
|
+
const match = attested.find((p) => p.manifest.to.startsWith(options.from));
|
|
58
|
+
if (!match) return notOk(errorRuntime("Starting contract not found", {
|
|
59
|
+
why: `No migration with to hash matching "${options.from}" exists in ${migrationsRelative}`,
|
|
60
|
+
fix: "Check that the --from hash matches a known migration target hash."
|
|
61
|
+
}));
|
|
62
|
+
fromHash = match.manifest.to;
|
|
63
|
+
fromContract = match.manifest.toContract;
|
|
64
|
+
} else {
|
|
65
|
+
const latestMigration = findLatestMigration(graph);
|
|
66
|
+
if (latestMigration) {
|
|
67
|
+
fromHash = latestMigration.to;
|
|
68
|
+
const leafPkg = attested.find((p) => p.manifest.migrationId === latestMigration.migrationId);
|
|
69
|
+
if (leafPkg) fromContract = leafPkg.manifest.toContract;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (MigrationToolsError.is(error)) return notOk(errorRuntime(error.message, {
|
|
75
|
+
why: error.why,
|
|
76
|
+
fix: error.fix,
|
|
77
|
+
meta: { code: error.code }
|
|
78
|
+
}));
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
if (fromHash === toStorageHash) return notOk(errorRuntime("No changes detected", {
|
|
82
|
+
why: "The from and to contract hashes are identical — there is nothing to migrate.",
|
|
83
|
+
fix: "Change the contract and run `prisma-next contract emit` before creating a new migration."
|
|
84
|
+
}));
|
|
85
|
+
const timestamp = /* @__PURE__ */ new Date();
|
|
86
|
+
const packageDir = join(migrationsDir, formatMigrationDirName(timestamp, options.name ?? "migration"));
|
|
87
|
+
const manifest = {
|
|
88
|
+
from: fromHash,
|
|
89
|
+
to: toStorageHash,
|
|
90
|
+
migrationId: null,
|
|
91
|
+
kind: "regular",
|
|
92
|
+
fromContract,
|
|
93
|
+
toContract: toContractJson,
|
|
94
|
+
hints: {
|
|
95
|
+
used: [],
|
|
96
|
+
applied: [],
|
|
97
|
+
plannerVersion: "1.0.0",
|
|
98
|
+
planningStrategy: "manual"
|
|
99
|
+
},
|
|
100
|
+
labels: [],
|
|
101
|
+
createdAt: timestamp.toISOString()
|
|
102
|
+
};
|
|
103
|
+
try {
|
|
104
|
+
await writeMigrationPackage(packageDir, manifest, []);
|
|
105
|
+
await scaffoldMigrationTs(packageDir);
|
|
106
|
+
return ok({
|
|
107
|
+
ok: true,
|
|
108
|
+
dir: relative(process.cwd(), packageDir),
|
|
109
|
+
from: fromHash,
|
|
110
|
+
to: toStorageHash,
|
|
111
|
+
summary: `Scaffolded migration at ${relative(process.cwd(), packageDir)}`
|
|
112
|
+
});
|
|
113
|
+
} catch (error) {
|
|
114
|
+
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Failed to scaffold migration: ${error instanceof Error ? error.message : String(error)}` }));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function createMigrationNewCommand() {
|
|
118
|
+
const command = new Command("new");
|
|
119
|
+
setCommandDescriptions(command, "Scaffold a new migration for manual authoring", "Creates a migration package with a migration.ts file for manual authoring.\nWrite operation descriptors and data transforms in migration.ts, then run\n`migration verify` to resolve and attest the package.");
|
|
120
|
+
setCommandExamples(command, ["prisma-next migration new --name split-name", "prisma-next migration new --name custom-fk --from sha256:abc..."]);
|
|
121
|
+
addGlobalOptions(command).option("--name <slug>", "Migration name (used in directory name)").option("--from <hash>", "Starting contract hash (default: latest migration target)").option("--config <path>", "Path to prisma-next.config.ts").action(async (options) => {
|
|
122
|
+
const flags = parseGlobalFlags(options);
|
|
123
|
+
const ui = new TerminalUI({
|
|
124
|
+
color: flags.color,
|
|
125
|
+
interactive: flags.interactive
|
|
126
|
+
});
|
|
127
|
+
if (!flags.json && !flags.quiet) {
|
|
128
|
+
const header = formatStyledHeader({
|
|
129
|
+
command: "migration new",
|
|
130
|
+
description: "Scaffold a new migration",
|
|
131
|
+
details: [],
|
|
132
|
+
flags
|
|
133
|
+
});
|
|
134
|
+
ui.stderr(header);
|
|
135
|
+
}
|
|
136
|
+
const exitCode = handleResult(await executeMigrationNewCommand(options), flags, ui, (value) => {
|
|
137
|
+
if (flags.json) ui.output(JSON.stringify(value, null, 2));
|
|
138
|
+
else if (!flags.quiet) {
|
|
139
|
+
ui.output(`\nScaffolded migration at ${value.dir}`);
|
|
140
|
+
ui.output(` from: ${value.from}`);
|
|
141
|
+
ui.output(` to: ${value.to}`);
|
|
142
|
+
ui.output(`\nEdit migration.ts, then run \`prisma-next migration verify --dir ${value.dir}\` to attest.`);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
process.exit(exitCode);
|
|
146
|
+
});
|
|
147
|
+
return command;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
//#endregion
|
|
151
|
+
export { createMigrationNewCommand };
|
|
152
|
+
//# sourceMappingURL=migration-new.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-new.mjs","names":["contractJsonContent: string","toContractJson: Contract","fromContract: Contract | null","fromHash: string","manifest: MigrationManifest"],"sources":["../../src/commands/migration-new.ts"],"sourcesContent":["/**\n * `migration new` — scaffolds a migration package with a migration.ts file\n * for manual authoring. The user writes operation descriptors and data\n * transforms; `migration verify` resolves them to ops.json.\n */\n\nimport { readFileSync } from 'node:fs';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { findLatestMigration, reconstructGraph } from '@prisma-next/migration-tools/dag';\nimport {\n formatMigrationDirName,\n readMigrationsDir,\n writeMigrationPackage,\n} from '@prisma-next/migration-tools/io';\nimport { scaffoldMigrationTs } from '@prisma-next/migration-tools/migration-ts';\nimport type { MigrationManifest } from '@prisma-next/migration-tools/types';\nimport { isAttested, MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { type CliStructuredError, errorRuntime, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationNewOptions extends CommonCommandOptions {\n readonly name?: string;\n readonly from?: string;\n readonly config?: string;\n}\n\ninterface MigrationNewResult {\n readonly ok: true;\n readonly dir: string;\n readonly from: string;\n readonly to: string;\n readonly summary: string;\n}\n\nasync function executeMigrationNewCommand(\n options: MigrationNewOptions,\n): Promise<Result<MigrationNewResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { migrationsDir, migrationsRelative } = resolveMigrationPaths(options.config, config);\n\n // Read the emitted contract (destination)\n const contractPath = config.contract?.output ?? 'contract.json';\n const contractPathAbsolute = resolve(\n options.config ? resolve(options.config, '..') : process.cwd(),\n contractPath,\n );\n\n let contractJsonContent: string;\n try {\n contractJsonContent = readFileSync(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorRuntime(`Contract file not found at ${contractPathAbsolute}`, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: 'Run `prisma-next contract emit` first to generate the contract',\n }),\n );\n }\n throw error;\n }\n\n let toContractJson: Contract;\n try {\n toContractJson = JSON.parse(contractJsonContent) as Contract;\n } catch (error) {\n return notOk(\n errorRuntime('Contract JSON is invalid', {\n why: `Failed to parse ${contractPathAbsolute}: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n const toStorageHash = (\n (toContractJson as unknown as Record<string, unknown>)['storage'] as\n | Record<string, unknown>\n | undefined\n )?.['storageHash'] as string | undefined;\n if (!toStorageHash) {\n return notOk(\n errorRuntime('Contract is missing storageHash', {\n why: `Contract at ${contractPathAbsolute} has no storageHash`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n // Determine \"from\" hash\n let fromContract: Contract | null = null;\n let fromHash: string = EMPTY_CONTRACT_HASH;\n\n try {\n const packages = await readMigrationsDir(migrationsDir);\n const attested = packages.filter(isAttested);\n\n if (attested.length > 0) {\n const graph = reconstructGraph(attested);\n\n if (options.from) {\n // Explicit --from: find the migration with matching to hash\n const match = attested.find((p) => p.manifest.to.startsWith(options.from!));\n if (!match) {\n return notOk(\n errorRuntime('Starting contract not found', {\n why: `No migration with to hash matching \"${options.from}\" exists in ${migrationsRelative}`,\n fix: 'Check that the --from hash matches a known migration target hash.',\n }),\n );\n }\n fromHash = match.manifest.to;\n fromContract = match.manifest.toContract;\n } else {\n const latestMigration = findLatestMigration(graph);\n if (latestMigration) {\n fromHash = latestMigration.to;\n const leafPkg = attested.find(\n (p) => p.manifest.migrationId === latestMigration.migrationId,\n );\n if (leafPkg) {\n fromContract = leafPkg.manifest.toContract;\n }\n }\n }\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code },\n }),\n );\n }\n throw error;\n }\n\n // Check for no-op\n if (fromHash === toStorageHash) {\n return notOk(\n errorRuntime('No changes detected', {\n why: 'The from and to contract hashes are identical — there is nothing to migrate.',\n fix: 'Change the contract and run `prisma-next contract emit` before creating a new migration.',\n }),\n );\n }\n\n // Build manifest and write package\n const timestamp = new Date();\n const slug = options.name ?? 'migration';\n const dirName = formatMigrationDirName(timestamp, slug);\n const packageDir = join(migrationsDir, dirName);\n\n const manifest: MigrationManifest = {\n from: fromHash,\n to: toStorageHash,\n migrationId: null,\n kind: 'regular',\n fromContract,\n toContract: toContractJson,\n hints: {\n used: [],\n applied: [],\n plannerVersion: '1.0.0',\n planningStrategy: 'manual',\n },\n labels: [],\n createdAt: timestamp.toISOString(),\n };\n\n try {\n // Write package with empty ops (draft)\n await writeMigrationPackage(packageDir, manifest, []);\n\n // Scaffold migration.ts\n await scaffoldMigrationTs(packageDir);\n\n return ok({\n ok: true as const,\n dir: relative(process.cwd(), packageDir),\n from: fromHash,\n to: toStorageHash,\n summary: `Scaffolded migration at ${relative(process.cwd(), packageDir)}`,\n });\n } catch (error) {\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to scaffold migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nexport function createMigrationNewCommand(): Command {\n const command = new Command('new');\n setCommandDescriptions(\n command,\n 'Scaffold a new migration for manual authoring',\n 'Creates a migration package with a migration.ts file for manual authoring.\\n' +\n 'Write operation descriptors and data transforms in migration.ts, then run\\n' +\n '`migration verify` to resolve and attest the package.',\n );\n setCommandExamples(command, [\n 'prisma-next migration new --name split-name',\n 'prisma-next migration new --name custom-fk --from sha256:abc...',\n ]);\n addGlobalOptions(command)\n .option('--name <slug>', 'Migration name (used in directory name)')\n .option('--from <hash>', 'Starting contract hash (default: latest migration target)')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: MigrationNewOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n if (!flags.json && !flags.quiet) {\n const header = formatStyledHeader({\n command: 'migration new',\n description: 'Scaffold a new migration',\n details: [],\n flags,\n });\n ui.stderr(header);\n }\n\n const result = await executeMigrationNewCommand(options);\n\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value, null, 2));\n } else if (!flags.quiet) {\n ui.output(`\\nScaffolded migration at ${value.dir}`);\n ui.output(` from: ${value.from}`);\n ui.output(` to: ${value.to}`);\n ui.output(\n `\\nEdit migration.ts, then run \\`prisma-next migration verify --dir ${value.dir}\\` to attest.`,\n );\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAe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D,MAAM,UAAU,IAAI,QAAQ,MAAM;AAClC,wBACE,SACA,iDACA,+MAGD;AACD,oBAAmB,SAAS,CAC1B,+CACA,kEACD,CAAC;AACF,kBAAiB,QAAQ,CACtB,OAAO,iBAAiB,0CAA0C,CAClE,OAAO,iBAAiB,4DAA4D,CACpF,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,OAAO,YAAiC;EAC9C,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,KAAK,IAAI,WAAW;GAAE,OAAO,MAAM;GAAO,aAAa,MAAM;GAAa,CAAC;AAEjF,MAAI,CAAC,MAAM,QAAQ,CAAC,MAAM,OAAO;GAC/B,MAAM,SAAS,mBAAmB;IAChC,SAAS;IACT,aAAa;IACb,SAAS,EAAE;IACX;IACD,CAAC;AACF,MAAG,OAAO,OAAO;;EAKnB,MAAM,WAAW,aAFF,MAAM,2BAA2B,QAAQ,EAElB,OAAO,KAAK,UAAU;AAC1D,OAAI,MAAM,KACR,IAAG,OAAO,KAAK,UAAU,OAAO,MAAM,EAAE,CAAC;YAChC,CAAC,MAAM,OAAO;AACvB,OAAG,OAAO,6BAA6B,MAAM,MAAM;AACnD,OAAG,OAAO,WAAW,MAAM,OAAO;AAClC,OAAG,OAAO,WAAW,MAAM,KAAK;AAChC,OAAG,OACD,sEAAsE,MAAM,IAAI,eACjF;;IAEH;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import { Result } from "@prisma-next/utils/result";
|
|
3
|
+
|
|
4
|
+
//#region src/commands/migration-plan.d.ts
|
|
5
|
+
interface MigrationPlanResult {
|
|
6
|
+
readonly ok: boolean;
|
|
7
|
+
readonly noOp: boolean;
|
|
8
|
+
readonly from: string;
|
|
9
|
+
readonly to: string;
|
|
10
|
+
readonly migrationId?: string;
|
|
11
|
+
readonly dir?: string;
|
|
12
|
+
readonly operations: readonly {
|
|
13
|
+
readonly id: string;
|
|
14
|
+
readonly label: string;
|
|
15
|
+
readonly operationClass: string;
|
|
16
|
+
}[];
|
|
17
|
+
readonly sql?: readonly string[];
|
|
18
|
+
readonly summary: string;
|
|
19
|
+
readonly timings: {
|
|
20
|
+
readonly total: number;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
declare function createMigrationPlanCommand(): Command;
|
|
24
|
+
type PrefixResolutionFailure = {
|
|
25
|
+
reason: 'ambiguous';
|
|
26
|
+
count: number;
|
|
27
|
+
} | {
|
|
28
|
+
reason: 'not-found';
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Resolve a migration bundle by exact hash or prefix match.
|
|
32
|
+
*
|
|
33
|
+
* Tries exact match first, then prefix match (auto-prepending `sha256:` when
|
|
34
|
+
* the needle omits the scheme). Returns the matched bundle on success, or a
|
|
35
|
+
* discriminated failure indicating whether the prefix was ambiguous or simply
|
|
36
|
+
* not found.
|
|
37
|
+
*
|
|
38
|
+
* @internal Exported for testing only.
|
|
39
|
+
*/
|
|
40
|
+
declare function resolveBundleByPrefix<T extends {
|
|
41
|
+
manifest: {
|
|
42
|
+
to: string;
|
|
43
|
+
};
|
|
44
|
+
}>(bundles: readonly T[], needle: string): Result<T, PrefixResolutionFailure>;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { MigrationPlanResult, PrefixResolutionFailure, createMigrationPlanCommand, resolveBundleByPrefix };
|
|
47
|
+
//# sourceMappingURL=migration-plan.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-plan.d.mts","names":[],"sources":["../../src/commands/migration-plan.ts"],"sourcesContent":[],"mappings":";;;;UAqDiB,mBAAA;;EAAA,SAAA,IAAA,EAAA,OAAmB;EA0UpB,SAAA,IAAA,EAAA,MAAA;EA4GJ,SAAA,EAAA,EAAA,MAAA;EAcI,SAAA,WAAA,CAAA,EAAA,MAAqB;EACjB,SAAA,GAAA,CAAA,EAAA,MAAA;EAEV,SAAA,UAAA,EAAA,SAAA;IAAG,SAAA,EAAA,EAAA,MAAA;IAAV,SAAA,KAAA,EAAA,MAAA;IAAM,SAAA,cAAA,EAAA,MAAA;;;;;;;;iBA7HO,0BAAA,CAAA,GAA8B;KA4GlC,uBAAA;;;;;;;;;;;;;;;;iBAcI;;;;qBACI,sBAEjB,OAAO,GAAG"}
|