@prisma/orm-toolchain 8.0.0-rc.24-dev.42 → 8.0.0-rc.24-dev.44

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.
Files changed (93) hide show
  1. package/dist/{aggregate-BAt9Aj73.mjs → aggregate-B2D5REGs.mjs} +9 -9
  2. package/dist/{aggregate-BAt9Aj73.mjs.map → aggregate-B2D5REGs.mjs.map} +1 -1
  3. package/dist/{aggregate-DgWdbWNs.d.mts → aggregate-CvDNKQbR.d.mts} +5 -5
  4. package/dist/{aggregate-DgWdbWNs.d.mts.map → aggregate-CvDNKQbR.d.mts.map} +1 -1
  5. package/dist/{caught-errors-D_pbHqmS-B-4jRN6g.mjs → caught-errors-DZXnK8Ls-zVmM4nr3.mjs} +590 -49
  6. package/dist/caught-errors-DZXnK8Ls-zVmM4nr3.mjs.map +1 -0
  7. package/dist/cli-telemetry.mjs +1 -1
  8. package/dist/cli.d.mts +1 -1
  9. package/dist/cli.mjs +342 -106
  10. package/dist/cli.mjs.map +1 -1
  11. package/dist/cli__control-api.d.mts +13 -60
  12. package/dist/cli__control-api.d.mts.map +1 -1
  13. package/dist/cli__control-api.mjs +2 -2
  14. package/dist/cli__control-api__testing.d.mts +1 -1
  15. package/dist/cli__migration-cli.mjs +4 -4
  16. package/dist/cli__migration-cli.mjs.map +1 -1
  17. package/dist/config-loader.mjs +1 -1
  18. package/dist/contract-snapshot-store-D-s2aKZY.d.mts +2 -0
  19. package/dist/{contract-snapshot-store-xDOQSwJh-YNdzKU85.d.mts → contract-snapshot-store-DRAG5XXy-ChW4hBLb.d.mts} +6 -4
  20. package/dist/contract-snapshot-store-DRAG5XXy-ChW4hBLb.d.mts.map +1 -0
  21. package/dist/{contract-snapshot-store-B0fRbVHB-BN2g8BKh.mjs → contract-snapshot-store-Dl6v-Uxr-CwhnMsgc.mjs} +10 -6
  22. package/dist/contract-snapshot-store-Dl6v-Uxr-CwhnMsgc.mjs.map +1 -0
  23. package/dist/{db-sign-DLIR5swa-DQ0aN1nU.d.mts → db-sign-BQMw6RX9-Stp7Gjj7.d.mts} +187 -18
  24. package/dist/db-sign-BQMw6RX9-Stp7Gjj7.d.mts.map +1 -0
  25. package/dist/{domain-type-generation-BGcbGgHJ-Cdw5RNaZ.mjs → domain-type-generation-BGcbGgHJ-SB6n89eE.mjs} +3 -3
  26. package/dist/{domain-type-generation-BGcbGgHJ-Cdw5RNaZ.mjs.map → domain-type-generation-BGcbGgHJ-SB6n89eE.mjs.map} +1 -1
  27. package/dist/emitter.mjs +2 -2
  28. package/dist/emitter__domain-type-generation.mjs +1 -1
  29. package/dist/{errors-BMq40nYH-Cg8PBect.mjs → errors-BlaB9AFz-CZDOC0mV.mjs} +8 -10
  30. package/dist/{errors-BMq40nYH-Cg8PBect.mjs.map → errors-BlaB9AFz-CZDOC0mV.mjs.map} +1 -1
  31. package/dist/{exports-BiXPktAF.mjs → exports-B0yFVod3.mjs} +3 -3
  32. package/dist/{exports-BiXPktAF.mjs.map → exports-B0yFVod3.mjs.map} +1 -1
  33. package/dist/{exports-CCuYD8dO-yw1GizAT.mjs → exports-CCuYD8dO-fFXwpizm.mjs} +3 -3
  34. package/dist/{exports-CCuYD8dO-yw1GizAT.mjs.map → exports-CCuYD8dO-fFXwpizm.mjs.map} +1 -1
  35. package/dist/{exports-CZ6dPu-O.mjs → exports-DNFYCa6U.mjs} +3 -3
  36. package/dist/{exports-CZ6dPu-O.mjs.map → exports-DNFYCa6U.mjs.map} +1 -1
  37. package/dist/{graph-membership-D7m41lWA-B68g1CRS.mjs → graph-membership-ClCmhVjf-8XCns4rf.mjs} +3 -3
  38. package/dist/{graph-membership-D7m41lWA-B68g1CRS.mjs.map → graph-membership-ClCmhVjf-8XCns4rf.mjs.map} +1 -1
  39. package/dist/hash-DcBt3lpO.d.mts +1 -0
  40. package/dist/{hash-DclMqd7S-WBvXJ_4C.d.mts → hash-DclMqd7S-Dddl_NeA.d.mts} +2 -2
  41. package/dist/{hash-DclMqd7S-WBvXJ_4C.d.mts.map → hash-DclMqd7S-Dddl_NeA.d.mts.map} +1 -1
  42. package/dist/{invariants-DxCj82g2-DhGkStla.mjs → invariants-c9W7-6DY-CzSdi8Vp.mjs} +3 -3
  43. package/dist/{invariants-DxCj82g2-DhGkStla.mjs.map → invariants-c9W7-6DY-CzSdi8Vp.mjs.map} +1 -1
  44. package/dist/io-BalYebmm.d.mts +1 -0
  45. package/dist/{io-B39zsxMm-D5Wcf6cf.mjs → io-DUsSXBRO-BqRNb69U.mjs} +5 -5
  46. package/dist/{io-B39zsxMm-D5Wcf6cf.mjs.map → io-DUsSXBRO-BqRNb69U.mjs.map} +1 -1
  47. package/dist/{io-BzVNzfsY-DE_ev9K6.d.mts → io-DpAplMzQ-ZTJi-tTr.d.mts} +3 -3
  48. package/dist/{io-BzVNzfsY-DE_ev9K6.d.mts.map → io-DpAplMzQ-ZTJi-tTr.d.mts.map} +1 -1
  49. package/dist/{migration-DTmtOJ0n.mjs → migration-C1l4_CWi.mjs} +3 -3
  50. package/dist/{migration-DTmtOJ0n.mjs.map → migration-C1l4_CWi.mjs.map} +1 -1
  51. package/dist/{migration-graph-BoiiZAaU-DLht12k7.mjs → migration-graph-DBJAol1y-DX61Ss3X.mjs} +19 -3
  52. package/dist/{migration-graph-BoiiZAaU-DLht12k7.mjs.map → migration-graph-DBJAol1y-DX61Ss3X.mjs.map} +1 -1
  53. package/dist/{migration-graph-D8IuOkZb-pSI7-k4_.d.mts → migration-graph-DCIdjMtC-CAs3pm1A.d.mts} +10 -3
  54. package/dist/{migration-graph-D8IuOkZb-pSI7-k4_.d.mts.map → migration-graph-DCIdjMtC-CAs3pm1A.d.mts.map} +1 -1
  55. package/dist/{migration-graph-Dra4CcyN.d.mts → migration-graph-GiSYbAc8.d.mts} +2 -2
  56. package/dist/{migration-graph-Dra4CcyN.d.mts.map → migration-graph-GiSYbAc8.d.mts.map} +1 -1
  57. package/dist/migration-tools.d.mts +14 -14
  58. package/dist/migration-tools.mjs +13 -13
  59. package/dist/migration-tools__aggregate.d.mts +1 -1
  60. package/dist/migration-tools__aggregate.mjs +1 -1
  61. package/dist/migration-tools__contract-snapshot-store.d.mts +4 -4
  62. package/dist/migration-tools__contract-snapshot-store.mjs +2 -2
  63. package/dist/migration-tools__errors.mjs +1 -1
  64. package/dist/migration-tools__hash.d.mts +2 -2
  65. package/dist/migration-tools__invariants.mjs +1 -1
  66. package/dist/migration-tools__io.d.mts +2 -2
  67. package/dist/migration-tools__io.mjs +1 -1
  68. package/dist/migration-tools__migration-graph.d.mts +3 -3
  69. package/dist/migration-tools__migration-graph.mjs +3 -3
  70. package/dist/migration-tools__migration.mjs +1 -1
  71. package/dist/migration-tools__ref-resolution.mjs +1 -1
  72. package/dist/migration-tools__refs.mjs +1 -1
  73. package/dist/migration-tools__spaces.mjs +2 -2
  74. package/dist/{ref-Ba6Mk6Rg-DKaPWk2l.mjs → ref-C7TozKnq-C4UYYbRT.mjs} +398 -162
  75. package/dist/ref-C7TozKnq-C4UYYbRT.mjs.map +1 -0
  76. package/dist/{ref-resolution-C0xsiRig.mjs → ref-resolution-533MGMov.mjs} +2 -2
  77. package/dist/{ref-resolution-C0xsiRig.mjs.map → ref-resolution-533MGMov.mjs.map} +1 -1
  78. package/dist/{refs-t_JbIjGo-BVCqKpXd.mjs → refs-BE6yEgSV-CbpqGnbl.mjs} +3 -3
  79. package/dist/{refs-t_JbIjGo-BVCqKpXd.mjs.map → refs-BE6yEgSV-CbpqGnbl.mjs.map} +1 -1
  80. package/dist/{spaces-OVZ0QzWJ.mjs → spaces-Cj_GYpmM.mjs} +7 -7
  81. package/dist/{spaces-OVZ0QzWJ.mjs.map → spaces-Cj_GYpmM.mjs.map} +1 -1
  82. package/dist/{verify-contract-spaces-BOnqhfQs-BBq5YOKo.mjs → verify-contract-spaces-DvU9lE0Y-Y1WwEsPA.mjs} +4 -4
  83. package/dist/{verify-contract-spaces-BOnqhfQs-BBq5YOKo.mjs.map → verify-contract-spaces-DvU9lE0Y-Y1WwEsPA.mjs.map} +1 -1
  84. package/dist/vite-plugin-contract-emit.mjs +3 -3
  85. package/package.json +11 -11
  86. package/dist/caught-errors-D_pbHqmS-B-4jRN6g.mjs.map +0 -1
  87. package/dist/contract-snapshot-store-B0fRbVHB-BN2g8BKh.mjs.map +0 -1
  88. package/dist/contract-snapshot-store-DXFizCe8.d.mts +0 -2
  89. package/dist/contract-snapshot-store-xDOQSwJh-YNdzKU85.d.mts.map +0 -1
  90. package/dist/db-sign-DLIR5swa-DQ0aN1nU.d.mts.map +0 -1
  91. package/dist/hash-CwWGlFWV.d.mts +0 -1
  92. package/dist/io--BGERFnD.d.mts +0 -1
  93. package/dist/ref-Ba6Mk6Rg-DKaPWk2l.mjs.map +0 -1
