prisma-next 0.6.0-dev.3 → 0.6.0-dev.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +4 -4
- package/dist/{client-qVH-rEgd.mjs → client-BCnP7cHo.mjs} +9 -119
- package/dist/client-BCnP7cHo.mjs.map +1 -0
- package/dist/commands/contract-infer.mjs +1 -1
- package/dist/commands/db-init.mjs +3 -3
- package/dist/commands/db-schema.mjs +1 -1
- package/dist/commands/db-sign.mjs +1 -1
- package/dist/commands/db-update.mjs +3 -3
- package/dist/commands/db-verify.mjs +1 -1
- package/dist/commands/migration-apply.d.mts +1 -1
- package/dist/commands/migration-apply.mjs +2 -2
- package/dist/commands/migration-plan.d.mts.map +1 -1
- package/dist/commands/migration-plan.mjs +1 -1
- package/dist/commands/migration-show.d.mts +55 -7
- package/dist/commands/migration-show.d.mts.map +1 -1
- package/dist/commands/migration-show.mjs +153 -46
- package/dist/commands/migration-show.mjs.map +1 -1
- package/dist/commands/migration-status.d.mts.map +1 -1
- package/dist/commands/migration-status.mjs +1 -1
- package/dist/{contract-infer-BK9YFGEG.mjs → contract-infer-ByxhPjpW.mjs} +2 -2
- package/dist/{contract-infer-BK9YFGEG.mjs.map → contract-infer-ByxhPjpW.mjs.map} +1 -1
- package/dist/contract-space-aggregate-loader-BrwKK6Q6.mjs +160 -0
- package/dist/contract-space-aggregate-loader-BrwKK6Q6.mjs.map +1 -0
- package/dist/{db-verify-C0y1PCO2.mjs → db-verify-Czm5T-J4.mjs} +2 -2
- package/dist/{db-verify-C0y1PCO2.mjs.map → db-verify-Czm5T-J4.mjs.map} +1 -1
- package/dist/exports/control-api.d.mts +1 -1
- package/dist/exports/control-api.mjs +1 -1
- package/dist/{inspect-live-schema-CWYxGKlb.mjs → inspect-live-schema-DxdBd4Er.mjs} +2 -2
- package/dist/{inspect-live-schema-CWYxGKlb.mjs.map → inspect-live-schema-DxdBd4Er.mjs.map} +1 -1
- package/dist/{migration-command-scaffold-B5dORFEv.mjs → migration-command-scaffold-BdV8JYXV.mjs} +2 -2
- package/dist/{migration-command-scaffold-B5dORFEv.mjs.map → migration-command-scaffold-BdV8JYXV.mjs.map} +1 -1
- package/dist/{migration-plan-C6lVaHsO.mjs → migration-plan-mRu5K81L.mjs} +89 -149
- package/dist/migration-plan-mRu5K81L.mjs.map +1 -0
- package/dist/{migration-status-CZ-D5k7k.mjs → migration-status-By9G5p2H.mjs} +6 -8
- package/dist/{migration-status-CZ-D5k7k.mjs.map → migration-status-By9G5p2H.mjs.map} +1 -1
- package/dist/{migrations-D_UJnpuW.mjs → migrations-CTsyBXCA.mjs} +42 -29
- package/dist/migrations-CTsyBXCA.mjs.map +1 -0
- package/dist/{types-D7x-IFLO.d.mts → types-LItU7E4l.d.mts} +7 -9
- package/dist/{types-D7x-IFLO.d.mts.map → types-LItU7E4l.d.mts.map} +1 -1
- package/package.json +10 -10
- package/dist/client-qVH-rEgd.mjs.map +0 -1
- package/dist/extension-pack-inputs-C7xgE-vv.mjs +0 -74
- package/dist/extension-pack-inputs-C7xgE-vv.mjs.map +0 -1
- package/dist/migration-plan-C6lVaHsO.mjs.map +0 -1
- package/dist/migrations-D_UJnpuW.mjs.map +0 -1
|
@@ -4,174 +4,104 @@ import { t as assertFrameworkComponentsCompatible } from "./framework-components
|
|
|
4
4
|
import { a as loadMigrationPackages, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, g as parseGlobalFlags, i as getTargetMigrations, l as resolveMigrationPaths, t as addGlobalOptions, y as formatStyledHeader } from "./command-helpers-BeZHkxV8.mjs";
|
|
5
5
|
import { t as TerminalUI } from "./terminal-ui-C_hFNbAn.mjs";
|
|
6
6
|
import { t as handleResult } from "./result-handler-rmPVKIP2.mjs";
|
|
7
|
-
import {
|
|
7
|
+
import { n as toExtensionInputs, t as buildContractSpaceAggregate } from "./contract-space-aggregate-loader-BrwKK6Q6.mjs";
|
|
8
8
|
import { Command } from "commander";
|
|
9
9
|
import { getEmittedArtifactPaths } from "@prisma-next/emitter";
|
|
10
10
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
11
11
|
import { join, relative } from "pathe";
|
|
12
12
|
import { readFile } from "node:fs/promises";
|
|
13
|
-
import {
|
|
13
|
+
import { createControlStack, hasOperationPreview } from "@prisma-next/framework-components/control";
|
|
14
14
|
import { copyFilesWithRename, formatMigrationDirName, materialiseExtensionMigrationPackageIfMissing, writeMigrationPackage } from "@prisma-next/migration-tools/io";
|
|
15
15
|
import { findLatestMigration } from "@prisma-next/migration-tools/migration-graph";
|
|
16
|
-
import {
|
|
16
|
+
import { emitContractSpaceArtefacts, planAllSpaces, readContractSpaceHeadRef, spaceMigrationDirectory } from "@prisma-next/migration-tools/spaces";
|
|
17
17
|
import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
|
|
18
18
|
import { computeMigrationHash } from "@prisma-next/migration-tools/hash";
|
|
19
19
|
import { writeMigrationTs } from "@prisma-next/migration-tools/migration-ts";
|
|
20
20
|
import { deriveProvidedInvariants } from "@prisma-next/migration-tools/invariants";
|
|
21
|
-
//#region src/utils/contract-space-
|
|
21
|
+
//#region src/utils/contract-space-seed-phase.ts
|
|
22
22
|
/**
|
|
23
|
-
*
|
|
24
|
-
* under `migrations/<spaceId>/<dirName>/` for every package that does
|
|
25
|
-
* not yet exist there.
|
|
23
|
+
* Phase-1 of the two-phase `migration plan` pipeline (sub-spec § 4).
|
|
26
24
|
*
|
|
27
|
-
*
|
|
28
|
-
* spaces is a no-op that just returns the descriptor's `migrations`
|
|
29
|
-
* verbatim; the value `planAllSpaces` brings to this consumer site is
|
|
30
|
-
* **deterministic ordering** (alphabetical by spaceId) and
|
|
31
|
-
* **duplicate-spaceId detection**. The actual write is performed via
|
|
32
|
-
* `materialiseMigrationPackage` per package.
|
|
25
|
+
* For every extension that exposes a `contractSpace`:
|
|
33
26
|
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
27
|
+
* 1. Read the on-disk head ref (returns `null` on first emit).
|
|
28
|
+
* 2. Re-emit `contract.json` / `contract.d.ts` / `refs/head.json`
|
|
29
|
+
* unconditionally via {@link emitContractSpaceArtefacts}. The
|
|
30
|
+
* framework owns these files; re-emit is the contract.
|
|
31
|
+
* 3. Materialise any descriptor-shipped migration packages not yet on
|
|
32
|
+
* disk via {@link materialiseExtensionMigrationPackageIfMissing}.
|
|
33
|
+
* Existing packages are left untouched (by-existence skip).
|
|
38
34
|
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
35
|
+
* The return value lets the caller render a per-space status line and
|
|
36
|
+
* lets the phase-2 aggregate loader run on a now-consistent disk state
|
|
37
|
+
* (every loaded extension is guaranteed to have its head ref pinned
|
|
38
|
+
* to the descriptor's hash and to ship every package the descriptor
|
|
39
|
+
* declares).
|
|
40
|
+
*
|
|
41
|
+
* Output ordering is deterministic and alphabetical by spaceId (via
|
|
42
|
+
* {@link planAllSpaces}, which also detects duplicate spaceIds). This
|
|
43
|
+
* matches the canonical sort order used by every other aggregate
|
|
44
|
+
* surface (`migration apply`, `migration status`, the runner).
|
|
44
45
|
*/
|
|
45
|
-
async function
|
|
46
|
+
async function runContractSpaceSeedPhase(inputs) {
|
|
46
47
|
const planned = planAllSpaces(inputs.extensionPacks.filter((pack) => pack.contractSpace !== void 0).map((pack) => ({
|
|
47
48
|
spaceId: pack.id,
|
|
48
49
|
priorContract: null,
|
|
49
50
|
newContract: pack.contractSpace.contractJson,
|
|
50
|
-
|
|
51
|
-
})), (input) => input.
|
|
52
|
-
const
|
|
53
|
-
const
|
|
51
|
+
__pack: pack.contractSpace
|
|
52
|
+
})), (input) => input.__pack.migrations);
|
|
53
|
+
const descriptorBySpace = /* @__PURE__ */ new Map();
|
|
54
|
+
for (const pack of inputs.extensionPacks) if (pack.contractSpace !== void 0) descriptorBySpace.set(pack.id, pack.contractSpace);
|
|
55
|
+
const seeded = [];
|
|
54
56
|
for (const space of planned) {
|
|
57
|
+
const descriptor = descriptorBySpace.get(space.spaceId);
|
|
58
|
+
if (descriptor === void 0) continue;
|
|
59
|
+
const priorHash = (await readContractSpaceHeadRef(inputs.migrationsDir, space.spaceId))?.hash ?? null;
|
|
60
|
+
await emitContractSpaceArtefacts(inputs.migrationsDir, space.spaceId, {
|
|
61
|
+
contract: descriptor.contractJson,
|
|
62
|
+
contractDts: buildPlaceholderContractDts(space.spaceId),
|
|
63
|
+
headRef: {
|
|
64
|
+
hash: descriptor.headRef.hash,
|
|
65
|
+
invariants: descriptor.headRef.invariants
|
|
66
|
+
}
|
|
67
|
+
});
|
|
55
68
|
const spaceDir = spaceMigrationDirectory(inputs.migrationsDir, space.spaceId);
|
|
69
|
+
const newMigrationDirs = [];
|
|
56
70
|
for (const pkg of space.migrationPackages) {
|
|
57
71
|
const { written } = await materialiseExtensionMigrationPackageIfMissing(spaceDir, pkg);
|
|
58
|
-
if (written)
|
|
59
|
-
spaceId: space.spaceId,
|
|
60
|
-
dirName: pkg.dirName
|
|
61
|
-
});
|
|
62
|
-
else skipped.push({
|
|
63
|
-
spaceId: space.spaceId,
|
|
64
|
-
dirName: pkg.dirName
|
|
65
|
-
});
|
|
72
|
+
if (written) newMigrationDirs.push(pkg.dirName);
|
|
66
73
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
//#region src/utils/contract-space-migrate-pass.ts
|
|
75
|
-
/**
|
|
76
|
-
* Run drift detection + on-disk artefact emission for every loaded
|
|
77
|
-
* extension space at `migrate` time.
|
|
78
|
-
*
|
|
79
|
-
* Per sub-spec § 3:
|
|
80
|
-
*
|
|
81
|
-
* - For each declared extension that exposes a `contractSpace`:
|
|
82
|
-
* - Read the on-disk head hash from `migrations/<spaceId>/refs/head.json`
|
|
83
|
-
* (returns `null` on first emit).
|
|
84
|
-
* - Compare against the descriptor's `headRef.hash` via
|
|
85
|
-
* `detectSpaceContractDrift`. The `kind` discriminant decides whether
|
|
86
|
-
* the user sees a warning (`drift`), a no-op silent emit (`firstEmit`,
|
|
87
|
-
* `noDrift`), or nothing at all.
|
|
88
|
-
* - Always re-emit the on-disk artefacts (`contract.json`, `contract.d.ts`,
|
|
89
|
-
* `refs/head.json`). The framework owns these files and the helper is
|
|
90
|
-
* idempotent.
|
|
91
|
-
*
|
|
92
|
-
* Drift warnings are returned to the caller for formatting (TerminalUI,
|
|
93
|
-
* structured-output envelope, etc.) — the helper does not print directly,
|
|
94
|
-
* keeping it framework-neutral and unit-testable.
|
|
95
|
-
*
|
|
96
|
-
* Extension migration packages (the descriptor's pre-canned `migrations`
|
|
97
|
-
* array → `migrations/<spaceId>/<dirName>/`) are intentionally not
|
|
98
|
-
* materialised here — that interaction will be wired in a follow-on round
|
|
99
|
-
* once the runner-side single-tx slice (sub-spec § 6) is in place.
|
|
100
|
-
* On-disk artefacts are sufficient to lock the drift-warning behaviour
|
|
101
|
-
* and the always-on re-emit AC for R2.
|
|
102
|
-
*
|
|
103
|
-
* @see specs/framework-mechanism.spec.md § 3 — Drift detection (T1.9).
|
|
104
|
-
*/
|
|
105
|
-
async function runContractSpaceMigratePass(inputs) {
|
|
106
|
-
const drifts = [];
|
|
107
|
-
const emittedSpaceIds = [];
|
|
108
|
-
for (const pack of inputs.extensionPacks) {
|
|
109
|
-
if (pack.contractSpace === void 0) continue;
|
|
110
|
-
const { contractJson, headRef } = pack.contractSpace;
|
|
111
|
-
const onDiskHeadRef = await readContractSpaceHeadRef(inputs.migrationsDir, pack.id);
|
|
112
|
-
const drift = detectSpaceContractDrift(pack.id, {
|
|
113
|
-
descriptorHash: headRef.hash,
|
|
114
|
-
priorHeadHash: onDiskHeadRef?.hash ?? null
|
|
74
|
+
const action = priorHash !== descriptor.headRef.hash || newMigrationDirs.length > 0 ? "updated" : "unchanged";
|
|
75
|
+
seeded.push({
|
|
76
|
+
spaceId: space.spaceId,
|
|
77
|
+
action,
|
|
78
|
+
priorHash,
|
|
79
|
+
newHash: descriptor.headRef.hash,
|
|
80
|
+
newMigrationDirs
|
|
115
81
|
});
|
|
116
|
-
drifts.push(drift);
|
|
117
|
-
await emitContractSpaceArtefacts(inputs.migrationsDir, pack.id, {
|
|
118
|
-
contract: contractJson,
|
|
119
|
-
contractDts: buildPlaceholderContractDts(pack.id),
|
|
120
|
-
headRef: {
|
|
121
|
-
hash: headRef.hash,
|
|
122
|
-
invariants: headRef.invariants
|
|
123
|
-
}
|
|
124
|
-
});
|
|
125
|
-
emittedSpaceIds.push(pack.id);
|
|
126
82
|
}
|
|
127
|
-
return {
|
|
128
|
-
drifts,
|
|
129
|
-
emittedSpaceIds
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Format the user-facing drift warning for a single space. Callers
|
|
134
|
-
* funnel this through their preferred output channel (TerminalUI line,
|
|
135
|
-
* structured-output envelope `warnings[]`, etc.).
|
|
136
|
-
*
|
|
137
|
-
* Locks AM7 — drift warning surfaces the extension name and the diff
|
|
138
|
-
* direction (descriptor → on-disk head).
|
|
139
|
-
*/
|
|
140
|
-
function formatContractSpaceDriftWarning(drift) {
|
|
141
|
-
if (drift.kind !== "drift") throw new Error(`formatContractSpaceDriftWarning called with non-drift result: ${drift.kind}`);
|
|
142
|
-
return `Contract-space drift detected for "${drift.spaceId}": descriptor hash ${drift.descriptorHash} differs from on-disk head hash ${drift.priorHeadHash ?? "<none>"}. The on-disk artefacts under migrations/${drift.spaceId}/ will be refreshed to match the descriptor.`;
|
|
83
|
+
return { seeded };
|
|
143
84
|
}
|
|
144
85
|
/**
|
|
145
86
|
* Placeholder `.d.ts` content for an extension space's on-disk mirror.
|
|
146
87
|
*
|
|
147
|
-
* Rendering a fully-typed `.d.ts` for an extension contract requires
|
|
148
|
-
* SQL-family renderer with the codec / typemap registry threaded
|
|
149
|
-
* through; that integration
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
* spec gap closing alongside the typed renderer is **AC2 / AC14**
|
|
154
|
-
* (byte-equivalence of per-space artefacts under `migrate`):
|
|
155
|
-
* a placeholder cannot be byte-equal to a fully-rendered `.d.ts` from
|
|
156
|
-
* the same descriptor, so AC2 / AC14 are PARTIAL today and become
|
|
157
|
-
* fully-PASS once OQ3 closes.
|
|
158
|
-
*
|
|
159
|
-
* Scheduled to close in **M3** (cipherstash editor tooling) — that's
|
|
160
|
-
* the milestone where the typed renderer gets its first real
|
|
161
|
-
* extension-space consumer and the byte-equivalence guarantee is
|
|
162
|
-
* practically required.
|
|
88
|
+
* Rendering a fully-typed `.d.ts` for an extension contract requires
|
|
89
|
+
* the SQL-family renderer with the codec / typemap registry threaded
|
|
90
|
+
* through; until that integration ships, the on-disk `.d.ts` is a
|
|
91
|
+
* stub `export {};` module that documents how consumers should
|
|
92
|
+
* validate the sibling `contract.json`. The stub typechecks on its
|
|
93
|
+
* own and does not need any TypeScript suppressions.
|
|
163
94
|
*/
|
|
164
95
|
function buildPlaceholderContractDts(spaceId) {
|
|
165
96
|
return [
|
|
166
|
-
"// @ts-nocheck",
|
|
167
97
|
"/**",
|
|
168
98
|
` * Placeholder \`.d.ts\` for extension space "${spaceId}".`,
|
|
169
99
|
" *",
|
|
170
|
-
" * The framework re-emits this file on every `
|
|
171
|
-
" * `contract.json` and `refs/head.json`. A typed `.d.ts`
|
|
172
|
-
" * pass for extension contracts is tracked
|
|
173
|
-
" *
|
|
174
|
-
" *
|
|
100
|
+
" * The framework re-emits this file on every `migration plan` run",
|
|
101
|
+
" * alongside `contract.json` and `refs/head.json`. A typed `.d.ts`",
|
|
102
|
+
" * rendering pass for extension contracts is tracked separately;",
|
|
103
|
+
" * until that ships, consumers should import `contract.json`",
|
|
104
|
+
" * directly with `validateContract<…>(…)`.",
|
|
175
105
|
" */",
|
|
176
106
|
"export {};",
|
|
177
107
|
""
|
|
@@ -271,31 +201,43 @@ async function executeMigrationPlanCommand(options, flags, ui, startTime) {
|
|
|
271
201
|
const message = error instanceof Error ? error.message : String(error);
|
|
272
202
|
return notOk(errorUnexpected(message, { why: `Unexpected error while loading migrations: ${message}` }));
|
|
273
203
|
}
|
|
274
|
-
const
|
|
275
|
-
const migratePass = await runContractSpaceMigratePass({
|
|
204
|
+
const seedResult = await runContractSpaceSeedPhase({
|
|
276
205
|
migrationsDir,
|
|
277
|
-
extensionPacks:
|
|
206
|
+
extensionPacks: toExtensionInputs(config.extensionPacks ?? [])
|
|
278
207
|
});
|
|
279
208
|
if (!flags.json && !flags.quiet) {
|
|
280
|
-
for (const
|
|
209
|
+
for (const record of seedResult.seeded) if (record.action === "updated") {
|
|
210
|
+
const pkgSuffix = record.newMigrationDirs.length > 0 ? `; ${record.newMigrationDirs.length} new migration package(s) materialised` : "";
|
|
211
|
+
ui.step(`Updated ${record.spaceId} to ${record.newHash}${pkgSuffix}`);
|
|
212
|
+
}
|
|
281
213
|
}
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
});
|
|
286
|
-
if (!flags.json && !flags.quiet) for (const entry of extensionMigrationsResult.emitted) ui.step(`Emitted ${entry.spaceId}/${entry.dirName}`);
|
|
214
|
+
const emittedExtensionDirs = seedResult.seeded.flatMap((r) => r.newMigrationDirs.map((dirName) => ({
|
|
215
|
+
spaceId: r.spaceId,
|
|
216
|
+
dirName
|
|
217
|
+
})));
|
|
287
218
|
if (fromHash === toStorageHash) return ok({
|
|
288
219
|
ok: true,
|
|
289
220
|
noOp: true,
|
|
290
221
|
from: fromHash,
|
|
291
222
|
to: toStorageHash,
|
|
292
223
|
operations: [],
|
|
293
|
-
emittedExtensionDirs
|
|
224
|
+
emittedExtensionDirs,
|
|
294
225
|
summary: "No changes detected between contracts",
|
|
295
226
|
timings: { total: Date.now() - startTime }
|
|
296
227
|
});
|
|
297
228
|
const migrations = getTargetMigrations(config.target);
|
|
298
229
|
if (!migrations) return notOk(errorTargetMigrationNotSupported({ why: `Target "${config.target.id}" does not support migrations` }));
|
|
230
|
+
const stack = createControlStack(config);
|
|
231
|
+
const familyInstance = config.family.create(stack);
|
|
232
|
+
const aggregateResult = await buildContractSpaceAggregate({
|
|
233
|
+
targetId: config.target.targetId,
|
|
234
|
+
migrationsDir,
|
|
235
|
+
appContract: toContractJson,
|
|
236
|
+
extensionPacks: config.extensionPacks ?? [],
|
|
237
|
+
validateContract: (json) => familyInstance.validateContract(json)
|
|
238
|
+
});
|
|
239
|
+
if (!aggregateResult.ok) return notOk(aggregateResult.failure);
|
|
240
|
+
const aggregate = aggregateResult.value;
|
|
299
241
|
const frameworkComponents = assertFrameworkComponentsCompatible(config.family.familyId, config.target.targetId, [
|
|
300
242
|
config.target,
|
|
301
243
|
config.adapter,
|
|
@@ -317,12 +259,10 @@ async function executeMigrationPlanCommand(options, flags, ui, startTime) {
|
|
|
317
259
|
createdAt: timestamp.toISOString()
|
|
318
260
|
};
|
|
319
261
|
try {
|
|
320
|
-
const stack = createControlStack(config);
|
|
321
|
-
const familyInstance = config.family.create(stack);
|
|
322
262
|
const planner = migrations.createPlanner(familyInstance);
|
|
323
263
|
const fromSchema = migrations.contractToSchema(fromContract, frameworkComponents);
|
|
324
264
|
const plannerResult = planner.plan({
|
|
325
|
-
contract:
|
|
265
|
+
contract: aggregate.app.contract,
|
|
326
266
|
schema: fromSchema,
|
|
327
267
|
policy: { allowedOperationClasses: [
|
|
328
268
|
"additive",
|
|
@@ -332,7 +272,7 @@ async function executeMigrationPlanCommand(options, flags, ui, startTime) {
|
|
|
332
272
|
] },
|
|
333
273
|
fromContract,
|
|
334
274
|
frameworkComponents,
|
|
335
|
-
spaceId:
|
|
275
|
+
spaceId: aggregate.app.spaceId
|
|
336
276
|
});
|
|
337
277
|
if (plannerResult.kind === "failure") return notOk(errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts }));
|
|
338
278
|
let plannedOps = [];
|
|
@@ -383,7 +323,7 @@ async function executeMigrationPlanCommand(options, flags, ui, startTime) {
|
|
|
383
323
|
to: toStorageHash,
|
|
384
324
|
dir: relative(process.cwd(), packageDir),
|
|
385
325
|
operations: [],
|
|
386
|
-
emittedExtensionDirs
|
|
326
|
+
emittedExtensionDirs,
|
|
387
327
|
pendingPlaceholders: true,
|
|
388
328
|
summary: "Planned migration with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit",
|
|
389
329
|
timings: { total: Date.now() - startTime }
|
|
@@ -400,9 +340,9 @@ async function executeMigrationPlanCommand(options, flags, ui, startTime) {
|
|
|
400
340
|
label: op.label,
|
|
401
341
|
operationClass: op.operationClass
|
|
402
342
|
})),
|
|
403
|
-
emittedExtensionDirs
|
|
343
|
+
emittedExtensionDirs,
|
|
404
344
|
...preview !== void 0 ? { preview } : {},
|
|
405
|
-
summary: buildPlanSummary(plannedOps.length,
|
|
345
|
+
summary: buildPlanSummary(plannedOps.length, emittedExtensionDirs.length),
|
|
406
346
|
timings: { total: Date.now() - startTime }
|
|
407
347
|
});
|
|
408
348
|
} catch (error) {
|
|
@@ -551,4 +491,4 @@ function resolveBundleByPrefix(bundles, needle) {
|
|
|
551
491
|
//#endregion
|
|
552
492
|
export { formatMigrationPlanOutput as n, resolveBundleByPrefix as r, createMigrationPlanCommand as t };
|
|
553
493
|
|
|
554
|
-
//# sourceMappingURL=migration-plan-
|
|
494
|
+
//# sourceMappingURL=migration-plan-mRu5K81L.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-plan-mRu5K81L.mjs","names":[],"sources":["../src/utils/contract-space-seed-phase.ts","../src/commands/migration-plan.ts"],"sourcesContent":["import { materialiseExtensionMigrationPackageIfMissing } from '@prisma-next/migration-tools/io';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport type { MigrationOps } from '@prisma-next/migration-tools/package';\nimport {\n emitContractSpaceArtefacts,\n planAllSpaces,\n readContractSpaceHeadRef,\n type SpacePlanOutput,\n spaceMigrationDirectory,\n} from '@prisma-next/migration-tools/spaces';\n\n/**\n * In-memory authored migration package shipped by an extension descriptor.\n * Mirrors `MigrationPackage` from `@prisma-next/migration-tools/io` (the\n * on-disk shape minus `dirPath`); redeclared structurally here so the\n * CLI helper does not couple to any family's `ExtensionMigrationPackage`\n * type — any family that ships pre-built migration packages can pass\n * them through unchanged.\n */\nexport interface DescriptorMigrationPackage {\n readonly dirName: string;\n readonly metadata: MigrationMetadata;\n readonly ops: MigrationOps;\n}\n\n/**\n * Minimal descriptor view consumed by the seed phase. Mirrors the shape\n * the SQL family ships on each declared extension entry; only the fields\n * the seed phase needs are surfaced.\n */\nexport interface SeedPhaseExtensionInput {\n readonly id: string;\n readonly contractSpace?: {\n readonly contractJson: unknown;\n readonly headRef: { readonly hash: string; readonly invariants: readonly string[] };\n readonly migrations: readonly DescriptorMigrationPackage[];\n };\n}\n\nexport interface ContractSpaceSeedPhaseInputs {\n readonly migrationsDir: string;\n readonly extensionPacks: ReadonlyArray<SeedPhaseExtensionInput>;\n}\n\n/**\n * One per-space record describing what the seed phase did for an\n * extension contract space. Surfaced verbatim by the caller (typically\n * `migration plan`) so users see a single line per touched extension.\n *\n * - `action: 'updated'` — either the on-disk head pointer changed, or\n * one or more new descriptor-shipped migration packages were\n * materialised into `migrations/<spaceId>/<dirName>/`.\n * - `action: 'unchanged'` — the on-disk head already matched the\n * descriptor and no new migration packages needed to be written.\n *\n * Either way, the artefacts (`contract.json`, `contract.d.ts`,\n * `refs/head.json`) are re-emitted: the framework owns those files and\n * makes the re-emit observably idempotent at the byte level.\n */\nexport interface ContractSpaceSeedPhaseRecord {\n readonly spaceId: string;\n readonly action: 'updated' | 'unchanged';\n readonly priorHash: string | null;\n readonly newHash: string;\n readonly newMigrationDirs: readonly string[];\n}\n\nexport interface ContractSpaceSeedPhaseResult {\n readonly seeded: readonly ContractSpaceSeedPhaseRecord[];\n}\n\n/**\n * Phase-1 of the two-phase `migration plan` pipeline (sub-spec § 4).\n *\n * For every extension that exposes a `contractSpace`:\n *\n * 1. Read the on-disk head ref (returns `null` on first emit).\n * 2. Re-emit `contract.json` / `contract.d.ts` / `refs/head.json`\n * unconditionally via {@link emitContractSpaceArtefacts}. The\n * framework owns these files; re-emit is the contract.\n * 3. Materialise any descriptor-shipped migration packages not yet on\n * disk via {@link materialiseExtensionMigrationPackageIfMissing}.\n * Existing packages are left untouched (by-existence skip).\n *\n * The return value lets the caller render a per-space status line and\n * lets the phase-2 aggregate loader run on a now-consistent disk state\n * (every loaded extension is guaranteed to have its head ref pinned\n * to the descriptor's hash and to ship every package the descriptor\n * declares).\n *\n * Output ordering is deterministic and alphabetical by spaceId (via\n * {@link planAllSpaces}, which also detects duplicate spaceIds). This\n * matches the canonical sort order used by every other aggregate\n * surface (`migration apply`, `migration status`, the runner).\n */\nexport async function runContractSpaceSeedPhase(\n inputs: ContractSpaceSeedPhaseInputs,\n): Promise<ContractSpaceSeedPhaseResult> {\n const planInputs = inputs.extensionPacks\n .filter(\n (\n pack,\n ): pack is SeedPhaseExtensionInput & {\n contractSpace: NonNullable<SeedPhaseExtensionInput['contractSpace']>;\n } => pack.contractSpace !== undefined,\n )\n .map((pack) => ({\n spaceId: pack.id,\n priorContract: null,\n newContract: pack.contractSpace.contractJson,\n __pack: pack.contractSpace,\n }));\n\n // `planAllSpaces` brings deterministic alphabetical ordering and\n // duplicate-spaceId detection. The \"planner\" callback is a no-op\n // pass-through that simply returns the descriptor's pre-built\n // migration packages.\n const planned: readonly SpacePlanOutput<DescriptorMigrationPackage>[] = planAllSpaces(\n planInputs,\n (input) =>\n (\n input as typeof input & {\n readonly __pack: NonNullable<SeedPhaseExtensionInput['contractSpace']>;\n }\n ).__pack.migrations,\n );\n\n // Reassemble a spaceId → descriptor lookup so the loop below can read\n // the contractJson / headRef without leaking the typed-cast back into\n // `planAllSpaces`'s output shape.\n const descriptorBySpace = new Map<\n string,\n NonNullable<SeedPhaseExtensionInput['contractSpace']>\n >();\n for (const pack of inputs.extensionPacks) {\n if (pack.contractSpace !== undefined) descriptorBySpace.set(pack.id, pack.contractSpace);\n }\n\n const seeded: ContractSpaceSeedPhaseRecord[] = [];\n for (const space of planned) {\n const descriptor = descriptorBySpace.get(space.spaceId);\n if (descriptor === undefined) continue;\n\n const onDiskHeadRef = await readContractSpaceHeadRef(inputs.migrationsDir, space.spaceId);\n const priorHash = onDiskHeadRef?.hash ?? null;\n\n await emitContractSpaceArtefacts(inputs.migrationsDir, space.spaceId, {\n contract: descriptor.contractJson,\n contractDts: buildPlaceholderContractDts(space.spaceId),\n headRef: { hash: descriptor.headRef.hash, invariants: descriptor.headRef.invariants },\n });\n\n const spaceDir = spaceMigrationDirectory(inputs.migrationsDir, space.spaceId);\n const newMigrationDirs: string[] = [];\n for (const pkg of space.migrationPackages) {\n const { written } = await materialiseExtensionMigrationPackageIfMissing(spaceDir, pkg);\n if (written) newMigrationDirs.push(pkg.dirName);\n }\n\n const action: ContractSpaceSeedPhaseRecord['action'] =\n priorHash !== descriptor.headRef.hash || newMigrationDirs.length > 0\n ? 'updated'\n : 'unchanged';\n\n seeded.push({\n spaceId: space.spaceId,\n action,\n priorHash,\n newHash: descriptor.headRef.hash,\n newMigrationDirs,\n });\n }\n\n return { seeded };\n}\n\n/**\n * Placeholder `.d.ts` content for an extension space's on-disk mirror.\n *\n * Rendering a fully-typed `.d.ts` for an extension contract requires\n * the SQL-family renderer with the codec / typemap registry threaded\n * through; until that integration ships, the on-disk `.d.ts` is a\n * stub `export {};` module that documents how consumers should\n * validate the sibling `contract.json`. The stub typechecks on its\n * own and does not need any TypeScript suppressions.\n */\nfunction buildPlaceholderContractDts(spaceId: string): string {\n return [\n '/**',\n ` * Placeholder \\`.d.ts\\` for extension space \"${spaceId}\".`,\n ' *',\n ' * The framework re-emits this file on every `migration plan` run',\n ' * alongside `contract.json` and `refs/head.json`. A typed `.d.ts`',\n ' * rendering pass for extension contracts is tracked separately;',\n ' * until that ships, consumers should import `contract.json`',\n ' * directly with `validateContract<…>(…)`.',\n ' */',\n 'export {};',\n '',\n ].join('\\n');\n}\n","import { readFile } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport {\n createControlStack,\n hasOperationPreview,\n type MigrationPlanOperation,\n type OperationPreview,\n} from '@prisma-next/framework-components/control';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { computeMigrationHash } from '@prisma-next/migration-tools/hash';\nimport { deriveProvidedInvariants } from '@prisma-next/migration-tools/invariants';\nimport {\n copyFilesWithRename,\n formatMigrationDirName,\n writeMigrationPackage,\n} from '@prisma-next/migration-tools/io';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport { findLatestMigration } from '@prisma-next/migration-tools/migration-graph';\nimport { writeMigrationTs } from '@prisma-next/migration-tools/migration-ts';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join, relative } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport {\n type CliErrorConflict,\n CliStructuredError,\n errorContractValidationFailed,\n errorFileNotFound,\n errorMigrationPlanningFailed,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n mapMigrationToolsError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n getTargetMigrations,\n loadMigrationPackages,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { buildContractSpaceAggregate } from '../utils/contract-space-aggregate-loader';\nimport { runContractSpaceSeedPhase } from '../utils/contract-space-seed-phase';\nimport { toExtensionInputs } from '../utils/extension-pack-inputs';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport { assertFrameworkComponentsCompatible } from '../utils/framework-components';\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 MigrationPlanOptions extends CommonCommandOptions {\n readonly config?: string;\n readonly name?: string;\n readonly from?: string;\n}\n\nexport interface MigrationPlanResult {\n readonly ok: boolean;\n readonly noOp: boolean;\n readonly from: string | null;\n readonly to: string;\n readonly dir?: string;\n /**\n * Extension-space migration packages materialised onto disk during this\n * `plan` run. Each entry names a `migrations/<spaceId>/<dirName>/`\n * tree the framework wrote alongside the app-space migration directory.\n * Empty when the project has no extension packs declaring a contract\n * space, or when every extension-space package is already on disk.\n *\n * Surfacing these in the result (rather than only via `ui.step` log\n * lines) makes the cross-space side effect explicit to JSON consumers\n * and the success-summary renderer — the same multi-space side effect\n * that `migration apply` will replay.\n */\n readonly emittedExtensionDirs: readonly { readonly spaceId: string; readonly dirName: string }[];\n readonly operations: readonly {\n readonly id: string;\n readonly label: string;\n readonly operationClass: string;\n }[];\n /**\n * Family-agnostic textual preview of the migration plan operations.\n * Replaces the previous `sql?: readonly string[]` field; consumers should\n * read `result.preview?.statements`.\n */\n readonly preview?: OperationPreview;\n readonly summary: string;\n /**\n * When true, `migration.ts` was written but contains unfilled\n * `placeholder(...)` calls. The user must edit the file and then run\n * `node migration.ts` to self-emit `ops.json` / `migration.json`.\n */\n readonly pendingPlaceholders?: boolean;\n readonly timings: {\n readonly total: number;\n };\n}\n\nasync function executeMigrationPlanCommand(\n options: MigrationPlanOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationPlanResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative } =\n resolveMigrationPaths(options.config, config);\n\n const contractPathAbsolute = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n { label: 'migrations', value: appMigrationsRelative },\n ];\n if (options.from) {\n details.push({ label: 'from', value: options.from });\n }\n if (options.name) {\n details.push({ label: 'name', value: options.name });\n }\n const header = formatStyledHeader({\n command: 'migration plan',\n description: 'Plan a migration from contract changes',\n url: 'https://pris.ly/migration-plan',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // Load contract file (the \"to\" contract)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n let toContractJson: Contract;\n try {\n toContractJson = JSON.parse(contractJsonContent) as Contract;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n const rawStorageHash = toContractJson.storage?.storageHash;\n if (typeof rawStorageHash !== 'string') {\n return notOk(\n errorContractValidationFailed('Contract is missing storageHash', {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n const toStorageHash = rawStorageHash;\n\n // Read existing migrations and determine \"from\" contract\n let fromContract: Contract | null = null;\n let fromHash: string | null = null;\n let fromContractSourceDir: string | null = null;\n\n try {\n const { bundles, graph } = await loadMigrationPackages(appMigrationsDir);\n\n if (options.from) {\n const resolved = resolveBundleByPrefix(bundles, options.from);\n if (!resolved.ok) {\n const f = resolved.failure;\n return notOk(\n f.reason === 'ambiguous'\n ? errorRuntime('Multiple matching migrations found', {\n why: `Prefix \"${options.from}\" matches ${f.count} migrations in ${appMigrationsRelative}`,\n fix: 'Provide a longer prefix to disambiguate, or omit --from to use the latest migration target.',\n })\n : errorRuntime('Starting contract not found', {\n why: `No migration with to hash matching \"${options.from}\" exists in ${appMigrationsRelative}`,\n fix: 'Check that the --from hash matches a known migration target hash, or omit --from to use the latest migration target.',\n }),\n );\n }\n fromHash = resolved.value.metadata.to;\n fromContract = resolved.value.metadata.toContract;\n fromContractSourceDir = resolved.value.dirPath;\n } else {\n const latestMigration = findLatestMigration(graph);\n if (latestMigration) {\n fromHash = latestMigration.to;\n const leafPkg = bundles.find(\n (p) => p.metadata.migrationHash === latestMigration.migrationHash,\n );\n if (leafPkg) {\n fromContract = leafPkg.metadata.toContract;\n fromContractSourceDir = leafPkg.dirPath;\n }\n }\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n // Wrap unexpected (non-MigrationToolsError) failures from the migration\n // load phase in a structured CLI envelope. Letting them throw would\n // bypass `handleResult()` and crash the command — see CLI structured-\n // errors guideline (CliStructuredError + Result pattern).\n const message = error instanceof Error ? error.message : String(error);\n return notOk(\n errorUnexpected(message, {\n why: `Unexpected error while loading migrations: ${message}`,\n }),\n );\n }\n\n // Phase 1 — seed: unconditionally re-emit per-space pinned artefacts\n // (contract.json / contract.d.ts / refs/head.json) and materialise any\n // descriptor-shipped migration packages not yet on disk. Runs before\n // the no-op check so that an extension bump alone (with no structural\n // app-space change) still re-pins extension artefacts on disk.\n const canonicalExtensionInputs = toExtensionInputs(config.extensionPacks ?? []);\n const seedResult = await runContractSpaceSeedPhase({\n migrationsDir,\n extensionPacks: canonicalExtensionInputs,\n });\n if (!flags.json && !flags.quiet) {\n for (const record of seedResult.seeded) {\n if (record.action === 'updated') {\n const pkgSuffix =\n record.newMigrationDirs.length > 0\n ? `; ${record.newMigrationDirs.length} new migration package(s) materialised`\n : '';\n ui.step(`Updated ${record.spaceId} to ${record.newHash}${pkgSuffix}`);\n }\n }\n }\n const emittedExtensionDirs = seedResult.seeded.flatMap((r) =>\n r.newMigrationDirs.map((dirName) => ({ spaceId: r.spaceId, dirName })),\n );\n\n // Check for no-op (same hash means no changes)\n if (fromHash === toStorageHash) {\n const result: MigrationPlanResult = {\n ok: true,\n noOp: true,\n from: fromHash,\n to: toStorageHash,\n operations: [],\n emittedExtensionDirs,\n summary: 'No changes detected between contracts',\n timings: { total: Date.now() - startTime },\n };\n return ok(result);\n }\n\n // Check target supports migrations\n const migrations = getTargetMigrations(config.target);\n if (!migrations) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n // Phase 2 — load: build the aggregate against the now-consistent disk\n // state that phase 1 just seeded. The seed phase guarantees every\n // declared extension has its head ref pinned, so the loader's\n // declaredButUnmigrated precheck always passes here.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n const aggregateResult = await buildContractSpaceAggregate({\n targetId: config.target.targetId,\n migrationsDir,\n appContract: toContractJson,\n extensionPacks: config.extensionPacks ?? [],\n validateContract: (json: unknown) => familyInstance.validateContract(json),\n });\n if (!aggregateResult.ok) {\n return notOk(aggregateResult.failure);\n }\n const aggregate = aggregateResult.value;\n\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n [config.target, config.adapter, ...(config.extensionPacks ?? [])],\n );\n\n // Build manifest and write migration package\n const timestamp = new Date();\n const slug = options.name ?? 'migration';\n const dirName = formatMigrationDirName(timestamp, slug);\n const packageDir = join(appMigrationsDir, dirName);\n\n const baseMetadata: Omit<MigrationMetadata, 'migrationHash' | 'providedInvariants'> = {\n from: fromHash,\n to: toStorageHash,\n fromContract,\n toContract: toContractJson,\n hints: {\n used: [],\n applied: [],\n plannerVersion: '2.0.0',\n },\n labels: [],\n createdAt: timestamp.toISOString(),\n };\n\n try {\n const planner = migrations.createPlanner(familyInstance);\n const fromSchema = migrations.contractToSchema(fromContract, frameworkComponents);\n const plannerResult = planner.plan({\n contract: aggregate.app.contract,\n schema: fromSchema,\n policy: { allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'] },\n fromContract,\n frameworkComponents,\n spaceId: aggregate.app.spaceId,\n });\n if (plannerResult.kind === 'failure') {\n return notOk(\n errorMigrationPlanningFailed({\n conflicts: plannerResult.conflicts as readonly CliErrorConflict[],\n }),\n );\n }\n\n // Accessing .operations triggers toOp() on each call. If any call\n // is a DataTransformCall with an unfilled placeholder stub, toOp()\n // throws PN-MIG-2001. We catch that here so the migration can still\n // be scaffolded with `ops: []`; the user fills the placeholder, then\n // re-runs `node migration.ts` to attest with the real ops.\n let plannedOps: readonly MigrationPlanOperation[] = [];\n let hasPlaceholders = false;\n try {\n plannedOps = plannerResult.plan.operations;\n if (plannedOps.length === 0) {\n return notOk(\n errorMigrationPlanningFailed({\n conflicts: [\n {\n kind: 'unsupportedChange',\n summary:\n 'Contract changed but planner produced no operations. ' +\n 'This indicates unsupported or ignored changes.',\n },\n ],\n }),\n );\n }\n } catch (e) {\n if (CliStructuredError.is(e) && e.domain === 'MIG' && e.code === '2001') {\n hasPlaceholders = true;\n } else {\n throw e;\n }\n }\n\n const migrationTsContent = plannerResult.plan.renderTypeScript();\n\n // Always-attest: compute migrationHash over (metadata, ops). When\n // placeholders blocked lowering, ops is `[]` and the hash is computed\n // over the empty list — re-emitting after the user fills the placeholder\n // produces a different hash (over the real ops). This is intentional;\n // there is no on-disk \"draft\" state.\n const opsForWrite = hasPlaceholders ? [] : plannedOps;\n const metadataWithInvariants: Omit<MigrationMetadata, 'migrationHash'> = {\n ...baseMetadata,\n providedInvariants: deriveProvidedInvariants(opsForWrite),\n };\n const metadata: MigrationMetadata = {\n ...metadataWithInvariants,\n migrationHash: computeMigrationHash(metadataWithInvariants, opsForWrite),\n };\n\n await writeMigrationPackage(packageDir, metadata, opsForWrite);\n const destinationArtifacts = getEmittedArtifactPaths(contractPathAbsolute);\n await copyFilesWithRename(packageDir, [\n { sourcePath: destinationArtifacts.jsonPath, destName: 'end-contract.json' },\n { sourcePath: destinationArtifacts.dtsPath, destName: 'end-contract.d.ts' },\n ]);\n if (fromContractSourceDir !== null) {\n const sourceArtifacts = getEmittedArtifactPaths(\n join(fromContractSourceDir, 'end-contract.json'),\n );\n await copyFilesWithRename(packageDir, [\n { sourcePath: sourceArtifacts.jsonPath, destName: 'start-contract.json' },\n { sourcePath: sourceArtifacts.dtsPath, destName: 'start-contract.d.ts' },\n ]);\n }\n await writeMigrationTs(packageDir, migrationTsContent);\n\n if (hasPlaceholders) {\n const result: MigrationPlanResult = {\n ok: true,\n noOp: false,\n from: fromHash,\n to: toStorageHash,\n dir: relative(process.cwd(), packageDir),\n operations: [],\n emittedExtensionDirs,\n pendingPlaceholders: true,\n summary:\n 'Planned migration with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit',\n timings: { total: Date.now() - startTime },\n };\n return ok(result);\n }\n\n const preview = hasOperationPreview(familyInstance)\n ? familyInstance.toOperationPreview(plannedOps)\n : undefined;\n const result: MigrationPlanResult = {\n ok: true,\n noOp: false,\n from: fromHash,\n to: toStorageHash,\n dir: relative(process.cwd(), packageDir),\n operations: plannedOps.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n emittedExtensionDirs,\n ...(preview !== undefined ? { preview } : {}),\n summary: buildPlanSummary(plannedOps.length, emittedExtensionDirs.length),\n timings: { total: Date.now() - startTime },\n };\n return ok(result);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n const message = error instanceof Error ? error.message : String(error);\n return notOk(\n errorUnexpected(message, {\n why: `Unexpected error during migration plan: ${message}`,\n }),\n );\n }\n}\n\nexport function createMigrationPlanCommand(): Command {\n const command = new Command('plan');\n setCommandDescriptions(\n command,\n 'Plan a migration from contract changes',\n 'Compares the emitted contract against the latest on-disk migration state and\\n' +\n 'produces a new migration package with the required operations. No database\\n' +\n 'connection is needed — this is a fully offline operation.',\n );\n setCommandExamples(command, [\n 'prisma-next migration plan',\n 'prisma-next migration plan --name add-users-table',\n ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--name <slug>', 'Name slug for the migration directory', 'migration')\n .option('--from <hash>', 'Explicit starting contract hash (overrides latest migration target)')\n .action(async (options: MigrationPlanOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeMigrationPlanCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (planResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(planResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationPlanOutput(planResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n\n/**\n * Compose the success-line summary so the cross-space side effect\n * (extension-space migration packages materialised on disk during\n * this `plan` run) is visible in the top line — not just in the\n * step log above it.\n *\n * Example outputs:\n * - `Planned 3 operation(s)` (app-space-only project)\n * - `Planned 3 operation(s); materialised 1 extension-space migration` (one extension)\n * - `Planned 3 operation(s); materialised 2 extension-space migrations` (two extensions)\n *\n * Locks AC3 at the summary-line level: a reader of the success line\n * can tell that something happened beyond the app space.\n */\nfunction buildPlanSummary(plannedOpsCount: number, emittedExtensionDirsCount: number): string {\n const base = `Planned ${plannedOpsCount} operation(s)`;\n if (emittedExtensionDirsCount === 0) return base;\n const noun =\n emittedExtensionDirsCount === 1 ? 'extension-space migration' : 'extension-space migrations';\n return `${base}; materialised ${emittedExtensionDirsCount} ${noun}`;\n}\n\nexport function formatMigrationPlanOutput(result: MigrationPlanResult, flags: GlobalFlags): string {\n const lines: string[] = [];\n const useColor = flags.color !== false;\n\n const green_ = useColor ? (s: string) => `\\x1b[32m${s}\\x1b[0m` : (s: string) => s;\n const yellow_ = useColor ? (s: string) => `\\x1b[33m${s}\\x1b[0m` : (s: string) => s;\n const dim_ = useColor ? (s: string) => `\\x1b[2m${s}\\x1b[0m` : (s: string) => s;\n\n // Renders the extension-space materialisation block + canonical apply-step\n // hint shared by the no-op, placeholder, and full-plan branches. The app\n // space short-circuits do not skip it: an extension-only bump emits new\n // `migrations/<spaceId>/<dirName>/` directories on disk that the user\n // still has to apply, so the success line must surface them.\n function appendEmittedExtensions(): void {\n if (result.emittedExtensionDirs.length === 0) return;\n lines.push('');\n lines.push(dim_('Emitted extension migrations:'));\n for (const entry of result.emittedExtensionDirs) {\n lines.push(dim_(` ${entry.spaceId} → migrations/${entry.spaceId}/${entry.dirName}`));\n }\n lines.push('');\n lines.push(\n `Next: review the extension migrations above, then run ${green_('prisma-next migration apply')}.`,\n );\n }\n\n if (result.noOp) {\n lines.push(`${green_('✔')} No changes detected`);\n lines.push(dim_(` from: ${result.from}`));\n lines.push(dim_(` to: ${result.to}`));\n appendEmittedExtensions();\n return lines.join('\\n');\n }\n\n if (result.pendingPlaceholders) {\n lines.push(`${yellow_('⚠')} ${result.summary}`);\n lines.push('');\n lines.push(dim_(`from: ${result.from}`));\n lines.push(dim_(`to: ${result.to}`));\n if (result.dir) {\n lines.push(dim_(`dir: ${result.dir}`));\n }\n lines.push('');\n lines.push(\n 'Open migration.ts and replace each `placeholder(...)` call with your actual query.',\n );\n lines.push(`Then run: ${green_(`node ${result.dir ?? '<dir>'}/migration.ts`)}`);\n appendEmittedExtensions();\n return lines.join('\\n');\n }\n\n lines.push(`${green_('✔')} ${result.summary}`);\n lines.push('');\n\n if (result.operations.length > 0) {\n lines.push(dim_('│'));\n for (let i = 0; i < result.operations.length; i++) {\n const op = result.operations[i]!;\n const isLast = i === result.operations.length - 1;\n const treeChar = isLast ? '└' : '├';\n // operationClass tag is intentionally NOT inlined per spec:\n // a destructive footer warning still surfaces below this list.\n const destructiveMarker =\n op.operationClass === 'destructive' ? ` ${yellow_('(destructive)')}` : '';\n lines.push(`${dim_(treeChar)}─ ${op.label}${destructiveMarker}`);\n }\n\n const hasDestructive = result.operations.some((op) => op.operationClass === 'destructive');\n if (hasDestructive) {\n lines.push('');\n lines.push(\n `${yellow_('⚠')} This migration contains destructive operations that may cause data loss.`,\n );\n }\n lines.push('');\n }\n\n lines.push(dim_(`from: ${result.from}`));\n lines.push(dim_(`to: ${result.to}`));\n if (result.dir) {\n lines.push(dim_(`App space → ${result.dir}`));\n }\n // Per-space block: surface the extension-space directories materialised\n // alongside the app-space migration. Without this block the cross-space\n // side effect is invisible in the success summary (e2e finding F1).\n for (const entry of result.emittedExtensionDirs) {\n lines.push(\n dim_(`Extension space ${entry.spaceId} → migrations/${entry.spaceId}/${entry.dirName}`),\n );\n }\n\n lines.push('');\n // The \"Next:\" hint always points at the canonical apply path\n // (`prisma-next migration apply`) regardless of how many spaces\n // were materialised — `db update` is a dev-time convenience, not\n // the canonical replay step.\n lines.push(\n `Next: review ${green_(result.dir ?? '<dir>')} if needed, then run ${green_('prisma-next migration apply')}.`,\n );\n\n if (result.preview && result.preview.statements.length > 0) {\n // The non-empty length is already guaranteed by the surrounding check, so\n // a plain `every` here is equivalent to the helper in formatters/migrations.ts.\n const allSql = result.preview.statements.every((s) => s.language === 'sql');\n lines.push('');\n lines.push(dim_(allSql ? 'DDL preview' : 'Operation preview'));\n lines.push('');\n for (const statement of result.preview.statements) {\n const trimmed = statement.text.trim();\n if (!trimmed) continue;\n const line = statement.language === 'sql' && !trimmed.endsWith(';') ? `${trimmed};` : trimmed;\n lines.push(line);\n }\n }\n\n if (flags.verbose && result.timings) {\n lines.push('');\n lines.push(dim_(`Total time: ${result.timings.total}ms`));\n }\n\n return lines.join('\\n');\n}\n\nexport type PrefixResolutionFailure =\n | { reason: 'ambiguous'; count: number }\n | { reason: 'not-found' };\n\n/**\n * Resolve a migration package by **target contract hash** (`metadata.to`)\n * using exact match or prefix match.\n *\n * Note: matches `metadata.to` (the contract hash this migration produces),\n * not `metadata.migrationHash` (the package's content-addressed identity).\n * Tries exact match first, then prefix match (auto-prepending `sha256:` when\n * the needle omits the scheme). Returns the matched package on success, or a\n * discriminated failure indicating whether the prefix was ambiguous or simply\n * not found.\n *\n * @internal Exported for testing only.\n */\nexport function resolveBundleByPrefix<T extends { metadata: { to: string } }>(\n bundles: readonly T[],\n needle: string,\n): Result<T, PrefixResolutionFailure> {\n const exact = bundles.find((p) => p.metadata.to === needle);\n if (exact) return ok(exact);\n\n const prefixWithScheme = needle.startsWith('sha256:') ? needle : `sha256:${needle}`;\n const candidates = bundles.filter((p) => p.metadata.to.startsWith(prefixWithScheme));\n\n if (candidates.length === 1) return ok(candidates[0]!);\n if (candidates.length > 1) return notOk({ reason: 'ambiguous', count: candidates.length });\n return notOk({ reason: 'not-found' });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,eAAsB,0BACpB,QACuC;CAoBvC,MAAM,UAAkE,cAnBrD,OAAO,eACvB,QAEG,SAGG,KAAK,kBAAkB,KAAA,EAC7B,CACA,KAAK,UAAU;EACd,SAAS,KAAK;EACd,eAAe;EACf,aAAa,KAAK,cAAc;EAChC,QAAQ,KAAK;EACd,EAOS,GACT,UAEG,MAGA,OAAO,WACZ;CAKD,MAAM,oCAAoB,IAAI,KAG3B;CACH,KAAK,MAAM,QAAQ,OAAO,gBACxB,IAAI,KAAK,kBAAkB,KAAA,GAAW,kBAAkB,IAAI,KAAK,IAAI,KAAK,cAAc;CAG1F,MAAM,SAAyC,EAAE;CACjD,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,aAAa,kBAAkB,IAAI,MAAM,QAAQ;EACvD,IAAI,eAAe,KAAA,GAAW;EAG9B,MAAM,aAAY,MADU,yBAAyB,OAAO,eAAe,MAAM,QAAQ,GACxD,QAAQ;EAEzC,MAAM,2BAA2B,OAAO,eAAe,MAAM,SAAS;GACpE,UAAU,WAAW;GACrB,aAAa,4BAA4B,MAAM,QAAQ;GACvD,SAAS;IAAE,MAAM,WAAW,QAAQ;IAAM,YAAY,WAAW,QAAQ;IAAY;GACtF,CAAC;EAEF,MAAM,WAAW,wBAAwB,OAAO,eAAe,MAAM,QAAQ;EAC7E,MAAM,mBAA6B,EAAE;EACrC,KAAK,MAAM,OAAO,MAAM,mBAAmB;GACzC,MAAM,EAAE,YAAY,MAAM,8CAA8C,UAAU,IAAI;GAC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;EAC3E,MAAM,KAAK,GAAG;EACd,MAAM,KAAK,KAAK,SAAS,gBAAgB,oBAAoB,CAAC;EAC9D,MAAM,KAAK,GAAG;EACd,KAAK,MAAM,aAAa,OAAO,QAAQ,YAAY;GACjD,MAAM,UAAU,UAAU,KAAK,MAAM;GACrC,IAAI,CAAC,SAAS;GACd,MAAM,OAAO,UAAU,aAAa,SAAS,CAAC,QAAQ,SAAS,IAAI,GAAG,GAAG,QAAQ,KAAK;GACtF,MAAM,KAAK,KAAK;;;CAIpB,IAAI,MAAM,WAAW,OAAO,SAAS;EACnC,MAAM,KAAK,GAAG;EACd,MAAM,KAAK,KAAK,eAAe,OAAO,QAAQ,MAAM,IAAI,CAAC;;CAG3D,OAAO,MAAM,KAAK,KAAK;;;;;;;;;;;;;;;AAoBzB,SAAgB,sBACd,SACA,QACoC;CACpC,MAAM,QAAQ,QAAQ,MAAM,MAAM,EAAE,SAAS,OAAO,OAAO;CAC3D,IAAI,OAAO,OAAO,GAAG,MAAM;CAE3B,MAAM,mBAAmB,OAAO,WAAW,UAAU,GAAG,SAAS,UAAU;CAC3E,MAAM,aAAa,QAAQ,QAAQ,MAAM,EAAE,SAAS,GAAG,WAAW,iBAAiB,CAAC;CAEpF,IAAI,WAAW,WAAW,GAAG,OAAO,GAAG,WAAW,GAAI;CACtD,IAAI,WAAW,SAAS,GAAG,OAAO,MAAM;EAAE,QAAQ;EAAa,OAAO,WAAW;EAAQ,CAAC;CAC1F,OAAO,MAAM,EAAE,QAAQ,aAAa,CAAC"}
|
|
@@ -3,7 +3,8 @@ import { _ as errorUnexpected, m as errorRuntime, v as mapMigrationToolsError }
|
|
|
3
3
|
import { a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, g as parseGlobalFlags, h as toStructuralEdge, l as resolveMigrationPaths, m as toPathDecisionResult, n as collectDeclaredInvariants, o as maskConnectionUrl, s as readContractEnvelope, t as addGlobalOptions, y as formatStyledHeader } from "./command-helpers-BeZHkxV8.mjs";
|
|
4
4
|
import { t as TerminalUI } from "./terminal-ui-C_hFNbAn.mjs";
|
|
5
5
|
import { t as handleResult } from "./result-handler-rmPVKIP2.mjs";
|
|
6
|
-
import {
|
|
6
|
+
import { t as createControlClient } from "./client-BCnP7cHo.mjs";
|
|
7
|
+
import { t as buildContractSpaceAggregate } from "./contract-space-aggregate-loader-BrwKK6Q6.mjs";
|
|
7
8
|
import { Command } from "commander";
|
|
8
9
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
9
10
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -1310,7 +1311,7 @@ async function loadAggregateStatusSpaces(args) {
|
|
|
1310
1311
|
let pendingCount = 0;
|
|
1311
1312
|
let status;
|
|
1312
1313
|
if (walked.kind === "ok") {
|
|
1313
|
-
pendingCount = walked.result.
|
|
1314
|
+
pendingCount = walked.result.migrationEdges?.length ?? 0;
|
|
1314
1315
|
if (liveMarker === null) status = pendingCount === 0 ? "no-marker" : "pending";
|
|
1315
1316
|
else status = pendingCount === 0 ? "up-to-date" : "pending";
|
|
1316
1317
|
} else status = "unreachable";
|
|
@@ -1468,11 +1469,8 @@ async function executeMigrationStatusCommand(options, flags, ui) {
|
|
|
1468
1469
|
markerHash = marker?.storageHash;
|
|
1469
1470
|
markerInvariants = marker?.invariants ?? [];
|
|
1470
1471
|
mode = "online";
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
} catch {
|
|
1474
|
-
allMarkers = null;
|
|
1475
|
-
}
|
|
1472
|
+
if (typeof client.readAllMarkers === "function") allMarkers = await client.readAllMarkers();
|
|
1473
|
+
else allMarkers = null;
|
|
1476
1474
|
} catch {
|
|
1477
1475
|
if (!flags.json && !flags.quiet) ui.warn("Could not connect to database — showing offline status");
|
|
1478
1476
|
} finally {
|
|
@@ -1769,4 +1767,4 @@ function summarizeRefDistance(graph, markerHash, refHash, refName) {
|
|
|
1769
1767
|
//#endregion
|
|
1770
1768
|
export { loadAggregateStatusSpaces as a, formatStatusSummary as i, createMigrationStatusCommand as n, deriveEdgeStatuses as r, computeTotalPendingAcrossSpaces as t };
|
|
1771
1769
|
|
|
1772
|
-
//# sourceMappingURL=migration-status-
|
|
1770
|
+
//# sourceMappingURL=migration-status-By9G5p2H.mjs.map
|