@@ -1,5 +1,8 @@
1
- import "./constants-CM-w38DQ-Cz_EXbOc.mjs";
2
- import { l as spaceMigrationDirectory, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-BOnqhfQs-BBq5YOKo.mjs";
1
+ import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
2
+ import { n as isGraphNode } from "./graph-membership-ClCmhVjf-8XCns4rf.mjs";
3
+ import { a as findPathWithInvariants, o as historyEndsFrom, r as findPath, s as reconstructGraph } from "./migration-graph-DBJAol1y-DX61Ss3X.mjs";
4
+ import { l as spaceMigrationDirectory, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-DvU9lE0Y-Y1WwEsPA.mjs";
5
+ import { a as contractHashAtMarker } from "./aggregate-B2D5REGs.mjs";
3
6
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
4
7
  import { CliStructuredError as CliStructuredError$1, errorConfigValidation as errorConfigValidation$1, errorContractConfigMissing, errorContractValidationFailed, errorDatabaseConnectionRequired, errorDriverRequired, errorFileNotFound, errorMigrationPlanningFailed, errorTargetMigrationNotSupported, errorUnexpected } from "@prisma/orm-framework/errors/control";
5
8
  import { APP_SPACE_ID, hasMigrations } from "@prisma/orm-framework/components/control";
@@ -7,10 +10,277 @@ import { InternalError, isInternalError } from "@prisma/orm-framework/utils/inte
7
10
  import { notOk, ok } from "@prisma/orm-framework/utils/result";
8
11
  import { isStructuredError } from "@prisma/orm-framework/utils/structured-error";
9
12
  import { join, relative, resolve } from "pathe";
13
+ import { readFile } from "node:fs/promises";
10
14
  import { errorHashMismatch, errorMarkerMissing, errorRuntime, errorTargetMismatch } from "@prisma/orm-framework/errors/execution";
11
15
  import "@prisma/orm-framework/errors/migration";
12
- import { readFile } from "node:fs/promises";
13
- //#region ../../../1-framework/3-tooling/cli/dist/caught-errors-D_pbHqmS.mjs
16
+ //#region ../../../1-framework/3-tooling/cli/dist/caught-errors-DZXnK8Ls.mjs
17
+ /**
18
+ * Read-only migration-graph queries commands need at the control-api seam.
19
+ */
20
+ /** True when the on-disk graph contains a path fromHash → toHash. */
21
+ function hasMigrationPath(graph, fromHash, toHash) {
22
+ return findPath(graph, fromHash, toHash) !== null;
23
+ }
24
+ /** The invariants `target` requires that the database at `marker` does not record. */
25
+ function missingInvariants(marker, target) {
26
+ const recorded = new Set(marker?.invariants ?? []);
27
+ return new Set(target.invariants.filter((invariant) => !recorded.has(invariant)));
28
+ }
29
+ /** `space.emittedHash` is the contract the caller takes as emitted, as `PlanSpace.emittedHash` describes. */
30
+ function migrationsToTarget(space, marker, target) {
31
+ const from = contractHashAtMarker(marker);
32
+ const missing = missingInvariants(marker, target);
33
+ if (from === target.hash && missing.size === 0) return { kind: "none-needed" };
34
+ if (findPathWithInvariants(space.graph, from, target.hash, missing) !== null) return { kind: "on-disk" };
35
+ const missingInvariantIds = [...missing].sort();
36
+ if (from !== target.hash) return {
37
+ kind: "plan-needed",
38
+ missingInvariants: missingInvariantIds
39
+ };
40
+ return {
41
+ kind: "at-target-missing-invariants",
42
+ missingInvariants: missingInvariantIds,
43
+ ...ifDefined("newMigration", (space.graph.reverseChain.get(target.hash)?.length ?? 0) > 0 ? {
44
+ from: target.hash,
45
+ emitFirst: space.emittedHash !== target.hash
46
+ } : void 0)
47
+ };
48
+ }
49
+ function reference(value) {
50
+ return {
51
+ kind: "reference",
52
+ reference: value
53
+ };
54
+ }
55
+ /** The ref `refs` defines under `name`; not one `Object.prototype` holds, such as `constructor`. */
56
+ function refNamed(refs, name) {
57
+ return Object.hasOwn(refs, name) ? refs[name] : void 0;
58
+ }
59
+ /** The names of `refs`, the `db` ref first. */
60
+ function refNames(refs) {
61
+ return Object.keys(refs).sort((a, b) => a === "db" ? -1 : b === "db" ? 1 : a.localeCompare(b));
62
+ }
63
+ /** Where the history that continues from `hash` ends, as `--from` names each end. */
64
+ function historyEnds(graph, hash = EMPTY_CONTRACT_HASH) {
65
+ return historyEndsFrom(graph, hash).map((end) => end === "empty" ? "@empty" : end);
66
+ }
67
+ /**
68
+ * The `--from` the user chooses, for `reason`, when where the database is cannot be told: with no
69
+ * migrations, `@empty` or a ref, which `migration plan` baselines; otherwise where the history ends;
70
+ * with the space unread, none named.
71
+ */
72
+ function migrationPlanChoice(space, reason) {
73
+ return {
74
+ kind: "ambiguous",
75
+ reason,
76
+ candidates: space === void 0 ? [] : space.graph.nodes.size === 0 ? ["@empty", ...refNames(space.refs)] : historyEnds(space.graph)
77
+ };
78
+ }
79
+ const NO_MARKER = "The database has no marker";
80
+ const ADOPT_FIRST = "A database that is not empty needs adopting first";
81
+ /** Why a database with no marker in a space with no migrations gets a plan from `@empty` only as a choice. */
82
+ const NO_MARKER_REASON = `${NO_MARKER}, so a plan from \`@empty\` fits only an empty database. ${ADOPT_FIRST}: emit the contract that describes it as it is, before your change, and record it with \`{bin} db sign\`, then plan from there`;
83
+ /**
84
+ * Why `db migrate` on a database with no marker, in a space with migrations, fits only an empty
85
+ * database, and how to adopt one that is not: `sign` is the `db sign <contract>` and `list` the
86
+ * `migration list` advice prints.
87
+ */
88
+ function noMarkerReplayText(sign, list) {
89
+ return `${NO_MARKER}, so \`db migrate\` applies every migration on disk from the first, which fits only an empty database. ${ADOPT_FIRST}: record the contract it is at with \`${sign}\`, naming the migration whose result it matches (\`${list}\` shows them), and \`db migrate\` then applies only the migrations after it`;
90
+ }
91
+ function at(from) {
92
+ return {
93
+ from,
94
+ afterUnapplied: false
95
+ };
96
+ }
97
+ /**
98
+ * The `--from` that makes `migration plan` start where a database at `position` is. A contract a
99
+ * migration records is named by its hash. An empty database starts where its history ends, because
100
+ * a plan from the empty contract would recreate what the existing migrations create; with no
101
+ * migration from the empty contract it starts at `@empty`. With no migrations, a database with no
102
+ * marker may be empty or may need adopting, so the plan from `@empty` is a choice; a database at a
103
+ * contract a ref names starts from the ref, which `migration plan` baselines.
104
+ */
105
+ function startAtPosition(space, position) {
106
+ const { graph, refs } = space;
107
+ if (position.kind === "unknown") return at(migrationPlanChoice(space, position.reason));
108
+ if (position.kind === "unmarked" || position.hash === "empty") {
109
+ if (graph.nodes.size === 0) return at(position.kind === "unmarked" ? {
110
+ kind: "ambiguous",
111
+ reason: NO_MARKER_REASON,
112
+ candidates: ["@empty"]
113
+ } : reference("@empty"));
114
+ return startAtEndOf(graph, EMPTY_CONTRACT_HASH, "The migration history an empty database replays");
115
+ }
116
+ if (isGraphNode(position.hash, graph)) return at(reference(position.hash));
117
+ if (graph.nodes.size === 0) {
118
+ const [name] = refNames(refs).filter((each) => refs[each]?.hash === position.hash);
119
+ if (name !== void 0) return at(reference(name));
120
+ return at({
121
+ kind: "none",
122
+ reason: `No ref names contract ${position.hash}, and with no migrations \`migration plan\` starts only from \`@empty\` or a ref`
123
+ });
124
+ }
125
+ return at({
126
+ kind: "none",
127
+ reason: `No migration records contract ${position.hash}, and \`migration plan\` starts only from a contract a migration records`
128
+ });
129
+ }
130
+ /**
131
+ * Where the history that continues from `hash` ends: the one end, or a choice of them, past
132
+ * migrations not applied when an end is not `hash` itself.
133
+ */
134
+ function startAtEndOf(graph, hash, history) {
135
+ const ends = historyEnds(graph, hash);
136
+ const start = hash === "empty" ? "@empty" : hash;
137
+ const afterUnapplied = ends.some((end) => end !== start);
138
+ const [onlyEnd] = ends;
139
+ if (ends.length === 1 && onlyEnd !== void 0) return {
140
+ from: reference(onlyEnd),
141
+ afterUnapplied
142
+ };
143
+ return {
144
+ from: {
145
+ kind: "ambiguous",
146
+ reason: `${history} has more than one end`,
147
+ candidates: ends
148
+ },
149
+ afterUnapplied
150
+ };
151
+ }
152
+ /**
153
+ * The `--to` that makes `migration plan` end at `end`: none for the emitted contract, which it
154
+ * targets by default, nor for a contract hash that is the one the run was given; a ref by its name;
155
+ * a contract a migration records by its hash. It does not plan to the empty contract, by its hash or
156
+ * a ref, or to any other contract no migration records.
157
+ */
158
+ function migrationPlanTo(space, end) {
159
+ if (end.kind === "emitted") return { kind: "default" };
160
+ if ((end.kind === "ref" ? refNamed(space.refs, end.name)?.hash : end.hash) === "empty") return {
161
+ kind: "none",
162
+ reason: "`migration plan` does not plan a migration to the empty contract"
163
+ };
164
+ if (end.kind === "ref") return reference(end.name);
165
+ if (isGraphNode(end.hash, space.graph)) return reference(end.hash);
166
+ if (end.hash === space.emittedHash) return { kind: "default" };
167
+ return {
168
+ kind: "none",
169
+ reason: `No migration records contract ${end.hash}, and \`migration plan --to\` ends only at a contract a migration records, a ref, or the emitted contract`
170
+ };
171
+ }
172
+ /**
173
+ * The `--from` and `--to` of the `migration plan` that takes a database at `position` to `end`. To
174
+ * a contract the history records, the plan leaves from where the database is. To the emitted
175
+ * contract, a new one, it extends the history: it starts where the history that continues from the
176
+ * database's contract ends, so `db migrate` applies the migrations after it and then the new one,
177
+ * and the plan forks nothing.
178
+ */
179
+ function migrationPlanArguments(space, position, end) {
180
+ const to = migrationPlanTo(space, end);
181
+ const start = to.kind === "default" && position.kind === "contract" && position.hash !== "empty" && isGraphNode(position.hash, space.graph) ? startAtEndOf(space.graph, position.hash, "The migration history that continues from where the database is") : startAtPosition(space, position);
182
+ return {
183
+ from: start.from,
184
+ to,
185
+ ...ifDefined("startsAfterUnapplied", start.afterUnapplied ? true : void 0)
186
+ };
187
+ }
188
+ const EMPTY_ORIGIN_STATEMENTS = "A plan from `@empty` creates every model, so its statements name nothing it can resolve";
189
+ /**
190
+ * `from` for a plan that carries `--rename`, `--delete`, `--convert` or `--backfill`: such a plan
191
+ * cannot start at `@empty`, so that start is dropped, and with no start left there is no plan.
192
+ */
193
+ function migrationPlanFromForStatements(from) {
194
+ if (from.kind === "reference" && from.reference === "@empty") return {
195
+ kind: "none",
196
+ reason: EMPTY_ORIGIN_STATEMENTS
197
+ };
198
+ if (from.kind !== "ambiguous" || !from.candidates.includes("@empty")) return from;
199
+ const candidates = from.candidates.filter((candidate) => candidate !== "@empty");
200
+ return candidates.length === 0 ? {
201
+ kind: "none",
202
+ reason: `${from.reason}. ${EMPTY_ORIGIN_STATEMENTS}`
203
+ } : {
204
+ ...from,
205
+ candidates
206
+ };
207
+ }
208
+ /**
209
+ * The `--from` that plans a failed migration again after its directory is deleted: the contract it
210
+ * started from, as `--from` names it in the graph without that migration.
211
+ */
212
+ function migrationPlanReplacing(space, failed) {
213
+ if (failed.from === "empty") return reference("@empty");
214
+ return startAtPosition({
215
+ graph: reconstructGraph(space.packages.filter(({ dirName }) => dirName !== failed.dirName)),
216
+ refs: space.refs
217
+ }, {
218
+ kind: "contract",
219
+ hash: failed.from
220
+ }).from;
221
+ }
222
+ /**
223
+ * The `migration plan` that takes the database at `marker` to `end`, with how it reaches `end`
224
+ * through migrations when the contract `end` names is known.
225
+ */
226
+ function migrationPlanForDatabase(space, marker, end) {
227
+ const position = databasePositionOf(marker?.storageHash);
228
+ const plan = migrationPlanArguments(space, position, end);
229
+ const target = planEndContract(space, end);
230
+ return {
231
+ ...plan,
232
+ position,
233
+ ...ifDefined("migrationsToTarget", target === void 0 ? void 0 : migrationsToTarget(space, marker, target))
234
+ };
235
+ }
236
+ /** The contract `end` names, with the invariants a ref requires; undefined when it is not known. */
237
+ function planEndContract(space, end) {
238
+ switch (end.kind) {
239
+ case "emitted": return space.emittedHash === void 0 ? void 0 : {
240
+ hash: space.emittedHash,
241
+ invariants: []
242
+ };
243
+ case "ref": return refNamed(space.refs, end.name);
244
+ case "contract": return {
245
+ hash: end.hash,
246
+ invariants: []
247
+ };
248
+ }
249
+ }
250
+ /** Where a database whose marker names `markerHash`, or that has none, is. */
251
+ function databasePositionOf(markerHash) {
252
+ if (markerHash === void 0) return { kind: "unmarked" };
253
+ return {
254
+ kind: "contract",
255
+ hash: markerHash
256
+ };
257
+ }
258
+ /**
259
+ * The application space of `aggregate`, as a {@link PlanSpace}, with `emitted.hash` as its
260
+ * `emittedHash`: by default the hash of the contract the run was given, the aggregate's.
261
+ */
262
+ function appSpaceOf(aggregate, emitted = { hash: aggregate.app.contract().storage.storageHash }) {
263
+ return {
264
+ spaceId: aggregate.app.spaceId,
265
+ graph: aggregate.app.graph(),
266
+ refs: aggregate.app.refs,
267
+ ...ifDefined("emittedHash", emitted.hash)
268
+ };
269
+ }
270
+ /**
271
+ * The `--from` that makes `migration plan` start where a run of it started: the `--from` it was
272
+ * given, or the origin it resolved by default, which is `@empty`, the `db` ref it baselined from, or
273
+ * the hash the `db` ref names.
274
+ */
275
+ function migrationPlanFromRun(optionsFrom, resolution) {
276
+ if (optionsFrom !== void 0) return reference(optionsFrom);
277
+ switch (resolution.kind) {
278
+ case "greenfield": return reference("@empty");
279
+ case "auto-baseline": return reference("db");
280
+ case "graph-node":
281
+ case "ref": return reference(resolution.fromHash);
282
+ }
283
+ }
14
284
  const SHELL_SAFE = /^[A-Za-z0-9_.:/@%+,-]+$/;
15
285
  /** The value as a shell passes it through unchanged, single-quoted when needed. */
16
286
  function shellQuoted(value) {
@@ -64,6 +334,7 @@ function rerunFlags(flags) {
64
334
  return [
65
335
  ...flags.to === void 0 ? [] : ["--to", shellQuoted(flags.to)],
66
336
  ...flags.advanceRef === void 0 ? [] : ["--advance-ref", shellQuoted(flags.advanceRef)],
337
+ ...flags.noAdvanceRef === true ? ["--no-advance-ref"] : [],
67
338
  ...flags.permitPolicyChange === true ? ["--permit-policy-change"] : []
68
339
  ];
69
340
  }
@@ -71,6 +342,25 @@ function rerunFlags(flags) {
71
342
  function dbMigrateRerun(invocation) {
72
343
  return cliCommand(invocation, "db migrate", invocation.rerunArgs ?? []);
73
344
  }
345
+ /**
346
+ * The `db migrate` that applies a migration planned after changing the contract source: it ends at
347
+ * the new emitted contract, so it leaves out the user's `--to` and the `--permit-policy-change`
348
+ * that goes with it, and keeps the other flags.
349
+ */
350
+ function dbMigrateToEmitted(invocation) {
351
+ const given = invocation.rerunArgs ?? [];
352
+ return cliCommand(invocation, "db migrate", given.filter((word, index) => word !== "--to" && given[index - 1] !== "--to" && word !== "--permit-policy-change"));
353
+ }
354
+ /**
355
+ * The `db migrate` that applies what a failed `db update` advises to plan to `to`. It repeats the
356
+ * flags the user gave `db update`, which `db migrate` takes with the same meaning: `--to`, and
357
+ * `--advance-ref` and `--permit-policy-change`, without which it would not do what `db update` was
358
+ * asked to. Without a `--to` among them, it takes the plan's.
359
+ */
360
+ function dbUpdateApplyCommand(invocation, to) {
361
+ const given = invocation?.rerunArgs ?? [];
362
+ return cliCommand(invocation, "db migrate", [...given.includes("--to") || to.kind === "none" ? [] : argumentWords("--to", to), ...given]);
363
+ }
74
364
  /** The `db update` the user ran, with the flags they gave and `statements`, by default the run's own. */
75
365
  function dbUpdateRerun(invocation, statements = invocation.statementArgs ?? []) {
76
366
  return cliCommand(invocation, "db update", [...invocation.rerunArgs ?? [], ...statements]);
@@ -105,13 +395,186 @@ function cliCommand(invocation, command, args = []) {
105
395
  ...invocation?.dbGiven === true && COMMANDS_TAKING_DB.has(command) ? ["--db", "<url>"] : []
106
396
  ].join(" ");
107
397
  }
398
+ /** A `migration plan` that starts at `from`, as advice prints it; `from` resolves as printed. */
399
+ function printedPlanCommand(invocation, from, flags) {
400
+ return cliCommand(invocation, "migration plan", [...argumentWords("--from", from), ...flags]);
401
+ }
402
+ /** What advice prints where `--from` is for the user to choose. */
403
+ const CONTRACT_PLACEHOLDER = "<contract>";
404
+ /** The `migration plan` that goes from `plan.from` to `plan.to` (the emitted contract when absent) with `flags`. */
405
+ function printedPlan(invocation, plan, flags) {
406
+ const { to = { kind: "default" } } = plan;
407
+ const from = carriesStatement(flags) ? migrationPlanFromForStatements(plan.from) : plan.from;
408
+ if (from.kind === "none" || to.kind === "none") return {
409
+ kind: "none",
410
+ reason: [from, to].flatMap((argument) => argument.kind === "none" ? [argument.reason] : []).join(". ")
411
+ };
412
+ const words = [...argumentWords("--to", to), ...flags];
413
+ return from.kind === "ambiguous" ? printedChoicePlan(invocation, from, words) : {
414
+ kind: "runs",
415
+ command: printedPlanCommand(invocation, from, words)
416
+ };
417
+ }
108
418
  /**
109
- * The `migration plan` command advice prints: it starts from `from`, the contract the database is
110
- * at, whenever that is known, because `migration plan` cannot find its origin without it once
111
- * migrations exist and no `db` ref names one.
419
+ * How advice moves the database `plan` describes to `plan.to`: with the `migration plan` from
420
+ * `plan.from` with `flags`, by applying migrations on disk, or why neither can. `apply` is the
421
+ * `db migrate` that applies the result, by default the one that follows `db update`.
112
422
  */
113
- function printedPlanCommand(invocation, from, flags) {
114
- return cliCommand(invocation, "migration plan", [...from === void 0 ? [] : ["--from", from], ...flags]);
423
+ function printedWayToTarget(invocation, plan, flags, apply = dbUpdateApplyCommand(invocation, plan.to)) {
424
+ const target = targetText(plan.to);
425
+ const migrations = plan.migrationsToTarget ?? {
426
+ kind: "plan-needed",
427
+ missingInvariants: []
428
+ };
429
+ switch (migrations.kind) {
430
+ case "none-needed": return {
431
+ kind: "at-target",
432
+ reason: `The database is already at ${target} and records every invariant it requires, so there is no migration to apply`
433
+ };
434
+ case "on-disk": {
435
+ const onDisk = `Migrations on disk already lead from the database to ${target}, so a migration planned now would be a second path between the same two contracts, and \`db migrate\` applies only one of them`;
436
+ const adoptFirst = noMarkerText(invocation, plan);
437
+ const reason = adoptFirst === void 0 ? onDisk : `${onDisk}. ${adoptFirst}`;
438
+ return {
439
+ kind: "on-disk",
440
+ reason,
441
+ apply,
442
+ text: `${reason}. Apply them with \`${apply}\`, which names the migration.ts to change if one of them fails`,
443
+ ...ifDefined("adoptFirst", adoptFirst)
444
+ };
445
+ }
446
+ case "at-target-missing-invariants": {
447
+ const { missingInvariants, newMigration } = migrations;
448
+ const finish = (migrationTs) => `add to ${migrationTs} ${transformsText(missingInvariants)}, run \`${writtenMigrationRunCommand(invocation)}\` for its directory, and apply it with \`${apply}\``;
449
+ return {
450
+ kind: "none",
451
+ reason: `The database is at ${target}, but no migration on disk provides ${invariantsText(missingInvariants)} it requires and the database does not record, and a plan from a contract to itself is empty. ${selfMigrationText(invocation, target, newMigration, finish)}`
452
+ };
453
+ }
454
+ case "plan-needed": {
455
+ const adoptFirst = noMarkerText(invocation, plan);
456
+ if (plan.startsAfterUnapplied === true && carriesStatement(flags) && plan.from.kind !== "none" && !(plan.from.kind === "reference" && plan.from.reference === "@empty")) return applyUnappliedFirst(invocation, plan.from, adoptFirst);
457
+ const printed = printedPlan(invocation, plan, flags);
458
+ if (printed.kind === "none") return printed;
459
+ const { missingInvariants } = migrations;
460
+ const run = `${missingInvariants.length === 0 ? "" : `add to it ${transformsText(missingInvariants)}, `}run \`${writtenMigrationRunCommand(invocation)}\` for the directory it writes`;
461
+ return {
462
+ ...printed,
463
+ afterPlan: adoptFirst === void 0 ? `${run}, and apply it with \`${apply}\`` : `${run}. ${adoptFirst}. Then apply it with \`${apply}\``
464
+ };
465
+ }
466
+ }
467
+ }
468
+ /**
469
+ * For a database with no marker in a space with migrations, why `db migrate` fits it only when it
470
+ * is empty, and how to adopt it when it is not.
471
+ */
472
+ function noMarkerText(invocation, plan) {
473
+ if (plan.position?.kind !== "unmarked" || plan.startsAfterUnapplied !== true) return void 0;
474
+ return noMarkerReplayText(cliCommand(invocation, "db sign", [CONTRACT_PLACEHOLDER]), cliCommand(invocation, "migration list"));
475
+ }
476
+ /**
477
+ * Why advice that carries a statement prints no plan from `from`, past migrations on disk the
478
+ * database has not applied: one of them may already make the change. It says to apply them first,
479
+ * after `adoptFirst` for a database with no marker, then run the command again. It never offers
480
+ * `@empty` as where to apply them to, since that empties the database.
481
+ */
482
+ function applyUnappliedFirst(invocation, from, adoptFirst) {
483
+ const lead = "Migrations on disk that the database has not applied come before where a plan for this change would start, and one of them may already make the change, so the plan could not carry it";
484
+ const candidates = from.kind === "ambiguous" ? from.candidates.filter((each) => each !== "@empty") : [];
485
+ const [onlyCandidate] = candidates;
486
+ const end = from.kind === "reference" ? from.reference : candidates.length === 1 && onlyCandidate !== void 0 ? onlyCandidate : CONTRACT_PLACEHOLDER;
487
+ const runs = end !== CONTRACT_PLACEHOLDER;
488
+ const command = cliCommand(invocation, "db migrate", ["--to", runs ? shellQuoted(end) : end]);
489
+ const apply = `Apply them first with ${`\`${command}\``}${!runs && candidates.length > 0 ? `, replacing ${CONTRACT_PLACEHOLDER} with one of ${candidates.map((each) => `\`${each}\``).join(", ")}` : ""}, which names the migration.ts to change if one of them fails, then run the command again`;
490
+ return {
491
+ kind: "none",
492
+ reason: adoptFirst === void 0 ? `${lead}. ${apply}` : `${lead}. ${adoptFirst}. ${apply}`,
493
+ applyFirst: {
494
+ command,
495
+ runs,
496
+ text: apply,
497
+ ...ifDefined("adoptFirst", adoptFirst)
498
+ }
499
+ };
500
+ }
501
+ /**
502
+ * How to write a migration from `target`, the contract the database is at, to itself, then
503
+ * `finish` it, given the words that name its migration.ts.
504
+ */
505
+ function selfMigrationText(invocation, target, newMigration, finish) {
506
+ if (newMigration === void 0) return `Write a migration from that contract to itself, ${finish("its migration.ts")}`;
507
+ const command = `\`${cliCommand(invocation, "migration new", ["--from", newMigration.from])}\``;
508
+ if (!newMigration.emitFirst) return `Write a migration from that contract to itself with ${command}, ${finish("its migration.ts")}`;
509
+ const emit = `\`${cliCommand(invocation, "contract emit")}\``;
510
+ return `Change your contract source so it describes ${target} and run ${emit}, then write a migration from that contract to itself with ${command}. Then change your contract source back and run ${emit} again, because \`db update\` and \`migration plan\` target the emitted contract. Then ${finish("the new migration's migration.ts")}`;
511
+ }
512
+ function targetText(to) {
513
+ switch (to.kind) {
514
+ case "reference": return `\`${to.reference}\``;
515
+ case "default": return "the emitted contract";
516
+ case "none": return "the contract the run moves it to";
517
+ }
518
+ }
519
+ function quotedInvariants(invariants) {
520
+ return invariants.map((id) => JSON.stringify(id)).join(", ");
521
+ }
522
+ function invariantsText(invariants) {
523
+ return `${invariants.length === 1 ? "the invariant" : "the invariants"} ${quotedInvariants(invariants)}`;
524
+ }
525
+ /** The `dataTransform` operations that provide `invariants`: each carries one `invariantId`. */
526
+ function transformsText(invariants) {
527
+ return invariants.length === 1 ? `a \`dataTransform\` with \`invariantId\` ${quotedInvariants(invariants)}` : `a \`dataTransform\` for each of the invariants ${quotedInvariants(invariants)}, with that invariant as its \`invariantId\``;
528
+ }
529
+ const STATEMENT_FLAGS = /* @__PURE__ */ new Set([
530
+ "--rename",
531
+ "--delete",
532
+ "--convert",
533
+ "--backfill"
534
+ ]);
535
+ function carriesStatement(flags) {
536
+ return flags.some((flag) => STATEMENT_FLAGS.has(flag.split(/[\s=]/)[0] ?? ""));
537
+ }
538
+ /**
539
+ * A `migration plan` whose `--from` the user chooses, for `choice.reason`, from `choice.candidates`:
540
+ * with one candidate, the command names it and the reason says when it fits.
541
+ */
542
+ function printedChoicePlan(invocation, choice, flags) {
543
+ const [only] = choice.candidates;
544
+ if (choice.candidates.length === 1 && only !== void 0) return {
545
+ kind: "fill",
546
+ command: printedPlanCommand(invocation, {
547
+ kind: "reference",
548
+ reference: only
549
+ }, flags),
550
+ fill: choice.reason
551
+ };
552
+ const statements = carriesStatement(flags);
553
+ const choices = choice.candidates.length > 0 ? `one of ${choice.candidates.map((candidate) => `\`${candidate}\``).join(", ")}` : `a contract \`${cliCommand(invocation, "migration list")}\` shows${statements ? " or a ref that names one" : ", a ref that names one, or `@empty`"}`;
554
+ return {
555
+ kind: "fill",
556
+ command: cliCommand(invocation, "migration plan", [
557
+ "--from",
558
+ CONTRACT_PLACEHOLDER,
559
+ ...flags
560
+ ]),
561
+ fill: `${choice.reason}, so replace ${CONTRACT_PLACEHOLDER} with ${choices}`
562
+ };
563
+ }
564
+ /** `plan` quoted for a sentence: its command, followed for `fill` by what to put in its placeholder. */
565
+ function quotedPlan(plan) {
566
+ return plan.kind === "runs" ? `\`${plan.command}\`` : `\`${plan.command}\` (${plan.fill})`;
567
+ }
568
+ /** The next action for `plan`: a command when it runs, otherwise the choice or the reason it has none. */
569
+ function planAction(label, plan) {
570
+ switch (plan.kind) {
571
+ case "runs": return runCommandAction(label, plan.command);
572
+ case "fill": return chooseAction(`${label} with \`${plan.command}\`. ${plan.fill}.`);
573
+ case "none": return chooseAction(plan.reason);
574
+ }
575
+ }
576
+ function argumentWords(flag, argument) {
577
+ return argument.kind === "reference" ? [flag, shellQuoted(argument.reference)] : [];
115
578
  }
116
579
  /**
117
580
  * The command that runs a `migration.ts`, named relative to the directory the CLI ran in, with the
@@ -129,7 +592,7 @@ function writtenMigrationRunCommand(invocation) {
129
592
  return [
130
593
  "node",
131
594
  "<migration directory>/migration.ts",
132
- ...configWords(invocation.configPath)
595
+ ...configWords(invocation?.configPath)
133
596
  ].join(" ");
134
597
  }
135
598
  /** A path as advice prints it: relative to the directory the CLI ran in. */
@@ -184,6 +647,18 @@ function errorAdvanceRefArgConflict(options) {
184
647
  meta: { advanceRef: options.advanceRef }
185
648
  });
186
649
  }
650
+ /**
651
+ * `db migrate --advance-ref <name>` targets the empty contract, which a ref cannot name, so the ref
652
+ * could never be written. Raised before anything is applied.
653
+ */
654
+ function errorRefTargetEmpty(options) {
655
+ return new ActionableCliError("MIGRATION.REF_TARGET_EMPTY", `Cannot advance ref "${options.name}" to the empty contract`, {
656
+ why: "This run would bring the database to the empty contract. The empty contract is where the planner starts, not a contract a ref can name, so the ref could never be written. Nothing was applied.",
657
+ fix: "Run the command again without --advance-ref.",
658
+ nextActions: [runCommandAction("Apply without advancing a ref", options.rerunWithoutRef)],
659
+ meta: { name: options.name }
660
+ });
661
+ }
187
662
  function quotedSpaces(spaces) {
188
663
  return spaces.map((space) => `"${space}"`).join(", ");
189
664
  }
@@ -332,10 +807,29 @@ function errorRefSetBundleNotFound(hash) {
332
807
  meta: { hash }
333
808
  });
334
809
  }
335
- function errorPlanForgotTheFlag(resolvedHash, reachableRefs, options) {
810
+ /**
811
+ * The choices a refusal of `migration plan`'s origin gives, for `reason`: a plan from a contract
812
+ * `migration plan` can start from, and the `db` ref pointed at one, which `migration ref set` takes only for a
813
+ * contract a migration records.
814
+ */
815
+ function originChoices(space, reason, invocation) {
816
+ const choice = migrationPlanChoice(space, reason);
817
+ const refTargets = choice.candidates.filter((candidate) => candidate !== "@empty");
818
+ const refChoice = `Point the db ref at the contract your database is at with \`${cliCommand(invocation, "migration ref set", ["db", CONTRACT_PLACEHOLDER])}\`, replacing ${CONTRACT_PLACEHOLDER} with ${refTargets.length > 0 ? `one of ${refTargets.map((target) => `\`${target}\``).join(", ")}` : `a contract \`${cliCommand(invocation, "migration list")}\` shows`}`;
819
+ return {
820
+ plan: printedChoicePlan(invocation, choice, []),
821
+ refChoice
822
+ };
823
+ }
824
+ function planFromCommand(invocation, from) {
825
+ return cliCommand(invocation, "migration plan", ["--from", shellQuoted(from)]);
826
+ }
827
+ function errorPlanForgotTheFlag(resolvedHash, reachableRefs, space, options) {
828
+ const invocation = options?.invocation;
336
829
  const reachableList = reachableRefs.length > 0 ? reachableRefs.map((r) => `${r.name} (${r.hash})`).join(", ") : "(none)";
337
- const refFix = reachableRefs.length > 0 ? `Run migration plan with ${reachableRefs.map((r) => `--from ${r.name}`).join(" or ")}.` : "Pass --from <contract> naming the `to` hash of an on-disk migration (`{bin} migration list` shows them), or point the db ref at one with `{bin} migration ref set db <contract>`.";
338
- const nextActions = reachableRefs.length > 0 ? reachableRefs.map((ref) => runCommandAction(`Plan from ${ref.name}`, `{bin} migration plan --from ${ref.name}`)) : [runCommandAction("Plan from an explicit origin", "{bin} migration plan --from <contract>"), runCommandAction("Point the db ref at a graph node", "{bin} migration ref set db <contract>")];
830
+ const { plan: explicit, refChoice } = originChoices(space, `No migration records contract ${resolvedHash}`, invocation);
831
+ const refFix = reachableRefs.length > 0 ? `Run migration plan with ${reachableRefs.map((r) => `--from ${r.name}`).join(" or ")}.` : `Plan from a contract a migration records with \`${explicit.command}\`: ${explicit.fill}. Or ${refChoice.charAt(0).toLowerCase()}${refChoice.slice(1)}.`;
832
+ const nextActions = reachableRefs.length > 0 ? reachableRefs.map((ref) => runCommandAction(`Plan from ${ref.name}`, planFromCommand(invocation, ref.name))) : [planAction("Plan from an explicit origin", explicit), chooseAction(refChoice)];
339
833
  return new ActionableCliError("MIGRATION.HASH_NOT_IN_GRAPH", `Resolved from-hash is not in the migration graph: ${resolvedHash}`, {
340
834
  why: `The migration graph reaches ${reachableList}; resolved ${resolvedHash} isn't a graph node.`,
341
835
  fix: refFix,
@@ -380,20 +874,20 @@ function errorSnapshotMissing(identifier, options) {
380
874
  * produce an empty-origin migration that ignores the existing history — almost
381
875
  * always a mistake — so the command refuses and names the three exits.
382
876
  */
383
- function errorPlanOriginUnknown(reachableRefs) {
384
- const fromSuggestion = reachableRefs.length > 0 ? reachableRefs.map((r) => `--from ${r.name}`).join(" or ") : "--from <contract>";
385
- const refSetCommand = "{bin} migration ref set db <contract>";
877
+ function errorPlanOriginUnknown(reachableRefs, space, invocation) {
878
+ const { plan: explicit, refChoice } = originChoices(space, "No `db` ref and no --from say where the plan starts", invocation);
879
+ const fromEmpty = planFromCommand(invocation, "@empty");
386
880
  return new ActionableCliError("MIGRATION.PLAN_ORIGIN_UNKNOWN", "Cannot determine the plan origin: migrations exist but no origin is named", {
387
881
  why: "Migrations exist on disk, but there is no `db` ref and no --from was given, so the plan origin would silently fall back to an empty database and the resulting migration would recreate everything the existing migrations already create.",
388
882
  fix: [
389
- `Set the \`db\` ref to the contract your database is at (\`${refSetCommand}\`), or, on a database whose migration history does not need to be kept, advance it via \`{bin} db update\`.`,
390
- `Or pass the origin explicitly: \`{bin} migration plan ${fromSuggestion}\`.`,
883
+ `${refChoice}, or, on a database whose migration history does not need to be kept, advance it via \`${cliCommand(invocation, "db update")}\`.`,
884
+ reachableRefs.length > 0 ? `Or pass the origin explicitly: ${reachableRefs.map((r) => `\`${planFromCommand(invocation, r.name)}\``).join(" or ")}.` : `Or pass the origin explicitly: \`${explicit.command}\`. ${explicit.fill}.`,
391
885
  "Or pass --from @empty to deliberately plan from an empty database."
392
886
  ].join("\n"),
393
887
  nextActions: [
394
- runCommandAction("Point the db ref at the origin contract", refSetCommand),
395
- ...reachableRefs.length > 0 ? reachableRefs.map((ref) => runCommandAction(`Plan from ${ref.name}`, `{bin} migration plan --from ${ref.name}`)) : [runCommandAction("Plan from an explicit origin", `{bin} migration plan ${fromSuggestion}`)],
396
- runCommandAction("Plan from an empty database deliberately", "{bin} migration plan --from @empty")
888
+ chooseAction(refChoice),
889
+ ...reachableRefs.length > 0 ? reachableRefs.map((ref) => runCommandAction(`Plan from ${ref.name}`, planFromCommand(invocation, ref.name))) : [planAction("Plan from an explicit origin", explicit)],
890
+ runCommandAction("Plan from an empty database deliberately", fromEmpty)
397
891
  ],
398
892
  meta: { reachableRefs: reachableRefs.map((r) => r.name) }
399
893
  });
@@ -473,9 +967,8 @@ const MIGRATION_PLAN_VERBS = [
473
967
  * `refused`, `--convert` or `--backfill` statements that ask for code the user writes, were given
474
968
  * to `db update`, which applies its plan directly and so has no migration file whose slot the user
475
969
  * could fill. `statements` are every statement the user gave, in the order given: the `migration
476
- * plan` command the error suggests carries each one that command accepts, and starts from
477
- * `databaseStorageHash`, the contract the database is at, when it is known. Its commands repeat the
478
- * `--config` of `invocation`.
970
+ * plan` command the error suggests carries each one that command accepts, from `origin`; when no plan
971
+ * can start there, the error says why and suggests none. Its commands repeat the `--config` of `invocation`.
479
972
  */
480
973
  function needsMigrationFileReason(refused) {
481
974
  const converts = refused.some(({ verb }) => verb === "convert");
@@ -483,14 +976,57 @@ function needsMigrationFileReason(refused) {
483
976
  if (converts && backfills) return "--convert of a field and --backfill ask for a migration file with a slot for the code that converts the values or the value that fills the field";
484
977
  return converts ? "--convert of a field asks for a migration file with a slot for the code that converts its values" : "--backfill asks for a migration file with a slot for the value that fills the field";
485
978
  }
486
- function errorStatementNeedsMigrationFile(statements, refused, invocation, databaseStorageHash) {
979
+ function errorStatementNeedsMigrationFile(statements, refused, invocation, migrationPlan) {
487
980
  const written = refused.map(({ verb, text }) => `"--${verb} ${text}"`);
488
981
  const listed = written.length === 1 ? written[0] : `${written.slice(0, -1).join(", ")} and ${written.at(-1)}`;
489
- const plan = printedPlanCommand(invocation, databaseStorageHash, statements.filter(({ verb }) => MIGRATION_PLAN_VERBS.includes(verb)).map(statementFlag));
982
+ const why = `${needsMigrationFileReason(refused)}, and db update has no migration file to fill: it applies its plan directly.`;
983
+ const plan = printedWayToTarget(invocation, migrationPlan, statements.filter(({ verb }) => MIGRATION_PLAN_VERBS.includes(verb)).map(statementFlag));
984
+ if (plan.kind === "on-disk") {
985
+ const edit = "Write what these statements ask for in the migration.ts of the migration on disk that changes the field, and run that migration.ts with `node`";
986
+ return new ActionableCliError("MIGRATION.STATEMENT_NEEDS_MIGRATION_FILE", `db update cannot carry out ${listed}`, {
987
+ why: `${why} ${plan.reason}.`,
988
+ fix: plan.adoptFirst === void 0 ? `${edit}, then apply the migrations with \`${plan.apply}\`. Or leave out these statements: db update then asks before it loses any data.` : `${edit}. ${plan.adoptFirst}. Then apply the migrations with \`${plan.apply}\`. Or leave out these statements: db update then asks before it loses any data.`,
989
+ nextActions: [
990
+ chooseAction(edit),
991
+ ...plan.adoptFirst === void 0 ? [] : [chooseAction(plan.adoptFirst)],
992
+ runCommandAction("Then apply the migrations on disk", plan.apply),
993
+ chooseAction("Or run db update without these statements")
994
+ ],
995
+ meta: { statements: refused.map(({ verb, text }) => ({
996
+ verb,
997
+ text
998
+ })) }
999
+ });
1000
+ }
1001
+ if (plan.kind === "none" && plan.applyFirst !== void 0) {
1002
+ const { command, runs, text: applyText, adoptFirst } = plan.applyFirst;
1003
+ return new ActionableCliError("MIGRATION.STATEMENT_NEEDS_MIGRATION_FILE", `db update cannot carry out ${listed}`, {
1004
+ why: `${why} ${plan.reason}.`,
1005
+ fix: `${plan.reason}. Or leave out these statements: db update then asks before it loses any data.`,
1006
+ nextActions: [
1007
+ ...adoptFirst === void 0 ? [] : [chooseAction(adoptFirst)],
1008
+ runs ? runCommandAction("Apply the migrations on disk the database has not applied, then run the command again", command) : chooseAction(applyText),
1009
+ chooseAction("Or run db update without these statements")
1010
+ ],
1011
+ meta: { statements: refused.map(({ verb, text }) => ({
1012
+ verb,
1013
+ text
1014
+ })) }
1015
+ });
1016
+ }
1017
+ if (plan.kind === "none" || plan.kind === "at-target") return new ActionableCliError("MIGRATION.STATEMENT_NEEDS_MIGRATION_FILE", `db update cannot carry out ${listed}`, {
1018
+ why: `${why} No migration can be planned for them either. ${plan.reason}.`,
1019
+ fix: "Leave out these statements: db update then asks before it loses any data.",
1020
+ nextActions: [chooseAction("Run db update without these statements")],
1021
+ meta: { statements: refused.map(({ verb, text }) => ({
1022
+ verb,
1023
+ text
1024
+ })) }
1025
+ });
490
1026
  return new ActionableCliError("MIGRATION.STATEMENT_NEEDS_MIGRATION_FILE", `db update cannot carry out ${listed}`, {
491
- why: `${needsMigrationFileReason(refused)}, and db update has no migration file to fill: it applies its plan directly.`,
492
- fix: `Plan the change with ${plan}, fill in the migration.ts it writes, run that migration.ts with the \`node\` command \`migration plan\` prints, and apply it with ${cliCommand(invocation, "db migrate")}. Or leave out these statements: db update then asks before it loses any data.`,
493
- nextActions: [runCommandAction("Plan the change into a migration file to fill in", plan), chooseAction("Or run db update without these statements")],
1027
+ why,
1028
+ fix: `Plan the change with ${quotedPlan(plan)}, fill in the migration.ts it writes, ${plan.afterPlan}. Or leave out these statements: db update then asks before it loses any data.`,
1029
+ nextActions: [planAction("Plan the change into a migration file to fill in", plan), chooseAction("Or run db update without these statements")],
494
1030
  meta: { statements: refused.map(({ verb, text }) => ({
495
1031
  verb,
496
1032
  text
@@ -606,36 +1142,30 @@ function errorPlanProducedNoOperations(destination) {
606
1142
  const ROLLBACK_IS_DESTRUCTIVE = "A rollback (reverse) plan is expected to contain destructive (DROP) operations — review them before applying";
607
1143
  const RENAMES_AND_DATA_NEED_MORE = "Plan a rename with --rename old:new; re-adding a required field without a safe default, or a type change that needs data, may need you to fill in the planned migration.ts";
608
1144
  /**
609
- * The advice to plan the missing migration in the app space and apply it. `toArgument` is what
610
- * `--to` takes to name the target, or `undefined` for the emitted contract: `migration plan` and
611
- * `db migrate` target it without `--to`, and `migration plan --to` resolves only a contract that a
612
- * migration or a ref names. A space with no migrations has no such contract, so neither of its
613
- * commands carries `--to`. Otherwise the apply step is the `db migrate` the user ran, when its flags
614
- * are known.
1145
+ * The advice to plan the missing migration in the app space and apply it, or, when no `migration
1146
+ * plan` can author it, why not. The apply step is the `db migrate` the user ran, when its flags are
1147
+ * known.
615
1148
  */
616
- function planThenApply(meta, toArgument, invocation) {
617
- const from = meta.kind === "neverPlanned" || meta.fromHash === "empty" ? void 0 : meta.fromHash;
618
- const to = meta.kind === "neverPlanned" || toArgument === void 0 ? [] : ["--to", toArgument];
619
- const planCommand = printedPlanCommand(invocation, from, [
620
- ...to,
621
- "--name",
622
- "<slug>"
623
- ]);
624
- const applyCommand = meta.kind === "neverPlanned" ? cliCommand(invocation, "db migrate") : cliCommand(invocation, "db migrate", invocation.rerunArgs ?? to);
1149
+ function planThenApply(plan, invocation) {
1150
+ const printed = printedPlan(invocation, plan, []);
1151
+ if (printed.kind === "none") return noPlanReaches(printed.reason, invocation);
1152
+ const to = plan.to.kind === "reference" ? ["--to", shellQuoted(plan.to.reference)] : [];
1153
+ const planStep = printed.kind === "runs" ? printed.command : `${printed.command}\n ${printed.fill}.`;
1154
+ const applyCommand = cliCommand(invocation, "db migrate", invocation.rerunArgs ?? to);
625
1155
  const listCommand = cliCommand(invocation, "migration list");
626
1156
  const showCommand = cliCommand(invocation, "migration show", ["<bundle>"]);
627
1157
  return {
628
1158
  fix: [
629
1159
  "Plan the missing edge, then apply it:",
630
- ` 1. ${planCommand}`,
1160
+ ` 1. ${planStep}`,
631
1161
  ` 2. ${applyCommand}`,
632
1162
  `${ROLLBACK_IS_DESTRUCTIVE}.`,
633
1163
  `${RENAMES_AND_DATA_NEED_MORE}.`,
634
1164
  `Inspect the on-disk graph with \`${listCommand}\`, or \`${showCommand}\` for any bundle in the path you expected.`
635
1165
  ].join("\n"),
636
1166
  nextActions: [
637
- runCommandAction("Plan the missing edge", planCommand),
638
- runCommandAction("Apply it", applyCommand),
1167
+ planAction("Plan the missing edge", printed),
1168
+ printed.kind === "runs" ? runCommandAction("Apply it", applyCommand) : chooseAction(`Then apply it with \`${applyCommand}\``),
639
1169
  chooseAction(ROLLBACK_IS_DESTRUCTIVE),
640
1170
  chooseAction(RENAMES_AND_DATA_NEED_MORE),
641
1171
  runCommandAction("Inspect the on-disk graph", listCommand),
@@ -643,6 +1173,17 @@ function planThenApply(meta, toArgument, invocation) {
643
1173
  ]
644
1174
  };
645
1175
  }
1176
+ /**
1177
+ * The advice when no `migration plan` can author the missing path: `reason` says why, and the
1178
+ * advice points at the graph.
1179
+ */
1180
+ function noPlanReaches(reason, invocation) {
1181
+ const listCommand = cliCommand(invocation, "migration list");
1182
+ return {
1183
+ fix: [`${reason}.`, `Inspect the on-disk graph with \`${listCommand}\`.`].join("\n"),
1184
+ nextActions: [chooseAction(reason), runCommandAction("Inspect the on-disk graph", listCommand)]
1185
+ };
1186
+ }
646
1187
  /** `MIGRATION.UNFILLED_PLACEHOLDER` from `db migrate`: a migration to apply still has `placeholder(...)` calls, so its `ops.json` lacks their operations. */
647
1188
  function errorMigrationHasUnfilledPlaceholders(directory, invocation) {
648
1189
  const migrationTs = join(directory, "migration.ts");
@@ -1077,6 +1618,6 @@ function diagnosticWithoutConnectionString(diagnostic, connection) {
1077
1618
  };
1078
1619
  }
1079
1620
  //#endregion
1080
- export { errorStatementInvalid as $, errorFileNotFound as A, errorPathUnreachable as B, errorContractArgConflict as C, statementFlag as Ct, errorConvertAndDelete as D, errorContractValidationFailed as E, writtenMigrationRunCommand as Et, errorMarkerMissing as F, errorRefSetEmptySentinel as G, errorPlanOriginUnknown as H, errorMigrationHasUnfilledPlaceholders as I, errorSignRefsNotWritten as J, errorRefSetHashNotInGraph as K, errorMigrationPackageNotFound as L, errorHashMismatch as M, errorInvalidSpaceId as N, errorDatabaseConnectionRequired as O, errorLegendHumanOnly as P, errorStatementDidNotResolveLoss as Q, errorMigrationPlanningFailed as R, errorConsentUnused as S, shellQuoted as St, errorContractTypesModuleMissing as T, toStructuralEdge as Tt, errorPlanProducedNoOperations as U, errorPlanForgotTheFlag as V, errorRefSetBundleNotFound as W, errorSpaceNotFound as X, errorSnapshotMissing as Y, errorStatementAnswersNoQuestion as Z, displayPath as _, rerunFlags as _t, appRefsDirFor as a, errorUnexpected as at, errorAmbiguousMigrationRef as b, runCommandAction as bt, cliCommand as c, maskConnectionUrl as ct, closeQuietly as d, planThenApply as dt, errorStatementNeedsMigrationFile as et, collectDeclaredInvariants as f, printedPath as ft, dbUpdateRerun as g, requireLiveDatabase as gt, dbMigrateRerun as h, redactUrlCredentials as ht, appMigrationsDirFor as i, errorTargetMismatch as it, errorFromCaught as j, errorDriverRequired as k, cliErrorFromStructured as l, migrationModuleOf as lt, contractTypesModuleOf as m, readContractEnvelope as mt, CliStructuredError$1 as n, errorStatementUnresolved as nt, baseDirFor as o, getTargetMigrations as ot, contractPathFor as p, printedPlanCommand as pt, errorRuntime as q, STORE_ORIGIN_SNAPSHOT_STEPS as r, errorTargetMigrationNotSupported as rt, chooseAction as s, mapRefResolutionError as st, ActionableCliError as t, errorStatementOriginUnknown as tt, cliInvocation as u, migrationsDirFor as ut, editFileAction as v, resolveContractPath as vt, errorContractConfigMissing as w, targetSupportsMigrations as wt, errorConfigValidation$1 as x, selfEmitCommand as xt, errorAdvanceRefArgConflict as y, resolveMigrationPaths as yt, errorNoMigrations as z };
1621
+ export { errorSignRefsNotWritten as $, errorContractValidationFailed as A, redactUrlCredentials as At, errorMigrationHasUnfilledPlaceholders as B, toStructuralEdge as Bt, errorAdvanceRefArgConflict as C, planAction as Ct, errorContractArgConflict as D, printedWayToTarget as Dt, errorConsentUnused as E, printedPlan as Et, errorFromCaught as F, runCommandAction as Ft, errorPlanForgotTheFlag as G, errorMigrationPlanningFailed as H, errorHashMismatch as I, selfEmitCommand as It, errorRefSetBundleNotFound as J, errorPlanOriginUnknown as K, errorInvalidSpaceId as L, shellQuoted as Lt, errorDatabaseConnectionRequired as M, rerunFlags as Mt, errorDriverRequired as N, resolveContractPath as Nt, errorContractConfigMissing as O, quotedPlan as Ot, errorFileNotFound as P, resolveMigrationPaths as Pt, errorRuntime as Q, errorLegendHumanOnly as R, statementFlag as Rt, editFileAction as S, migrationsDirFor as St, errorConfigValidation$1 as T, printedPath as Tt, errorNoMigrations as U, errorMigrationPackageNotFound as V, writtenMigrationRunCommand as Vt, errorPathUnreachable as W, errorRefSetHashNotInGraph as X, errorRefSetEmptySentinel as Y, errorRefTargetEmpty as Z, databasePositionOf as _, migrationPlanChoice as _t, appMigrationsDirFor as a, errorStatementNeedsMigrationFile as at, dbUpdateRerun as b, migrationPlanReplacing as bt, baseDirFor as c, errorTargetMigrationNotSupported as ct, cliErrorFromStructured as d, getTargetMigrations as dt, errorSnapshotMissing as et, cliInvocation as f, hasMigrationPath as ft, contractTypesModuleOf as g, migrationPlanArguments as gt, contractPathFor as h, migrationModuleOf as ht, STORE_ORIGIN_SNAPSHOT_STEPS as i, errorStatementInvalid as it, errorConvertAndDelete as j, requireLiveDatabase as jt, errorContractTypesModuleMissing as k, readContractEnvelope as kt, chooseAction as l, errorTargetMismatch as lt, collectDeclaredInvariants as m, maskConnectionUrl as mt, CONTRACT_PLACEHOLDER as n, errorStatementAnswersNoQuestion as nt, appRefsDirFor as o, errorStatementOriginUnknown as ot, closeQuietly as p, mapRefResolutionError as pt, errorPlanProducedNoOperations as q, CliStructuredError$1 as r, errorStatementDidNotResolveLoss as rt, appSpaceOf as s, errorStatementUnresolved as st, ActionableCliError as t, errorSpaceNotFound as tt, cliCommand as u, errorUnexpected as ut, dbMigrateRerun as v, migrationPlanForDatabase as vt, errorAmbiguousMigrationRef as w, planThenApply as wt, displayPath as x, migrationPlanTo as xt, dbMigrateToEmitted as y, migrationPlanFromRun as yt, errorMarkerMissing as z, targetSupportsMigrations as zt };
1081
1622
 
1082
- //# sourceMappingURL=caught-errors-D_pbHqmS-B-4jRN6g.mjs.map
1623
+ //# sourceMappingURL=caught-errors-DZXnK8Ls-zVmM4nr3.mjs.map