@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,41 +1,41 @@
1
- import { a as expandContractInputs } from "./exports-CZ6dPu-O.mjs";
1
+ import { a as expandContractInputs } from "./exports-DNFYCa6U.mjs";
2
2
  import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
3
- import { D as errorNoInvariantPath, M as errorUnknownInvariant, b as errorInvalidRefName, r as errorContractDeserializationFailed, t as MigrationToolsError, y as errorInvalidRefFile } from "./errors-BMq40nYH-Cg8PBect.mjs";
3
+ import { D as errorNoInvariantPath, M as errorUnknownInvariant, b as errorInvalidRefName, r as errorContractDeserializationFailed, t as MigrationToolsError, y as errorInvalidRefFile } from "./errors-BlaB9AFz-CZDOC0mV.mjs";
4
+ import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-ClCmhVjf-8XCns4rf.mjs";
5
+ import { i as findPathWithDecision, r as findPath } from "./migration-graph-DBJAol1y-DX61Ss3X.mjs";
4
6
  import { r as verifyMigrationHash, t as computeMigrationHash } from "./hash-BAZVWU4a-BQovI7hF.mjs";
5
- import { c as writeContractSnapshot, i as readContractSnapshotJson, r as createSnapshotContentVerifier, s as snapshotsImportPathFrom, t as contractSnapshotDir } from "./contract-snapshot-store-B0fRbVHB-BN2g8BKh.mjs";
6
- import { t as deriveProvidedInvariants } from "./invariants-DxCj82g2-DhGkStla.mjs";
7
- import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigrationDirName, u as writeMigrationPackage } from "./io-B39zsxMm-D5Wcf6cf.mjs";
8
- import { i as findPathWithDecision, r as findPath } from "./migration-graph-BoiiZAaU-DLht12k7.mjs";
9
- import { c as readContractSpaceHeadRef, l as spaceMigrationDirectory, o as isValidSpaceId, s as listContractSpaceDirectories, t as APP_SPACE_ID$1, u as spaceRefsDirectory } from "./verify-contract-spaces-BOnqhfQs-BBq5YOKo.mjs";
10
- import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-OVZ0QzWJ.mjs";
11
- import { $ as errorStatementInvalid, A as errorFileNotFound, B as errorPathUnreachable, Ct as statementFlag, E as errorContractValidationFailed, Et as writtenMigrationRunCommand, G as errorRefSetEmptySentinel, H as errorPlanOriginUnknown, I as errorMigrationHasUnfilledPlaceholders, K as errorRefSetHashNotInGraph, N as errorInvalidSpaceId, Q as errorStatementDidNotResolveLoss, R as errorMigrationPlanningFailed, S as errorConsentUnused, St as shellQuoted, T as errorContractTypesModuleMissing, Tt as toStructuralEdge, U as errorPlanProducedNoOperations, V as errorPlanForgotTheFlag, W as errorRefSetBundleNotFound, X as errorSpaceNotFound, Y as errorSnapshotMissing, Z as errorStatementAnswersNoQuestion, at as errorUnexpected, b as errorAmbiguousMigrationRef, bt as runCommandAction, c as cliCommand, d as closeQuietly, dt as planThenApply, et as errorStatementNeedsMigrationFile, f as collectDeclaredInvariants, ft as printedPath, g as dbUpdateRerun, gt as requireLiveDatabase, h as dbMigrateRerun, j as errorFromCaught, l as cliErrorFromStructured, lt as migrationModuleOf, m as contractTypesModuleOf, mt as readContractEnvelope, n as CliStructuredError$1, nt as errorStatementUnresolved, ot as getTargetMigrations, pt as printedPlanCommand, q as errorRuntime, r as STORE_ORIGIN_SNAPSHOT_STEPS, rt as errorTargetMigrationNotSupported, s as chooseAction, st as mapRefResolutionError, t as ActionableCliError, tt as errorStatementOriginUnknown, ut as migrationsDirFor, v as editFileAction, vt as resolveContractPath, w as errorContractConfigMissing, x as errorConfigValidation$1, xt as selfEmitCommand, yt as resolveMigrationPaths } from "./caught-errors-D_pbHqmS-B-4jRN6g.mjs";
12
- import { r as getEmittedArtifactPaths, t as emit } from "./exports-CCuYD8dO-yw1GizAT.mjs";
13
- import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-D7m41lWA-B68g1CRS.mjs";
14
- import { a as readRefs, d as validateRefValue, n as advanceRef, r as deleteRef, s as refsByContractHash, t as HEAD_REF_NAME, u as validateRefName } from "./refs-t_JbIjGo-BVCqKpXd.mjs";
15
- import { a as contractHashAtMarker, c as loadContractSpaceAggregate, d as requireHeadRef, f as resolveRecordedPath, m as verifyMigration, n as buildFabricatedMigrationEdge, p as spacesInApplyOrder, r as collectAggregateNamespaces, t as allStorageElementsExternal, u as planMigration } from "./aggregate-BAt9Aj73.mjs";
7
+ import { a as readContractSnapshotJson, c as snapshotsImportPathFrom, i as hasContractSnapshot, l as writeContractSnapshot, r as createSnapshotContentVerifier, t as contractSnapshotDir } from "./contract-snapshot-store-Dl6v-Uxr-CwhnMsgc.mjs";
8
+ import { t as deriveProvidedInvariants } from "./invariants-c9W7-6DY-CzSdi8Vp.mjs";
9
+ import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigrationDirName, u as writeMigrationPackage } from "./io-DUsSXBRO-BqRNb69U.mjs";
10
+ import { a as readRefs, d as validateRefValue, n as advanceRef, r as deleteRef, s as refsByContractHash, t as HEAD_REF_NAME, u as validateRefName } from "./refs-BE6yEgSV-CbpqGnbl.mjs";
11
+ import { c as readContractSpaceHeadRef, l as spaceMigrationDirectory, o as isValidSpaceId, s as listContractSpaceDirectories, t as APP_SPACE_ID$1, u as spaceRefsDirectory } from "./verify-contract-spaces-DvU9lE0Y-Y1WwEsPA.mjs";
12
+ import { a as contractHashAtMarker, c as loadContractSpaceAggregate, d as requireHeadRef, f as resolveRecordedPath, m as verifyMigration, n as buildFabricatedMigrationEdge, p as spacesInApplyOrder, r as collectAggregateNamespaces, t as allStorageElementsExternal, u as planMigration } from "./aggregate-B2D5REGs.mjs";
13
+ import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-Cj_GYpmM.mjs";
14
+ import { A as errorContractValidationFailed, B as errorMigrationHasUnfilledPlaceholders, Bt as toStructuralEdge, Ct as planAction, Dt as printedWayToTarget, E as errorConsentUnused, Et as printedPlan, F as errorFromCaught, Ft as runCommandAction, G as errorPlanForgotTheFlag, H as errorMigrationPlanningFailed, It as selfEmitCommand, J as errorRefSetBundleNotFound, K as errorPlanOriginUnknown, L as errorInvalidSpaceId, Lt as shellQuoted, Nt as resolveContractPath, O as errorContractConfigMissing, Ot as quotedPlan, P as errorFileNotFound, Pt as resolveMigrationPaths, Q as errorRuntime, Rt as statementFlag, S as editFileAction, St as migrationsDirFor, T as errorConfigValidation$1, Tt as printedPath, Vt as writtenMigrationRunCommand, W as errorPathUnreachable, X as errorRefSetHashNotInGraph, Y as errorRefSetEmptySentinel, _ as databasePositionOf, at as errorStatementNeedsMigrationFile, b as dbUpdateRerun, bt as migrationPlanReplacing, ct as errorTargetMigrationNotSupported, d as cliErrorFromStructured, dt as getTargetMigrations, et as errorSnapshotMissing, g as contractTypesModuleOf, gt as migrationPlanArguments, ht as migrationModuleOf, i as STORE_ORIGIN_SNAPSHOT_STEPS, it as errorStatementInvalid, jt as requireLiveDatabase, k as errorContractTypesModuleMissing, kt as readContractEnvelope, l as chooseAction, m as collectDeclaredInvariants, n as CONTRACT_PLACEHOLDER, nt as errorStatementAnswersNoQuestion, ot as errorStatementOriginUnknown, p as closeQuietly, pt as mapRefResolutionError, q as errorPlanProducedNoOperations, r as CliStructuredError$1, rt as errorStatementDidNotResolveLoss, s as appSpaceOf, st as errorStatementUnresolved, t as ActionableCliError, tt as errorSpaceNotFound, u as cliCommand, ut as errorUnexpected, v as dbMigrateRerun, vt as migrationPlanForDatabase, w as errorAmbiguousMigrationRef, wt as planThenApply, xt as migrationPlanTo, y as dbMigrateToEmitted, yt as migrationPlanFromRun } from "./caught-errors-DZXnK8Ls-zVmM4nr3.mjs";
15
+ import { r as getEmittedArtifactPaths, t as emit } from "./exports-CCuYD8dO-fFXwpizm.mjs";
16
16
  import { a as writeMigrationTs, n as formatMigrationTs } from "./migration-ts-DDgjsR1O.mjs";
17
- import { c as parseContractRef, l as parseMigrationRef, o as isLiveMarkerRef, r as RESERVED_CONTRACT_REFS, s as isReservedContractRef, t as EMPTY_CONTRACT_REF } from "./ref-resolution-C0xsiRig.mjs";
17
+ import { c as parseContractRef, l as parseMigrationRef, o as isLiveMarkerRef, r as RESERVED_CONTRACT_REFS, s as isReservedContractRef, t as EMPTY_CONTRACT_REF } from "./ref-resolution-533MGMov.mjs";
18
18
  import { createRequire } from "node:module";
19
19
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
20
20
  import { CliStructuredError } from "@prisma/orm-framework/errors/control";
21
21
  import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, DATA_PROTECTION_KEYS, createControlStack, databasePoliciesOf, databasePolicyDifferences, databasePolicyValueText, describeMigrationStatement, enumValueCoordinateFromJson, enumValueStatementText, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, movedDatabasePoliciesWhy, planOriginOf, valueObjectFieldStatementText, withDeclaredDatabasePolicies } from "@prisma/orm-framework/components/control";
22
- import { InternalError } from "@prisma/orm-framework/utils/internal-error";
22
+ import { InternalError, isInternalError } from "@prisma/orm-framework/utils/internal-error";
23
23
  import { notOk, ok } from "@prisma/orm-framework/utils/result";
24
24
  import { docsUrlFor, isStructuredError, isStructuredErrorCode, structuredError } from "@prisma/orm-framework/utils/structured-error";
25
25
  import { basename, dirname, isAbsolute, join, relative, resolve } from "pathe";
26
- import { errorMarkerPoliciesCorrupt } from "@prisma/orm-framework/errors/execution";
27
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
28
26
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
27
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
29
28
  import { type } from "arktype";
29
+ import { UNBOUND_NAMESPACE_ID, changedElementCoordinates } from "@prisma/orm-framework/components/ir";
30
+ import { asNamespaceId, valueObjectAt, valueObjectsWithCoordinates } from "@prisma/orm-framework/contract/types";
31
+ import { errorMarkerPoliciesCorrupt } from "@prisma/orm-framework/errors/execution";
30
32
  import { existsSync, readdirSync, statSync } from "node:fs";
31
33
  import { compareCodeUnits } from "@prisma/orm-framework/contract/hashing-utils";
32
- import { asNamespaceId, valueObjectAt, valueObjectsWithCoordinates } from "@prisma/orm-framework/contract/types";
33
- import { UNBOUND_NAMESPACE_ID, changedElementCoordinates } from "@prisma/orm-framework/components/ir";
34
34
  import { mergeCapabilityMatrices } from "@prisma/orm-framework/components/components";
35
35
  import { isDeepStrictEqual } from "node:util";
36
36
  import { canonicalStringify } from "@prisma/orm-framework/utils/canonical-stringify";
37
37
  import { abortable } from "@prisma/orm-framework/utils/abortable";
38
- //#region ../../../1-framework/3-tooling/cli/dist/ref-Ba6Mk6Rg.mjs
38
+ //#region ../../../1-framework/3-tooling/cli/dist/ref-C7TozKnq.mjs
39
39
  /**
40
40
  * The meta of a contract that failed to load because the family refused it, such as the columns whose defaults it refused, for the command to report: the refusal's own meta, or the `refusedDefaults` a migration-tools error kept from it.
41
41
  */
@@ -243,17 +243,26 @@ function failedTypeChangeText(change) {
243
243
  function quoted$1(command) {
244
244
  return `\`${command}\``;
245
245
  }
246
- /** A `db migrate` command as advice prints it, for a migration that is not the one the user ran. */
247
- function dbMigrateCommand(invocation) {
248
- return quoted$1(cliCommand(invocation, "db migrate"));
249
- }
250
246
  /** The `db migrate` the user ran, as advice that repeats it prints it. */
251
247
  function dbMigrateAgain(invocation) {
252
248
  return quoted$1(dbMigrateRerun(invocation));
253
249
  }
254
- /** The steps after filling the migration.ts a `migration plan` wrote with no placeholders: run it, which writes its operations, and apply it. */
250
+ /**
251
+ * Applying a migration planned after a change of the contract source, which ends at the new emitted
252
+ * contract: the ref the run's `--to` named still names the contract the failed migration went to.
253
+ */
254
+ function applyToEmitted(invocation) {
255
+ const apply = quoted$1(dbMigrateToEmitted(invocation));
256
+ const ref = invocation.targetRef;
257
+ if (ref === void 0) return apply;
258
+ return `${apply}, which goes to the new migration's contract and not to \`${ref}\`; \`${ref}\` still names the contract the failed migration went to, so if it should name the new one, run ${quoted$1(cliCommand(invocation, "migration ref set", [shellQuoted(ref), CONTRACT_PLACEHOLDER]))} with the contract the new migration ends at`;
259
+ }
260
+ /**
261
+ * The steps after filling the migration.ts a `migration plan` wrote with no placeholders, after a
262
+ * change of the contract source: run it, which writes its operations, and apply it.
263
+ */
255
264
  function runWrittenFile(invocation) {
256
- return `run ${quoted$1(writtenMigrationRunCommand(invocation))} for the directory it writes, and apply it with ${dbMigrateCommand(invocation)}`;
265
+ return `run ${quoted$1(writtenMigrationRunCommand(invocation))} for the directory it writes, and apply it with ${applyToEmitted(invocation)}`;
257
266
  }
258
267
  /** The step between filling a planned migration.ts and applying it, which writes its operations. */
259
268
  const RUN_PLANNED_FILE = "run that migration.ts with the `node` command `migration plan` prints";
@@ -270,17 +279,21 @@ function changeValueAdvice(change, rerun) {
270
279
  return change.by === "cast" && change.reason === "value" ? [chooseAction(`Change the value the failure names so the database's cast accepts it, then re-run ${rerun}`)] : [];
271
280
  }
272
281
  /** The way out of a failed cast for `db update`, which plans and applies in one step. */
273
- function dbUpdateFailedTypeChangeAdvice(change, databaseStorageHash, invocation) {
274
- const plan = printedPlanCommand(invocation, databaseStorageHash, [statementFlag({
282
+ function dbUpdateFailedTypeChangeAdvice(change, migrationPlan, invocation) {
283
+ const changeValue = changeValueAdvice(change, quoted$1(dbUpdateRerun(invocation)));
284
+ const plan = printedWayToTarget(invocation, migrationPlan, [statementFlag({
275
285
  verb: "convert",
276
286
  text: change.field
277
287
  })]);
278
- return [chooseAction(`${failedTypeChangeText(change)} Plan the change with ${quoted$1(plan)}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`), ...changeValueAdvice(change, quoted$1(dbUpdateRerun(invocation)))];
288
+ if (plan.kind === "on-disk") return [chooseAction(`${failedTypeChangeText(change)} ${plan.text}`), ...changeValue];
289
+ if (plan.kind === "none" || plan.kind === "at-target") return [chooseAction(`${failedTypeChangeText(change)} No migration can be planned for the change. ${plan.reason}`), ...changeValue];
290
+ return [chooseAction(`${failedTypeChangeText(change)} Plan the change with ${quotedPlan(plan)}, write the conversion in the migration.ts it writes, ${plan.afterPlan}`), ...changeValue];
279
291
  }
280
292
  /** The way out of rows without a value for `db update`, which plans and applies in one step. */
281
- function dbUpdateRowsWithoutValueAdvice(reports, databaseStorageHash, invocation) {
293
+ function dbUpdateRowsWithoutValueAdvice(reports, migrationPlan, invocation) {
282
294
  const flags = backfillFlags(reports);
283
- const planned = flags.length === 0 ? [] : [chooseAction(`Plan it with ${quoted$1(printedPlanCommand(invocation, databaseStorageHash, flags))}, fill the backfill steps in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`)];
295
+ const plan = printedWayToTarget(invocation, migrationPlan, flags);
296
+ const planned = flags.length === 0 ? [] : plan.kind === "on-disk" ? [chooseAction(plan.text)] : plan.kind === "none" || plan.kind === "at-target" ? [chooseAction(`No migration can be planned to backfill those rows. ${plan.reason}`)] : [chooseAction(`Plan it with ${quotedPlan(plan)}, fill the backfill steps in the migration.ts it writes, ${plan.afterPlan}`)];
284
297
  const [first] = reports;
285
298
  if (first?.reason === "nullValues") {
286
299
  const keep = optionalFields([first], "the field");
@@ -356,21 +369,31 @@ function storedValuesText(reports) {
356
369
  return values.length === 1 ? `the stored value ${values[0]} to one the enum keeps` : `each of the stored values ${values.join(", ")} to one its enum keeps`;
357
370
  }
358
371
  /** The way out when the data of required columns holds stored values `db update` removes. */
359
- function dbUpdateRowsHoldingValueAdvice(reports, databaseStorageHash, invocation) {
372
+ function dbUpdateRowsHoldingValueAdvice(reports, migrationPlan, invocation) {
360
373
  const others = otherStatements$1(invocation, reports);
361
374
  const deletes = deleteFlags(reports);
362
375
  const rename = chooseAction(`${newMember(reports, invocation)}, then run ${quoted$1(cliCommand(invocation, "db update", [...others, ...renameFlags(reports)]))}`);
363
- if (databaseStorageHash === void 0) return [rename, chooseAction(`To keep that data under another stored value, change ${storedValuesText(reports)} in the database yourself, then re-run ${quoted$1(dbUpdateRerun(invocation, [...others, ...deletes]))}`)];
376
+ const plan = printedWayToTarget(invocation, migrationPlan, [...others, ...deletes]);
377
+ if (plan.kind === "on-disk") return [rename, chooseAction(plan.text)];
378
+ if (plan.kind === "none" || plan.kind === "at-target") return [rename, chooseAction(`No migration can be planned to keep that data. ${plan.reason}. To keep that data under another stored value, change ${storedValuesText(reports)} in the database yourself, then re-run ${quoted$1(dbUpdateRerun(invocation, [...others, ...deletes]))}`)];
364
379
  const swaps = swapCalls(reports);
365
380
  if (swaps === void 0) return [rename];
366
- return [rename, chooseAction(`To keep that data by hand, plan the change with ${quoted$1(printedPlanCommand(invocation, databaseStorageHash, [...others, ...deletes]))}, make the edits below in the migration.ts it writes, ${KEPT_VALUE}, ${runWrittenFile(invocation)}.\n${swaps}`)];
381
+ return [rename, chooseAction(`To keep that data by hand, plan the change with ${quotedPlan(plan)}, make the edits below in the migration.ts it writes, ${KEPT_VALUE}, ${plan.afterPlan}.\n${swaps}`)];
367
382
  }
368
383
  function migrateRowsHoldingValueAdvice(reports, failedMigration, invocation) {
369
384
  const { file, run } = failedMigrationFile(failedMigration);
370
385
  const swaps = swapCalls(reports);
371
386
  const byHand = swaps === void 0 ? [] : [editFileAction(`To keep that data by hand, make the edits below in ${file}, ${KEPT_VALUE}, ${run}, and re-run ${dbMigrateAgain(invocation)}.\n${swaps}`)];
372
387
  if (failedMigration === void 0) return byHand;
373
- return [replan(`${newMember(reports, invocation)}, delete`, renameFlags(reports), failedMigration, deleteFlags(reports).map((flag) => `\`${flag}\``).join(" or "), `put any code you copied into the migration.ts it writes, ${runWrittenFile(invocation)}`), ...byHand];
388
+ const inPlace = swaps === void 0 && replacingPlan(failedMigration, renameFlags(reports)).kind === "none" ? [editFileAction(`To keep that data, add an operation to ${file} that updates the rows holding ${storedValuesList(reports)} to a stored value the enum keeps, before the operation that removes it, ${run}, and re-run ${dbMigrateAgain(invocation)}`)] : [];
389
+ return [
390
+ replan(`${newMember(reports, invocation)}, delete`, renameFlags(reports), failedMigration, deleteFlags(reports).map((flag) => `\`${flag}\``).join(" or "), `put any code you copied into the migration.ts it writes, ${runWrittenFile(invocation)}`),
391
+ ...byHand,
392
+ ...inPlace
393
+ ];
394
+ }
395
+ function storedValuesList(reports) {
396
+ return distinct(reports.map(({ value }) => JSON.stringify(value))).join(" or ");
374
397
  }
375
398
  /** Where the operation that updates the rows goes among the operations of a migration.ts that replaces a check. */
376
399
  function betweenTheChecks(report, replacedCheck) {
@@ -383,13 +406,15 @@ function fixRowsFirst(report, rerun) {
383
406
  return chooseAction(`Update or delete those rows so they fit check "${report.check}", then re-run ${quoted$1(rerun)}`);
384
407
  }
385
408
  /** The way out when existing rows fail a check `db update` adds: it cannot keep the data while the check it replaces holds. */
386
- function dbUpdateRowsFailingCheckAdvice(report, databaseStorageHash, invocation) {
409
+ function dbUpdateRowsFailingCheckAdvice(report, migrationPlan, invocation) {
387
410
  const update = dbUpdateRerun(invocation);
388
411
  const { replacedCheck } = report;
389
412
  if (replacedCheck === void 0) return [fixRowsFirst(report, update)];
390
413
  const cannotKeep = `${quoted$1(cliCommand(invocation, "db update"))} cannot keep this data`;
391
- if (databaseStorageHash === void 0) return [chooseAction(`${cannotKeep}, and no migration ends at the contract the database is at, so ${quoted$1(cliCommand(invocation, "migration plan"))} cannot plan from it. Drop check "${replacedCheck}" in the database yourself, update those rows to fit check "${report.check}", then re-run ${quoted$1(update)}`)];
392
- return [chooseAction(`${cannotKeep}. Plan the change with ${quoted$1(printedPlanCommand(invocation, databaseStorageHash, invocation.statementArgs ?? []))}, add ${updateOperation(report)} to the migration.ts it writes, ${betweenTheChecks(report, replacedCheck)}, ${runWrittenFile(invocation)}`)];
414
+ const plan = printedWayToTarget(invocation, migrationPlan, invocation.statementArgs ?? []);
415
+ if (plan.kind === "on-disk") return [chooseAction(`${cannotKeep}. ${plan.text}`)];
416
+ if (plan.kind === "none" || plan.kind === "at-target") return [chooseAction(`${cannotKeep}, and no migration can be planned for it. ${plan.reason}. Drop check "${replacedCheck}" in the database yourself, update those rows to fit check "${report.check}", then re-run ${quoted$1(update)}`)];
417
+ return [chooseAction(`${cannotKeep}. Plan the change with ${quotedPlan(plan)}, add ${updateOperation(report)} to the migration.ts it writes, ${betweenTheChecks(report, replacedCheck)}, ${plan.afterPlan}`)];
393
418
  }
394
419
  function migrateRowsFailingCheckAdvice(report, failedMigration, invocation) {
395
420
  const { replacedCheck } = report;
@@ -410,23 +435,32 @@ function failedMigrationText(failed, invocation) {
410
435
  return {
411
436
  directory: printedPath(invocation, failed.directory),
412
437
  name: dirName.slice(dirName.indexOf("_") + 1),
413
- from: failed.from === "empty" ? void 0 : failed.from,
438
+ replanFrom: failed.replanFrom,
414
439
  nodeCommand: selfEmitCommand(invocation, join(failed.directory, "migration.ts")),
415
440
  invocation
416
441
  };
417
442
  }
443
+ /** The `migration plan` that replaces the failed migration once its directory is deleted. */
444
+ function replacingPlan(failed, flags) {
445
+ return printedPlan(failed.invocation, { from: failed.replanFrom }, [
446
+ "--name",
447
+ failed.name,
448
+ ...flags
449
+ ]);
450
+ }
451
+ function keepFailedMigration(failed, reason) {
452
+ return chooseAction(`Keep \`${failed.directory}\`: no migration plan can replace it once it is deleted. ${reason}`);
453
+ }
418
454
  /**
419
455
  * Planning the failed migration again with `flags`. `opening` is the words before the directory,
420
- * so the sentence can start the advice or follow why it is needed.
456
+ * so the sentence can start the advice or follow why it is needed. When no plan can replace the
457
+ * migration, the advice is to keep it.
421
458
  */
422
459
  function replan(opening, flags, failed, except = void 0, afterPlan = `fill in the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateAgain(failed.invocation)}`) {
460
+ const plan = replacingPlan(failed, flags);
461
+ if (plan.kind === "none") return keepFailedMigration(failed, plan.reason);
423
462
  const others = except === void 0 ? OTHER_STATEMENTS : `${OTHER_STATEMENTS} except any ${except}`;
424
- const plan = printedPlanCommand(failed.invocation, failed.from, [
425
- "--name",
426
- failed.name,
427
- ...flags
428
- ]);
429
- return chooseAction(`${opening} \`${failed.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${quoted$1(plan)}, ${others}, ${afterPlan}`);
463
+ return chooseAction(`${opening} \`${failed.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${quotedPlan(plan)}, ${others}, ${afterPlan}`);
430
464
  }
431
465
  /**
432
466
  * Where to fix code written in the failed migration's `migration.ts`, and the command that runs the
@@ -450,7 +484,7 @@ function migrateFailedTypeChangeAdvice(change, failedMigration, invocation) {
450
484
  verb: "convert",
451
485
  text: change.field
452
486
  });
453
- if (failedMigration === void 0) return [chooseAction(`${changeText} Plan the type change again with ${quoted$1(printedPlanCommand(invocation, void 0, [convert]))}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateAgain(invocation)}`), ...changeValueAdvice(change, dbMigrateAgain(invocation))];
487
+ if (failedMigration === void 0) return [chooseAction(`${changeText} Find the migration that changes field "${change.field}" with ${quoted$1(cliCommand(invocation, "migration list"))}, delete its directory (copy any code you wrote in its migration.ts first), plan it again from the contract it starts from with \`${convert}\`, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateAgain(invocation)}`), ...changeValueAdvice(change, dbMigrateAgain(invocation))];
454
488
  const deleted = `\`${statementFlag({
455
489
  verb: "delete",
456
490
  text: change.field
@@ -469,37 +503,64 @@ function migrateRowsWithoutValueAdvice(reports, failedMigration, invocation) {
469
503
  }
470
504
  const flags = backfillFlags(reports);
471
505
  const again = (opening) => flags.length === 0 || failedMigration === void 0 ? void 0 : replan(opening, flags, failedMigration);
506
+ const replaceable = failedMigration !== void 0 && replacingPlan(failedMigration, flags).kind !== "none";
472
507
  const one = reports.length === 1;
473
508
  if (reports.every(({ reason }) => reason === "nullValues")) {
474
509
  const rerun = chooseAction(one ? `Set a value in ${theRows(first?.rows ?? 0)} and re-run ${dbMigrateAgain(invocation)}` : `Set a value in the rows that hold NULL in each of ${fieldList(reports)} and re-run ${dbMigrateAgain(invocation)}`);
475
510
  const backfill = again("Delete");
476
511
  const fields = optionalFields(reports, one ? "the field" : "those fields");
477
- const keep = fields === void 0 ? [] : [failedMigration === void 0 ? editFileAction(`Keep ${fields.text} optional in the contract source, and plan the migration again`) : keepOptional(fields.text, fields.one ? "it" : "them", failedMigration, invocation)];
512
+ const keep = fields === void 0 ? [] : [failedMigration === void 0 ? editFileAction(`Keep ${fields.text} optional in the contract source, and plan the migration again`) : keepOptional(fields.text, fields.one ? "it" : "them", failedMigration, invocation)].filter((action) => action !== void 0);
478
513
  return [
479
514
  rerun,
480
515
  ...backfill === void 0 ? [] : [backfill],
481
516
  ...keep
482
517
  ];
483
518
  }
519
+ const unreplaceable = failedMigration !== void 0 && !replaceable;
484
520
  if (first?.reason === "nullValues") {
485
521
  const notEnough = "The migration also adds a required field the existing rows have no value for, so setting values is not enough.";
486
522
  const backfill = again(`${notEnough} Delete`);
487
- if (backfill !== void 0) return [backfill];
523
+ if (backfill !== void 0 && replaceable) return [backfill];
524
+ if (unreplaceable) {
525
+ const newFields = reports.filter(({ reason }) => reason === "newField");
526
+ return [...backfill === void 0 ? [] : [backfill], editFileAction(`${notEnough} Set a value in the rows that hold NULL, and ${fillInPlace(newFields, failedMigration, invocation)}`)];
527
+ }
488
528
  const newFields = optionalFields(reports.filter(({ reason }) => reason === "newField"), "the new fields");
489
- return newFields === void 0 ? [resolveTheCause(invocation)] : [editFileAction(`${notEnough} Make ${newFields.text} optional in the contract source, and plan the migration again`)];
529
+ return [...backfill === void 0 ? [] : [backfill], newFields === void 0 ? resolveTheCause(invocation) : editFileAction(`${notEnough} Make ${newFields.text} optional in the contract source, and plan the migration again`)];
490
530
  }
491
531
  const fields = theFields(reports);
492
532
  const required = again(`To keep ${fields} required, delete`);
533
+ if (unreplaceable && required !== void 0) return [required, editFileAction(`To keep ${fields} required, ${fillInPlace(reports, failedMigration, invocation)}`)];
493
534
  const optional = optionalFields(reports, fields);
494
535
  if (required === void 0) return [optional === void 0 ? resolveTheCause(invocation) : editFileAction(`Make ${optional.text} optional in the contract source, and plan the migration again`)];
495
536
  return [required, ...optional === void 0 ? [] : [editFileAction(`Make ${optional.text} optional in the contract source, and plan it again`)]];
496
537
  }
538
+ /**
539
+ * Giving the rows of new required fields a value in the failed migration itself, for when no plan
540
+ * can replace it: the shape `migration plan --backfill` writes, made by hand.
541
+ */
542
+ function fillInPlace(reports, failedMigration, invocation) {
543
+ const { file, run } = failedMigrationFile(failedMigration);
544
+ const flags = backfillFlags(reports).map((flag) => `\`${flag}\``).join(" ");
545
+ const shape = flags === "" ? "`migration plan --backfill`" : `\`migration plan\` with ${flags}`;
546
+ const field = reports.length === 1 ? "the field" : "each field";
547
+ return `give the existing rows a value for ${fieldList(reports)} in the migration itself, in the shape ${shape} writes: add ${field} as optional, fill it with a data transform, and only then make it required. Make that change in ${file}, ${run}, and re-run ${dbMigrateAgain(invocation)}`;
548
+ }
549
+ /**
550
+ * The way out of a failed migration an extension ships: its migrations come with the extension, and
551
+ * `migration plan` plans only the application's contract space.
552
+ */
553
+ function extensionMigrationAdvice(spaceId, invocation) {
554
+ return [resolveTheCause(invocation), chooseAction(`The failed migration belongs to extension space "${spaceId}", whose migrations come with the extension and \`migration plan\` does not plan, so do not edit or plan it again; ask the extension's author for a version whose migrations apply to this database`)];
555
+ }
497
556
  function resolveTheCause(invocation) {
498
557
  return chooseAction(`Resolve the cause the failure names, then re-run ${dbMigrateAgain(invocation)}`);
499
558
  }
559
+ /** Keeping `fields` optional by planning the failed migration again; none when no plan can replace it. */
500
560
  function keepOptional(fields, pronoun, failedMigration, invocation) {
501
- const plan = printedPlanCommand(invocation, failedMigration.from, ["--name", failedMigration.name]);
502
- return editFileAction(`Keep ${fields} optional: make ${pronoun} optional in the contract source again, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), and plan it again with ${quoted$1(plan)}, ${OTHER_STATEMENTS}, put back any code you copied, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`);
561
+ const plan = replacingPlan(failedMigration, []);
562
+ if (plan.kind === "none") return void 0;
563
+ return editFileAction(`Keep ${fields} optional: make ${pronoun} optional in the contract source again, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), and plan it again with ${quotedPlan(plan)}, ${OTHER_STATEMENTS}, put back any code you copied, ${RUN_PLANNED_FILE}, and apply it with ${applyToEmitted(invocation)}`);
503
564
  }
504
565
  function theRows(rows) {
505
566
  return rows === 1 ? "that row" : `those ${rows} rows`;
@@ -509,10 +570,16 @@ function fieldList(reports) {
509
570
  }
510
571
  function migrateSchemaCheckAdvice(failedMigration, invocation) {
511
572
  const emit = quoted$1(cliCommand(invocation, "contract emit"));
512
- const plan = printedPlanCommand(invocation, failedMigration?.from, failedMigration === void 0 ? [] : ["--name", failedMigration.name]);
513
- const directory = failedMigration === void 0 ? "the failed migration's directory" : `\`${failedMigration.directory}\``;
573
+ if (failedMigration === void 0) {
574
+ const editedByHand = editFileAction(`If a migration you edited by hand does not reach its destination contract, find it with ${quoted$1(cliCommand(invocation, "migration list"))}, change its operations to resolve the issues listed, run its migration.ts with \`node\`, and run ${dbMigrateAgain(invocation)}`);
575
+ if (invocation.rerunArgs?.includes("--to") === true) return [editedByHand];
576
+ return [editFileAction(`If the contract source does not describe the schema you want, change it to resolve the issues listed, re-run ${emit}, and run ${quoted$1(cliCommand(invocation, "migration status"))}. If it prints a \`migration plan\`, run it, ${RUN_PLANNED_FILE}, and run ${dbMigrateAgain(invocation)}; otherwise run the command it prints`), editedByHand];
577
+ }
514
578
  const { file, run } = failedMigrationFile(failedMigration);
515
- return [editFileAction(`If the contract source does not describe the schema you want, change it to resolve the issues listed, re-run ${emit}, delete ${directory} (copy any code you wrote in its migration.ts first), plan it again with ${quoted$1(plan)}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}`), editFileAction(`If ${file} does not reach its destination contract, for example after a hand edit, change its operations to resolve the issues listed, ${run}, and run ${dbMigrateAgain(invocation)}`)];
579
+ const fixMigration = editFileAction(`If ${file} does not reach its destination contract, for example after a hand edit, change its operations to resolve the issues listed, ${run}, and run ${dbMigrateAgain(invocation)}`);
580
+ const plan = replacingPlan(failedMigration, []);
581
+ if (plan.kind === "none") return [keepFailedMigration(failedMigration, plan.reason), fixMigration];
582
+ return [editFileAction(`If the contract source does not describe the schema you want, change it to resolve the issues listed, re-run ${emit}, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${quotedPlan(plan)}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${applyToEmitted(invocation)}`), fixMigration];
516
583
  }
517
584
  /** The way out when objects in the database keep an operation from running. */
518
585
  function blockingObjectsAdvice(objects, rerun) {
@@ -527,6 +594,7 @@ function migrateAdvice(failure, facts, failedOnDisk, invocation) {
527
594
  const failedMigration = failedOnDisk === void 0 ? void 0 : failedMigrationText(failedOnDisk, invocation);
528
595
  const { blockingObjects } = failure.meta;
529
596
  if (blockingObjects !== void 0) return blockingObjectsAdvice(blockingObjects, dbMigrateRerun(invocation));
597
+ if (failedOnDisk?.extensionSpaceId !== void 0) return extensionMigrationAdvice(failedOnDisk.extensionSpaceId, invocation);
530
598
  if (facts.failedTypeChange !== void 0) return migrateFailedTypeChangeAdvice(facts.failedTypeChange, failedMigration, invocation);
531
599
  if (facts.rowsWithoutValue !== void 0) return migrateRowsWithoutValueAdvice(facts.rowsWithoutValue, failedMigration, invocation);
532
600
  if (facts.rowsHoldingValue !== void 0) return migrateRowsHoldingValueAdvice(facts.rowsHoldingValue, failedMigration, invocation);
@@ -562,16 +630,23 @@ function runnerFailureError(failure, advice) {
562
630
  });
563
631
  }
564
632
  const DB_INIT_ADDITIVE_ONLY_FIX = "`db init` applies only additive changes. Run `{bin} db update`, which also applies widening and destructive ones once you answer what each operation that would lose data means, with `--delete` or `--rename`.";
565
- const DB_INIT_NEEDS_MIGRATION_FIX = "`db init` applies only additive changes, and `db update` does not apply data operations. Plan a migration with `{bin} migration plan`, which can include them, and apply it with `{bin} db migrate`.";
633
+ const DB_INIT_NEEDS_MIGRATION = "`db init` applies only additive changes, and `db update` does not apply data operations.";
566
634
  /**
567
635
  * What to do instead of `db init` when its additive-only policy refused operations of the given classes: `db update` when its policy allows all of them, otherwise a planned migration.
568
636
  */
569
- function adviceForRefusedClasses(refused) {
637
+ function adviceForRefusedClasses(refused, context) {
570
638
  const allowedByDbUpdate = new Set(DB_UPDATE_POLICY.allowedOperationClasses);
571
- if (![...refused].every((operationClass) => allowedByDbUpdate.has(operationClass))) return {
572
- fix: DB_INIT_NEEDS_MIGRATION_FIX,
573
- nextAction: runCommandAction("Plan a migration, since db update does not apply data operations", "{bin} migration plan")
574
- };
639
+ if (![...refused].every((operationClass) => allowedByDbUpdate.has(operationClass))) {
640
+ const plan = printedPlan(context.invocation, { from: context.migrationPlanOrigin }, []);
641
+ if (plan.kind === "none") return {
642
+ fix: `${DB_INIT_NEEDS_MIGRATION} No migration can be planned for them. ${plan.reason}.`,
643
+ nextAction: planAction("Plan a migration", plan)
644
+ };
645
+ return {
646
+ fix: `${DB_INIT_NEEDS_MIGRATION} Plan a migration with ${quotedPlan(plan)}, which can include them, and apply it with \`${cliCommand(context.invocation, "db migrate")}\`.`,
647
+ nextAction: planAction("Plan a migration, since db update does not apply data operations", plan)
648
+ };
649
+ }
575
650
  return {
576
651
  fix: DB_INIT_ADDITIVE_ONLY_FIX,
577
652
  nextAction: runCommandAction(refused.has("destructive") ? "Apply the change with db update, which asks what each operation that would lose data means" : "Apply the change with db update", "{bin} db update")
@@ -581,11 +656,11 @@ function adviceForRefusedClasses(refused) {
581
656
  * `db init`'s planning failure: when its additive-only policy refused operations, it says to use
582
657
  * `db update` or a planned migration instead.
583
658
  */
584
- function dbInitPlanningFailedError(conflicts) {
659
+ function dbInitPlanningFailedError(conflicts, context) {
585
660
  const planningFailed = errorMigrationPlanningFailed({ conflicts });
586
661
  const refused = new Set(conflicts.flatMap((conflict) => conflict.refusedOperationClass === void 0 ? [] : [conflict.refusedOperationClass]));
587
662
  if (refused.size === 0) return planningFailed;
588
- const { fix, nextAction } = adviceForRefusedClasses(refused);
663
+ const { fix, nextAction } = adviceForRefusedClasses(refused, context);
589
664
  return new ActionableCliError(planningFailed.code, planningFailed.message, {
590
665
  why: planningFailed.why,
591
666
  fix,
@@ -600,15 +675,14 @@ function dbInitRunnerFailureError(failure, facts, invocation) {
600
675
  return runnerFailureError(failure, facts.rowsWithoutValue !== void 0 ? dbInitRowsWithoutValueAdvice(facts.rowsWithoutValue, invocation) : schemaCheckIssues(failure) !== void 0 ? [editFileAction(`Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${init}\``)] : facts.failedPrecheck !== void 0 ? dbInitFailedPrecheckAdvice(invocation) : [chooseAction(`Fix the schema mismatch (db init is additive-only), or bring the database to the contract with \`${cliCommand(invocation, "db update")}\`, which moves the database without a reset and asks before losing data`)]);
601
676
  }
602
677
  /**
603
- * A failed `db update` apply as the CLI reports it. `databaseStorageHash` is the contract the
604
- * database is at when a migration of the graph ends at it: the origin a `migration plan` for this
605
- * database starts from.
678
+ * A failed `db update` apply as the CLI reports it. `migrationPlan` is the `--from` and `--to` of a
679
+ * `migration plan` that takes this database where the run was going.
606
680
  */
607
681
  function dbUpdateRunnerFailureError(failure, facts, context) {
608
- const { databaseStorageHash, invocation } = context;
682
+ const { migrationPlan, invocation } = context;
609
683
  const update = dbUpdateRerun(invocation);
610
684
  const { blockingObjects } = failure.meta;
611
- return runnerFailureError(failure, blockingObjects !== void 0 ? blockingObjectsAdvice(blockingObjects, update) : facts.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeAdvice(facts.failedTypeChange, databaseStorageHash, invocation) : facts.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueAdvice(facts.rowsWithoutValue, databaseStorageHash, invocation) : facts.rowsHoldingValue !== void 0 ? dbUpdateRowsHoldingValueAdvice(facts.rowsHoldingValue, databaseStorageHash, invocation) : facts.rowsFailingCheck !== void 0 ? dbUpdateRowsFailingCheckAdvice(facts.rowsFailingCheck, databaseStorageHash, invocation) : schemaCheckIssues(failure) !== void 0 ? [editFileAction(`Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${update}\``)] : [chooseAction(`Resolve the cause the failure names, then re-run \`${update}\``)]);
685
+ return runnerFailureError(failure, blockingObjects !== void 0 ? blockingObjectsAdvice(blockingObjects, update) : facts.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeAdvice(facts.failedTypeChange, migrationPlan, invocation) : facts.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueAdvice(facts.rowsWithoutValue, migrationPlan, invocation) : facts.rowsHoldingValue !== void 0 ? dbUpdateRowsHoldingValueAdvice(facts.rowsHoldingValue, migrationPlan, invocation) : facts.rowsFailingCheck !== void 0 ? dbUpdateRowsFailingCheckAdvice(facts.rowsFailingCheck, migrationPlan, invocation) : schemaCheckIssues(failure) !== void 0 ? [editFileAction(`Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${update}\``)] : [chooseAction(`Resolve the cause the failure names, then re-run \`${update}\``)]);
612
686
  }
613
687
  function startText(fromHash) {
614
688
  return fromHash === "empty" ? "the empty contract (the space has no marker)" : `the contract its marker names ("${fromHash}")`;
@@ -728,9 +802,10 @@ function twoRuns(invocation, subject, kept) {
728
802
  return one ? `To keep it with db update, change it in two runs. First rename member ${names} of enum ${enumName} in the contract source to a name the enum does not have and give it a stored value the enum does not use, run ${emit}, and run ${quoted(first)}. Then rename that member back to ${names} with its final stored value, run ${emit}, and run ${quoted(second)}.` : `To keep it with db update, change them in two runs. First rename members ${names} of enum ${enumName} in the contract source to names the enum does not have and give each a stored value the enum does not use, run ${emit}, and run ${quoted(first)}. Then rename those members back to ${names} with their final stored values, run ${emit}, and run ${quoted(second)}.`;
729
803
  }
730
804
  /**
731
- * How `db update` says to keep the data of a subject: it cannot in one run. It plans the change with `migration plan` from the contract the database is at, when a migration ends there and the target gives edits, answering with `--delete` each kept subject whose edits it gives, or changes the stored values in two runs through temporary members; members whose edits swap values do that only when no migration ends there.
805
+ * How `db update` says to keep the data of a subject: it cannot in one run. It plans the change with the `migration plan` `migrationPlan` gives when the target gives edits, answering with `--delete` each kept subject whose edits it gives, or changes the stored values in two runs through temporary members; members whose edits swap values do that only when no plan can start where the database is.
732
806
  */
733
- function dbUpdateKeepDataEditAdvice(invocation, databaseStorageHash) {
807
+ function dbUpdateKeepDataEditAdvice(invocation, migrationPlan) {
808
+ const origin = migrationPlan.from;
734
809
  return (subject, kept) => {
735
810
  const deleteFlag = statementFlag({
736
811
  verb: "delete",
@@ -740,26 +815,39 @@ function dbUpdateKeepDataEditAdvice(invocation, databaseStorageHash) {
740
815
  const lead = swaps ? `db update cannot keep that data in one run, because members of the enum swap stored values, and ${deleteFlag} removes it.` : `db update cannot keep that data in one run, and ${deleteFlag} removes it.`;
741
816
  const runs = twoRuns(invocation, subject, kept);
742
817
  const runWays = runs === void 0 ? [] : [runs];
743
- if (databaseStorageHash === void 0 || subject.edits.length === 0) return {
818
+ const edited = kept.filter(({ edits }) => edits.length > 0);
819
+ if (origin.kind === "none" && edited.length > 0) return {
820
+ lead,
821
+ ways: [`No migration can be planned to keep it. ${origin.reason}.`, ...runWays]
822
+ };
823
+ if (subject.edits.length === 0) return {
744
824
  lead,
745
825
  ways: runWays
746
826
  };
747
- const edited = kept.filter(({ edits }) => edits.length > 0);
748
827
  const deletes = edited.map(({ text }) => statementFlag({
749
828
  verb: "delete",
750
829
  text
751
830
  }));
831
+ const plan = printedWayToTarget(invocation, migrationPlan, [...otherStatements(invocation, [subject.text]).filter((flag) => !deletes.includes(flag)), ...deletes]);
832
+ if (plan.kind === "on-disk") return {
833
+ lead,
834
+ ways: [`${plan.reason}. To keep it, in the migration.ts of the one that removes it ${editsText(edited.flatMap(({ edits }) => edits))}, run that migration.ts with \`node\`, and apply them with \`${plan.apply}\`.`, ...swaps ? [] : runWays]
835
+ };
836
+ if (plan.kind === "none" || plan.kind === "at-target") return {
837
+ lead,
838
+ ways: [`No migration can be planned to keep it. ${plan.reason}.`, ...runWays]
839
+ };
752
840
  return {
753
841
  lead,
754
- ways: [`To keep it, plan the change with ${quoted(printedPlanCommand(invocation, databaseStorageHash, [...otherStatements(invocation, [subject.text]).filter((flag) => !deletes.includes(flag)), ...deletes]))}, in the migration.ts it writes ${editsText(edited.flatMap(({ edits }) => edits))}, ${runWrittenFile(invocation)}.`, ...swaps ? [] : runWays]
842
+ ways: [`To keep it, plan the change with ${quotedPlan(plan)}, in the migration.ts it writes ${editsText(edited.flatMap(({ edits }) => edits))}, ${plan.afterPlan}.`, ...swaps ? [] : runWays]
755
843
  };
756
844
  };
757
845
  }
758
846
  /**
759
847
  * The planner's refusal as the CLI reports it. When a conflict can be written by hand, its next
760
848
  * actions are the conflicts' own advice, which says what to write, then the plan to write it in:
761
- * the run's statements without the ones the conflict leaves out, from the contract the database is
762
- * at when that is known.
849
+ * the run's statements without the ones the conflict leaves out, from and to where
850
+ * `context.migrationPlan` says, or why no such plan exists.
763
851
  */
764
852
  function planningRefusedError(conflicts, context) {
765
853
  const refused = errorMigrationPlanningFailed({ conflicts });
@@ -770,8 +858,8 @@ function planningRefusedError(conflicts, context) {
770
858
  return resolved !== void 0 && leaveOut.has(JSON.stringify(resolved));
771
859
  });
772
860
  const kept = context.statements.filter((statement) => !left.includes(statement));
773
- const plan = printedPlanCommand(context.invocation, context.from, [...context.to === void 0 ? [] : ["--to", context.to], ...kept.map(statementFlag)]);
774
- const action = chooseAction(`To write the rewrites by hand, plan the change without ${left.map(statementFlag).join(" and ")} with \`${plan}\`, add the rewrites the message describes to the migration.ts it writes, ${runWrittenFile(context.invocation)}`);
861
+ const plan = printedWayToTarget(context.invocation, context.migrationPlan, kept.map(statementFlag));
862
+ const action = chooseAction(plan.kind === "on-disk" ? `${plan.reason}. To write the rewrites by hand, add the rewrites the message describes to the migration.ts of the one that makes the change, run that migration.ts with \`node\`, and apply them with \`${plan.apply}\`` : plan.kind === "none" || plan.kind === "at-target" ? `The rewrites cannot be written by hand in a migration. ${plan.reason}` : `To write the rewrites by hand, plan the change without ${left.map(statementFlag).join(" and ")} with ${quotedPlan(plan)}, add the rewrites the message describes to the migration.ts it writes, ${plan.afterPlan}`);
775
863
  const reasons = conflicts.flatMap(({ why }) => why === void 0 ? [] : [why]);
776
864
  return new ActionableCliError(refused.code, refused.message, {
777
865
  why: refused.why,
@@ -841,8 +929,11 @@ function errorChangePolicyForbids(args) {
841
929
  meta
842
930
  });
843
931
  }
844
- const migrate = cliCommand(invocation, "db migrate", toRef);
845
- const recovery = `Author a migration with ${cliCommand(invocation, "migration plan")}, then apply it with ${migrate}.`;
932
+ const target = args.migrationPlan.to;
933
+ const migrate = cliCommand(invocation, "db migrate", ref !== void 0 ? toRef : target.kind === "reference" ? ["--to", shellQuoted(target.reference)] : []);
934
+ const way = printedWayToTarget(invocation, args.migrationPlan, [], migrate);
935
+ const atTarget = way.kind === "at-target" || args.migrationPlan.migrationsToTarget?.kind === "at-target-missing-invariants";
936
+ const recovery = way.kind === "on-disk" ? `${way.text}.` : way.kind === "none" || way.kind === "at-target" ? `${atTarget ? "" : "No migration can be planned to move it. "}${way.reason}.` : `Author a migration with ${quotedPlan(way)}, ${way.afterPlan}.`;
846
937
  return new ActionableCliError("MIGRATION.CHANGE_POLICY_FORBIDS", `${policyHolder} permits only migrations`, {
847
938
  why,
848
939
  fix: recovery,
@@ -871,7 +962,7 @@ function extensionsOwnMigrations(spaceIds) {
871
962
  return spaceIds.length === 1 ? `Contract space ${quotedList$1(spaceIds)} belongs to an extension, so do not edit or delete its migrations; ask the extension's author for a version without the operation.` : `Contract spaces ${quotedList$1(spaceIds)} belong to extensions, so do not edit or delete their migrations; ask the extensions' authors for versions without the operations.`;
872
963
  }
873
964
  /** What a user can do about refused operations in the application's contract space, for the command that refused them. */
874
- function keepAppProtected(setting, command, operations, alongsideExtensions, invocation) {
965
+ function keepAppProtected(setting, command, operations, alongsideExtensions, invocation, migrationPlan) {
875
966
  if (command === "db migrate") {
876
967
  const unapplied = alongsideExtensions ? "For an application migration no database has applied" : "For a migration no database has applied";
877
968
  return [KEEP_APPLIED_MIGRATION, setting === "accessWidening" ? `${unapplied}, delete the migration and any later ones no database has applied, put the contract's access rules back as they were, and plan again.` : `${unapplied}, delete the migration and any later ones no database has applied, and plan again: with --rename if a model or field was only renamed, with --convert if its type changed, or after putting back in the contract what the migration removes.`];
@@ -880,20 +971,27 @@ function keepAppProtected(setting, command, operations, alongsideExtensions, inv
880
971
  const changesType = operations.some(({ loss }) => loss === "typeChange");
881
972
  return [
882
973
  alongsideExtensions ? "For the application's operations: if a model or field was only renamed, state the rename with --rename <old>:<new>." : "If a model or field was only renamed, state the rename with --rename <old>:<new>.",
883
- ...changesType ? [`For a type change, write the conversion with ${cliCommand(invocation === void 0 ? void 0 : {
884
- ...invocation,
885
- dbGiven: false
886
- }, "migration plan", ["--convert", "<field>"])}.`] : [],
974
+ ...changesType ? [typeChangeSentence(invocation, migrationPlan)] : [],
887
975
  "Otherwise keep it in the contract."
888
976
  ];
889
977
  }
978
+ function typeChangeSentence(invocation, migrationPlan) {
979
+ if (migrationPlan === void 0) return "For a type change, state the conversion with --convert <field>.";
980
+ const plan = printedWayToTarget(invocation, migrationPlan, ["--convert", "<field>"]);
981
+ switch (plan.kind) {
982
+ case "on-disk": return `${plan.reason}. For a type change, write the conversion in the migration.ts of the one that changes the field, run that migration.ts with \`node\`, and apply them with \`${plan.apply}\`.`;
983
+ case "none":
984
+ case "at-target": return `A type change cannot be written as a migration here. ${plan.reason}.`;
985
+ default: return `For a type change, write the conversion with ${quotedPlan(plan)}, ${plan.afterPlan}.`;
986
+ }
987
+ }
890
988
  /** What a user can do instead of a refused change, for the command that refused it and the contract spaces that hold it. */
891
- function keepProtected(refusal, command, appSpaceId, invocation) {
989
+ function keepProtected(refusal, command, appSpaceId, invocation, migrationPlan) {
892
990
  const inApp = refusal.operations.filter(({ spaceId }) => spaceId === appSpaceId);
893
991
  const extensionSpaces = [...new Set(refusal.operations.flatMap(({ spaceId }) => spaceId === appSpaceId ? [] : [spaceId]))];
894
992
  return [
895
993
  refusingPolicy(refusal.source, refusal.setting === "accessWidening" ? FORBIDDEN_CHANGE.accessWidening : "losing data"),
896
- ...inApp.length === 0 ? [] : keepAppProtected(refusal.setting, command, inApp, extensionSpaces.length > 0, invocation),
994
+ ...inApp.length === 0 ? [] : keepAppProtected(refusal.setting, command, inApp, extensionSpaces.length > 0, invocation, migrationPlan),
897
995
  ...extensionSpaces.length === 0 ? [] : [extensionsOwnMigrations(extensionSpaces)],
898
996
  doItAnyway(refusal.source)
899
997
  ].join(" ");
@@ -911,7 +1009,7 @@ function errorDataProtectionForbids(args) {
911
1009
  const policyHolder = refName === void 0 ? "This database's data protection policy" : `${refName} declares a data protection policy that`;
912
1010
  const forbidden = refusals.map(({ setting }) => FORBIDDEN_CHANGE[setting]).join(" and ");
913
1011
  const why = refusals.flatMap(({ setting, source, operations }) => [`${source.kind === "ref" ? `${source.refName} declares` : "The marker records"} ${setting}: ${FORBIDDEN_LEVEL[setting]}.`, ...operations.map(refusedOperationText)]).join(" ");
914
- const recoveries = refusals.map((refusal) => keepProtected(refusal, command, spaceId, args.invocation));
1012
+ const recoveries = refusals.map((refusal) => keepProtected(refusal, command, spaceId, args.invocation, args.migrationPlan));
915
1013
  return new ActionableCliError("MIGRATION.DATA_PROTECTION_FORBIDS", `${policyHolder} forbids ${forbidden}`, {
916
1014
  why,
917
1015
  fix: recoveries.join(" "),
@@ -2255,6 +2353,24 @@ function consentDescription(verb, subject, text, loss) {
2255
2353
  return verb === "delete" && loss === "typeChange" ? `accept lossy type change of ${kind} "${text}"` : `${verb} ${kind} "${text}"`;
2256
2354
  }
2257
2355
  const DELETE_CASTS = "--delete keeps the field and lets the database cast its values, which can change or lose some.";
2356
+ /**
2357
+ * The sentence that says which `migration plan` writes the values of `fields`, or why none can; a
2358
+ * command that gives no plan origin is told it has none to offer.
2359
+ */
2360
+ function backfillPlanText(migrationPlan, fields, values) {
2361
+ const flags = fields.map((each) => statementFlag({
2362
+ verb: "backfill",
2363
+ text: each
2364
+ }));
2365
+ if (migrationPlan === void 0) return `this command plans no migration that writes ${values}`;
2366
+ const plan = printedWayToTarget(migrationPlan.invocation, migrationPlan, flags);
2367
+ switch (plan.kind) {
2368
+ case "on-disk": return `${plan.reason}. Apply them with \`${plan.apply}\` instead, which says how to write ${values} if they leave it out`;
2369
+ case "none":
2370
+ case "at-target": return `no migration can be planned to write ${values} either. ${plan.reason}`;
2371
+ default: return `plan the change with ${quotedPlan(plan)} to write ${values} in migration.ts, ${plan.afterPlan}`;
2372
+ }
2373
+ }
2258
2374
  /** What each answer to a type change does: `--convert`, where the command writes a migration to fill in, and `--delete`. */
2259
2375
  function typeChangeNote(loss, canConvert) {
2260
2376
  if (loss.loss !== "typeChange") return [];
@@ -2520,7 +2636,7 @@ function newRequiredFieldNote(subject, contracts) {
2520
2636
  verb: "backfill",
2521
2637
  text: each
2522
2638
  })).join(" ");
2523
- return [...temporary.length === 0 ? [] : [`If you answer delete, the existing objects get a temporary value in the new required ${named(temporary)}.`], ...needed.length === 0 ? [] : !contracts.canConvert ? [`If you answer delete, the new required ${named(needed)} ${needed.length === 1 ? "gets" : "get"} no temporary value: plan the change with migration plan ${backfills} to write ${needed.length === 1 ? "its value" : "their values"} in migration.ts.`] : needed.length === 1 ? [`If you answer delete, the new required ${named(needed)} still needs a value: add ${backfills} to write it in migration.ts.`] : [`If you answer delete, the new required ${named(needed)} still need a value: add ${backfills} to write them in migration.ts.`]];
2639
+ return [...temporary.length === 0 ? [] : [`If you answer delete, the existing objects get a temporary value in the new required ${named(temporary)}.`], ...needed.length === 0 ? [] : !contracts.canConvert ? [`If you answer delete, the new required ${named(needed)} ${needed.length === 1 ? "gets" : "get"} no temporary value: ${backfillPlanText(contracts.migrationPlan, needed, needed.length === 1 ? "its value" : "their values")}.`] : needed.length === 1 ? [`If you answer delete, the new required ${named(needed)} still needs a value: add ${backfills} to write it in migration.ts.`] : [`If you answer delete, the new required ${named(needed)} still need a value: add ${backfills} to write them in migration.ts.`]];
2524
2640
  }
2525
2641
  function quotedList(items) {
2526
2642
  const quoted = items.map((item) => `"${item}"`);
@@ -2780,6 +2896,7 @@ async function askPlanQuestions(input) {
2780
2896
  canConvert: input.canConvert,
2781
2897
  statements,
2782
2898
  ...ifDefined("keepDataEditAdvice", input.keepDataEditAdvice),
2899
+ ...ifDefined("migrationPlan", input.migrationPlan),
2783
2900
  temporaryValues: plan.temporaryValues
2784
2901
  };
2785
2902
  const pending = (verb, planned) => [...new Map(planned.filter((entry) => !consented.has(questionKey(verb, entry))).map((entry) => [questionKey(verb, entry), entry])).values()];
@@ -3174,7 +3291,7 @@ function describeIntegrityViolation(violation) {
3174
3291
  */
3175
3292
  function layoutFix(layout, migrationsDir) {
3176
3293
  const spaceDir = `\`${migrationsDir}/<space>/\``;
3177
- return [layout.some((v) => v.kind === "declaredButUnmigrated") ? `Run \`prisma contract emit\` or \`prisma migration plan\` to write the pinned files of each declared extension pack under ${spaceDir}.` : [], layout.some((v) => v.kind === "orphanSpaceDir") ? `For a directory no extension declares, declare its extension in \`extensions\` or remove ${spaceDir}.` : []].flat().join(" ");
3294
+ return [layout.some((v) => v.kind === "declaredButUnmigrated") ? `Run \`{bin} contract emit\` to write the pinned files of each declared extension pack under ${spaceDir}.` : [], layout.some((v) => v.kind === "orphanSpaceDir") ? `For a directory no extension declares, declare its extension in \`extensions\` or remove ${spaceDir}.` : []].flat().join(" ");
3178
3295
  }
3179
3296
  function mapIntegrityViolations(violations, migrationsDir) {
3180
3297
  if (violations.length === 0) return null;
@@ -3376,7 +3493,8 @@ const STRATEGY_OF = {
3376
3493
  * them. Then the change policy the run would leave in force must permit the command.
3377
3494
  */
3378
3495
  function checkRunPolicies(args) {
3379
- const { appSpaceId, inForce, ref } = args;
3496
+ const { app, inForce, ref } = args;
3497
+ const appSpaceId = app.spaceId;
3380
3498
  const declared = ref?.policies;
3381
3499
  const differences = declared === void 0 ? [] : databasePolicyDifferences(declared, inForce);
3382
3500
  if (ref !== void 0 && differences.length > 0 && !args.permitPolicyChange) return notOk(errorPolicyMismatch({
@@ -3400,6 +3518,13 @@ function checkRunPolicies(args) {
3400
3518
  refName: ref.name
3401
3519
  } : { kind: "marker" },
3402
3520
  targetHash: args.targetHash,
3521
+ migrationPlan: args.migrationPlan ?? migrationPlanForDatabase(app, args.markers.get(app.spaceId), ref === void 0 ? {
3522
+ kind: "contract",
3523
+ hash: args.targetHash
3524
+ } : {
3525
+ kind: "ref",
3526
+ name: ref.name
3527
+ }),
3403
3528
  ref: ref === void 0 ? void 0 : {
3404
3529
  name: ref.name,
3405
3530
  permitPolicyChange: args.permitPolicyChange
@@ -3460,7 +3585,8 @@ function refuseForbiddenChanges(args) {
3460
3585
  spaceId: args.appSpaceId,
3461
3586
  command: args.command,
3462
3587
  refusals,
3463
- invocation: args.invocation
3588
+ invocation: args.invocation,
3589
+ ...ifDefined("migrationPlan", args.migrationPlan)
3464
3590
  });
3465
3591
  }
3466
3592
  /**
@@ -3755,16 +3881,21 @@ async function executeRun(options) {
3755
3881
  if (!loaded.ok) throw loaded.failure;
3756
3882
  const aggregate = loaded.value;
3757
3883
  const markerRows = await familyInstance.readAllMarkers({ driver });
3884
+ const ref = options.action === "dbUpdate" ? options.ref : void 0;
3885
+ const appSpace = appSpaceOf(aggregate, { hash: (options.action === "dbUpdate" ? options.emittedContractHash : void 0) ?? (ref === void 0 ? contract.storage.storageHash : void 0) });
3886
+ const migrationPlan = migrationPlanForDatabase(appSpace, markerRows.get(aggregate.app.spaceId), dbUpdatePlanEnd(ref, contract.storage.storageHash));
3758
3887
  let checkedPolicies;
3759
3888
  if (options.action === "dbUpdate") {
3760
3889
  const checked = checkRunPolicies({
3761
3890
  command: "db update",
3762
- appSpaceId: aggregate.app.spaceId,
3891
+ app: appSpace,
3892
+ markers: markerRows,
3763
3893
  inForce: databasePoliciesInForce(markerRows, aggregate.app.spaceId, familyInstance.markerLocation),
3764
3894
  ref: options.ref,
3765
3895
  permitPolicyChange: options.permitPolicyChange,
3766
3896
  targetHash: contract.storage.storageHash,
3767
- invocation: options.invocation
3897
+ invocation: options.invocation,
3898
+ migrationPlan
3768
3899
  });
3769
3900
  if (!checked.ok) return notOk(checked.failure);
3770
3901
  checkedPolicies = checked.value;
@@ -3792,10 +3923,7 @@ async function executeRun(options) {
3792
3923
  const fieldConverts = appOrigin?.origin.kind === "missing" ? fieldConvertsInDestination(statementTexts, contract) : [];
3793
3924
  const firstResolved = fieldConverts.length > 0 ? [] : resolveRenames(statementTexts);
3794
3925
  const needsMigrationFile = fieldConverts.length > 0 ? fieldConverts : statementsNeedingMigrationFile(statementTexts, firstResolved);
3795
- if (needsMigrationFile.length > 0) {
3796
- const markerHash = markerRows.get(aggregate.app.spaceId)?.storageHash;
3797
- throw errorStatementNeedsMigrationFile(statementTexts, needsMigrationFile, options.invocation, aggregate.app.packages.some(({ metadata }) => metadata.to === markerHash) ? markerHash : void 0);
3798
- }
3926
+ if (needsMigrationFile.length > 0) throw errorStatementNeedsMigrationFile(statementTexts, needsMigrationFile, options.invocation, migrationPlan);
3799
3927
  if (mode === "apply") {
3800
3928
  const orphanMarkerError = detectOrphanMarkers(aggregate, markerRows, familyInstance.markerLocation);
3801
3929
  if (orphanMarkerError !== null) throw orphanMarkerError;
@@ -3827,6 +3955,7 @@ async function executeRun(options) {
3827
3955
  appSpaceId: aggregate.app.spaceId,
3828
3956
  command: "db update",
3829
3957
  invocation: options.invocation,
3958
+ migrationPlan,
3830
3959
  forbidden: forbiddingSettingsOfRun(checkedPolicies, options.ref),
3831
3960
  dataLoss: operations(planned.subjects.dataLoss),
3832
3961
  accessChanges: operations(planned.subjects.accessChanges)
@@ -3869,6 +3998,7 @@ async function executeRun(options) {
3869
3998
  aggregate,
3870
3999
  markerRows,
3871
4000
  invocation: options.invocation,
4001
+ migrationPlan,
3872
4002
  statements: texts,
3873
4003
  resolved
3874
4004
  }) });
@@ -3930,7 +4060,11 @@ async function executeRun(options) {
3930
4060
  originKnown: fromContract !== null,
3931
4061
  destination: contract,
3932
4062
  answer: options.answerQuestions,
3933
- keepDataEditAdvice: dbUpdateKeepDataEditAdvice(options.invocation, recordedDatabaseContract(aggregate, markerRows)),
4063
+ keepDataEditAdvice: dbUpdateKeepDataEditAdvice(options.invocation, migrationPlan),
4064
+ migrationPlan: {
4065
+ ...migrationPlan,
4066
+ invocation: options.invocation
4067
+ },
3934
4068
  replan: (planned) => plan([...consentTexts, ...planned], resolveRenames(planned))
3935
4069
  });
3936
4070
  if (!answered.ok) {
@@ -4002,6 +4136,7 @@ async function executeRun(options) {
4002
4136
  appliedStatements,
4003
4137
  subjects,
4004
4138
  databaseStorageHash,
4139
+ migrationPlan: action === "dbUpdate" ? migrationPlan : void 0,
4005
4140
  permitted
4006
4141
  });
4007
4142
  }
@@ -4022,7 +4157,7 @@ async function executeRun(options) {
4022
4157
  if (!applied.ok) {
4023
4158
  const facts = await withEditsAsWritten(runnerFailureFacts(applied.failure, orderedResolutions));
4024
4159
  return notOk(action === "dbInit" ? dbInitRunnerFailureError(applied.failure, facts, options.invocation) : dbUpdateRunnerFailureError(applied.failure, facts, {
4025
- databaseStorageHash,
4160
+ migrationPlan,
4026
4161
  invocation: options.invocation
4027
4162
  }));
4028
4163
  }
@@ -4041,6 +4176,7 @@ async function executeRun(options) {
4041
4176
  appliedStatements,
4042
4177
  subjects,
4043
4178
  databaseStorageHash,
4179
+ migrationPlan: action === "dbUpdate" ? migrationPlan : void 0,
4044
4180
  changedStorageEntities: signedWithoutOperations ? changedStorageEntities(fromContract, contract) : void 0,
4045
4181
  databasePoliciesUpdated: policiesToWrite?.differences,
4046
4182
  permitted
@@ -4190,10 +4326,12 @@ function detectOrphanMarkers(aggregate, markerRows, markerLocation) {
4190
4326
  });
4191
4327
  }
4192
4328
  function mapPlannerError(error, context) {
4193
- if (error.kind === "planFromDiffFailed") return context.action === "dbInit" ? dbInitPlanningFailedError(error.conflicts) : planningRefusedError(error.conflicts, {
4329
+ if (error.kind === "planFromDiffFailed") return context.action === "dbInit" ? dbInitPlanningFailedError(error.conflicts, {
4330
+ migrationPlanOrigin: context.migrationPlan.from,
4331
+ invocation: context.invocation
4332
+ }) : planningRefusedError(error.conflicts, {
4194
4333
  invocation: context.invocation,
4195
- from: recordedDatabaseContract(context.aggregate, context.markerRows),
4196
- to: void 0,
4334
+ migrationPlan: context.migrationPlan,
4197
4335
  statements: context.statements,
4198
4336
  resolved: context.resolved
4199
4337
  });
@@ -4221,6 +4359,7 @@ function wrapPlanResult(args) {
4221
4359
  mode: "plan",
4222
4360
  ...args.permitted.length > 0 ? { permitted: args.permitted } : {},
4223
4361
  ...ifDefined("databaseStorageHash", args.databaseStorageHash),
4362
+ ...ifDefined("migrationPlan", args.migrationPlan),
4224
4363
  ...ifDefined("appliedStatements", args.appliedStatements),
4225
4364
  ...args.subjects,
4226
4365
  plan: {
@@ -4241,6 +4380,7 @@ function wrapApplyResult(args) {
4241
4380
  ...args.permitted.length > 0 ? { permitted: args.permitted } : {},
4242
4381
  ...ifDefined("databasePoliciesUpdated", args.databasePoliciesUpdated),
4243
4382
  ...ifDefined("databaseStorageHash", args.databaseStorageHash),
4383
+ ...ifDefined("migrationPlan", args.migrationPlan),
4244
4384
  ...ifDefined("changedStorageEntities", args.changedStorageEntities),
4245
4385
  ...ifDefined("appliedStatements", args.appliedStatements),
4246
4386
  ...args.subjects,
@@ -4262,10 +4402,19 @@ function wrapApplyResult(args) {
4262
4402
  });
4263
4403
  }
4264
4404
  /**
4265
- * The storage hash of the contract the application space's database is at, when the migration
4266
- * graph has it: `migration plan --from` then resolves it. Without a migration that ends at it,
4267
- * `migration plan` starts from the `db` ref that `db update` keeps.
4405
+ * Where `db update` goes, as `migration plan` would end there: the ref `--to` named, a contract a
4406
+ * migration records, or else the emitted contract, the only other contract `db update` moves to.
4268
4407
  */
4408
+ function dbUpdatePlanEnd(ref, targetHash) {
4409
+ return ref === void 0 ? {
4410
+ kind: "contract",
4411
+ hash: targetHash
4412
+ } : {
4413
+ kind: "ref",
4414
+ name: ref.name
4415
+ };
4416
+ }
4417
+ /** The contract the application space's database is at, when a migration records it. */
4269
4418
  function recordedDatabaseContract(aggregate, markerRows) {
4270
4419
  const hash = markerRows.get(aggregate.app.spaceId)?.storageHash;
4271
4420
  return hash !== void 0 && aggregate.app.graph().nodes.has(hash) ? hash : void 0;
@@ -4572,7 +4721,8 @@ async function signContractSpaces(options) {
4572
4721
  if (inForce !== void 0) {
4573
4722
  const permitted = checkRunPolicies({
4574
4723
  command: "db sign",
4575
- appSpaceId,
4724
+ app: appSpaceOf(aggregate),
4725
+ markers,
4576
4726
  inForce,
4577
4727
  ref: void 0,
4578
4728
  permitPolicyChange: false,
@@ -4708,6 +4858,7 @@ async function executeDbUpdate(options) {
4708
4858
  acceptAccessChanges: options.acceptAccessChanges ?? false,
4709
4859
  ...ifDefined("ref", options.ref),
4710
4860
  permitPolicyChange: options.permitPolicyChange ?? false,
4861
+ ...ifDefined("emittedContractHash", options.emittedContractHash),
4711
4862
  ...ifDefined("verifySnapshotContent", options.verifySnapshotContent),
4712
4863
  ...ifDefined("onPlannerWarnings", options.onPlannerWarnings),
4713
4864
  ...ifDefined("onProgress", options.onProgress)
@@ -5304,7 +5455,8 @@ async function executeMigrate(options) {
5304
5455
  if (!planned.ok) return notOk(planned.failure);
5305
5456
  const checkedPolicies = checkRunPolicies({
5306
5457
  command: "db migrate",
5307
- appSpaceId: aggregate.app.spaceId,
5458
+ app: appSpaceOf(aggregate),
5459
+ markers: markerRows,
5308
5460
  inForce,
5309
5461
  ref,
5310
5462
  permitPolicyChange: options.permitPolicyChange ?? false,
@@ -5333,16 +5485,20 @@ async function executeMigrate(options) {
5333
5485
  }
5334
5486
  if (outcome.kind === "never-planned") return notOk(neverPlannedSpaceFailure(outcome, {
5335
5487
  appSpaceId: aggregate.app.spaceId,
5488
+ appSpace: appSpaceOf(aggregate),
5336
5489
  migrationsDir,
5490
+ target,
5337
5491
  invocation: options.invocation
5338
5492
  }));
5339
5493
  if (outcome.kind === "unreachable") return notOk(unreachableSpaceFailure({
5340
5494
  spaceId: outcome.spaceId,
5341
5495
  fromHash: contractHashAtMarker(outcome.liveMarker),
5342
- targetHash: outcome.targetHash
5496
+ targetHash: outcome.targetHash,
5497
+ position: databasePositionOf(outcome.liveMarker?.storageHash)
5343
5498
  }, {
5344
5499
  appSpaceId: aggregate.app.spaceId,
5345
- toArgument: toArgumentFor(target, aggregate.app.graph()),
5500
+ appSpace: appSpaceOf(aggregate),
5501
+ target,
5346
5502
  invocation: options.invocation
5347
5503
  }));
5348
5504
  if (outcome.kind === "unsatisfiable") throw noInvariantPathError({
@@ -5407,7 +5563,7 @@ async function executeMigrate(options) {
5407
5563
  });
5408
5564
  if (!applied.ok) {
5409
5565
  const facts = await withEditsAsWritten(runnerFailureFacts(applied.failure, collectOrdered(applyOrder, perSpacePlans)));
5410
- return notOk(migrateRunnerFailureError(applied.failure, facts, facts.failedMigration === void 0 ? void 0 : failedMigrationOnDisk(facts.failedMigration, migrationsDir), options.invocation));
5566
+ return notOk(migrateRunnerFailureError(applied.failure, facts, facts.failedMigration === void 0 ? void 0 : failedMigrationOnDisk(facts.failedMigration, migrationsDir, aggregate.app), options.invocation));
5411
5567
  }
5412
5568
  const orderedAll = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId) || plansKeptFromRunner.has(spaceId)).map((spaceId) => {
5413
5569
  if (perSpacePlans.has(spaceId)) {
@@ -5598,6 +5754,7 @@ function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker
5598
5754
  return {
5599
5755
  kind: "never-planned",
5600
5756
  spaceId: space.spaceId,
5757
+ liveMarker,
5601
5758
  targetHash
5602
5759
  };
5603
5760
  }
@@ -5788,7 +5945,7 @@ function buildSuccess(args) {
5788
5945
  * of the extension that ships them.
5789
5946
  */
5790
5947
  function neverPlannedSpaceFailure(space, run) {
5791
- if (space.spaceId === run.appSpaceId) return buildNeverPlannedFailure(space.spaceId, space.targetHash, run.migrationsDir, run.invocation);
5948
+ if (space.spaceId === run.appSpaceId) return buildNeverPlannedFailure(space.spaceId, space.targetHash, run.migrationsDir, migrationPlanArguments(run.appSpace, databasePositionOf(space.liveMarker?.storageHash), planEndOf(run.target)), run.invocation);
5792
5949
  return errorExtensionNeverPlanned({
5793
5950
  spaceId: space.spaceId,
5794
5951
  targetHash: space.targetHash,
@@ -5803,7 +5960,7 @@ function neverPlannedSpaceFailure(space, run) {
5803
5960
  * contract the path would start from: the one the marker names, or an offline `--from`.
5804
5961
  */
5805
5962
  function unreachableSpaceFailure(space, run) {
5806
- if (space.spaceId === run.appSpaceId) return buildPathNotFoundFailure(space.spaceId, space.fromHash, space.targetHash, run.toArgument, run.invocation);
5963
+ if (space.spaceId === run.appSpaceId) return buildPathNotFoundFailure(space.spaceId, space.fromHash, space.targetHash, migrationPlanArguments(run.appSpace, space.position ?? databasePositionOf(space.fromHash), planEndOf(run.target)), run.invocation);
5807
5964
  return errorExtensionPathUnreachable({
5808
5965
  spaceId: space.spaceId,
5809
5966
  fromHash: space.fromHash,
@@ -5812,15 +5969,16 @@ function unreachableSpaceFailure(space, run) {
5812
5969
  invocation: run.invocation
5813
5970
  });
5814
5971
  }
5815
- /**
5816
- * What `--to` takes to name the application space's target: a ref's name, or the hash of a contract
5817
- * a migration names. `undefined` for the emitted contract, and for a hash no migration names, which
5818
- * `--to` cannot resolve and which only the emitted contract can be.
5819
- */
5820
- function toArgumentFor(target, appGraph) {
5821
- if (target === void 0) return void 0;
5822
- if (target.kind === "ref") return target.ref.name;
5823
- return isGraphNode(target.hash, appGraph) ? target.hash : void 0;
5972
+ /** Where `db migrate` goes, as `migration plan` would end there: the emitted contract when it was given no other target. */
5973
+ function planEndOf(target) {
5974
+ if (target === void 0) return { kind: "emitted" };
5975
+ return target.kind === "ref" ? {
5976
+ kind: "ref",
5977
+ name: target.ref.name
5978
+ } : {
5979
+ kind: "contract",
5980
+ hash: target.hash
5981
+ };
5824
5982
  }
5825
5983
  /**
5826
5984
  * Build the `neverPlanned` failure raised when a contract space that
@@ -5832,7 +5990,7 @@ function toArgumentFor(target, appGraph) {
5832
5990
  *
5833
5991
  * @internal Exported for testing only.
5834
5992
  */
5835
- function buildNeverPlannedFailure(spaceId, targetHash, migrationsDir, invocation) {
5993
+ function buildNeverPlannedFailure(spaceId, targetHash, migrationsDir, plan, invocation) {
5836
5994
  const meta = {
5837
5995
  spaceId,
5838
5996
  targetHash,
@@ -5842,7 +6000,7 @@ function buildNeverPlannedFailure(spaceId, targetHash, migrationsDir, invocation
5842
6000
  summary: `No on-disk migrations for contract space "${spaceId}"`,
5843
6001
  why: `migrate is replay-only: a contract space that declares managed storage elements must have an authored migration graph on disk. Space "${spaceId}" has no migrations under \`${migrationsDir}/${spaceId}/\` but its head ref targets "${targetHash}".`,
5844
6002
  meta
5845
- }, planThenApply(meta, void 0, invocation));
6003
+ }, planThenApply(plan, invocation));
5846
6004
  }
5847
6005
  /**
5848
6006
  * Build the `pathUnreachable` failure raised when an emitted contract has no
@@ -5854,24 +6012,30 @@ function buildNeverPlannedFailure(spaceId, targetHash, migrationsDir, invocation
5854
6012
  *
5855
6013
  * @internal Exported for testing only.
5856
6014
  */
5857
- function buildPathNotFoundFailure(spaceId, fromHash, targetHash, toArgument, invocation) {
5858
- const fromText = fromHash === "empty" ? "the empty contract" : `"${fromHash}"`;
5859
- const meta = {
5860
- spaceId,
5861
- fromHash,
5862
- targetHash,
5863
- kind: "pathUnreachable"
5864
- };
5865
- return errorPathUnreachable({
6015
+ function buildPathNotFoundFailure(spaceId, fromHash, targetHash, plan, invocation) {
6016
+ return errorPathUnreachable(pathNotFound(spaceId, fromHash, targetHash), planThenApply(plan, invocation));
6017
+ }
6018
+ function pathNotFound(spaceId, fromHash, targetHash) {
6019
+ return {
5866
6020
  summary: "Current contract has no planned migration path",
5867
- why: `No migration edge connects ${fromText} to the target "${targetHash}" in contract space "${spaceId}". The on-disk migration graph does not join the two, and migrate replays existing edges — it never invents one.`,
5868
- meta
5869
- }, planThenApply(meta, toArgument, invocation));
6021
+ why: `No migration edge connects ${fromHash === "empty" ? "the empty contract" : `"${fromHash}"`} to the target "${targetHash}" in contract space "${spaceId}". The on-disk migration graph does not join the two, and migrate replays existing edges — it never invents one.`,
6022
+ meta: {
6023
+ spaceId,
6024
+ fromHash,
6025
+ targetHash,
6026
+ kind: "pathUnreachable"
6027
+ }
6028
+ };
5870
6029
  }
5871
- function failedMigrationOnDisk(failed, migrationsDir) {
6030
+ function failedMigrationOnDisk(failed, migrationsDir, app) {
5872
6031
  return {
5873
6032
  directory: join(migrationsDir, failed.spaceId, failed.edge.dirName),
5874
- from: failed.edge.from
6033
+ replanFrom: migrationPlanReplacing({
6034
+ graph: app.graph(),
6035
+ refs: app.refs,
6036
+ packages: app.packages
6037
+ }, failed.edge),
6038
+ ...failed.spaceId === app.spaceId ? {} : { extensionSpaceId: failed.spaceId }
5875
6039
  };
5876
6040
  }
5877
6041
  /**
@@ -6143,6 +6307,7 @@ var ControlClientImpl = class {
6143
6307
  ...ifDefined("acceptAccessChanges", options.acceptAccessChanges),
6144
6308
  ...ifDefined("ref", options.ref),
6145
6309
  ...ifDefined("permitPolicyChange", options.permitPolicyChange),
6310
+ ...ifDefined("emittedContractHash", options.emittedContractHash),
6146
6311
  ...ifDefined("statements", options.statements),
6147
6312
  answerQuestions: options.answerQuestions,
6148
6313
  ...ifDefined("verifySnapshotContent", this.snapshotVerifier),
@@ -6897,7 +7062,7 @@ async function buildRefAdvancementFields(options) {
6897
7062
  });
6898
7063
  }
6899
7064
  /**
6900
- * The --advance-ref tail of migrate and db sign: executeRefAdvancement with
7065
+ * The ref-advancement tail of db sign: executeRefAdvancement with
6901
7066
  * MigrationToolsError failures passed through as notOk, others rethrown.
6902
7067
  */
6903
7068
  async function advanceRefSafely(args) {
@@ -6908,6 +7073,40 @@ async function advanceRefSafely(args) {
6908
7073
  throw error;
6909
7074
  }
6910
7075
  }
7076
+ function refWriteFailure(error, failedAt) {
7077
+ const code = Reflect.get(Object(error), "code");
7078
+ return {
7079
+ reason: error instanceof Error ? error.message : String(error),
7080
+ causeCode: typeof code === "string" ? code : void 0,
7081
+ failedAt
7082
+ };
7083
+ }
7084
+ /**
7085
+ * Writes a ref after `db migrate` applied its migrations: the snapshot first, when this run
7086
+ * rendered it, then the pointer. Every failure is returned, not thrown: the database has already
7087
+ * moved, so a ref that cannot be written must not fail the run. An internal error is a bug and
7088
+ * goes to the outermost boundary.
7089
+ */
7090
+ async function writeAdvancedRef(args, writePointer) {
7091
+ let stage = args.snapshot.kind === "render" ? "snapshot" : "store-check";
7092
+ try {
7093
+ if (args.snapshot.kind === "render") await writeContractSnapshot(args.migrationsDir, args.hash, {
7094
+ contractJson: args.snapshot.contractIR.contract,
7095
+ contractDts: args.snapshot.contractIR.contractDts
7096
+ });
7097
+ else if (!await hasContractSnapshot(args.migrationsDir, args.hash)) return notOk({
7098
+ reason: `the snapshot store holds no contract for ${args.hash}`,
7099
+ causeCode: void 0,
7100
+ failedAt: "snapshot"
7101
+ });
7102
+ stage = "pointer";
7103
+ await writePointer(args.refsDir, args.name, args.hash);
7104
+ return ok(void 0);
7105
+ } catch (error) {
7106
+ if (isInternalError(error)) throw error;
7107
+ return notOk(refWriteFailure(error, stage));
7108
+ }
7109
+ }
6911
7110
  const RECORDED_FORMS = [
6912
7111
  "hash",
6913
7112
  "prefix",
@@ -7255,7 +7454,8 @@ async function executeMigrateShowPlan(options) {
7255
7454
  if (!checked.ok) return notOk(checked.failure);
7256
7455
  const permitted = checkRunPolicies({
7257
7456
  command: "db migrate",
7258
- appSpaceId: aggregate.app.spaceId,
7457
+ app: appSpaceOf(aggregate),
7458
+ markers: allMarkers,
7259
7459
  inForce,
7260
7460
  ref: namedRef,
7261
7461
  permitPolicyChange: options.permitPolicyChange ?? false,
@@ -7293,16 +7493,20 @@ async function executeMigrateShowPlan(options) {
7293
7493
  if (outcome.kind === "at-head") continue;
7294
7494
  if (outcome.kind === "never-planned") return notOk(neverPlannedSpaceFailure(outcome, {
7295
7495
  appSpaceId: aggregate.app.spaceId,
7496
+ appSpace: appSpaceOf(aggregate),
7296
7497
  migrationsDir,
7498
+ target: requestedTarget,
7297
7499
  invocation: options.invocation
7298
7500
  }));
7299
7501
  if (outcome.kind === "unreachable" || outcome.kind === "marker-outside-graph") return notOk(unreachableSpaceFailure({
7300
7502
  spaceId: outcome.spaceId,
7301
7503
  fromHash: outcome.kind === "marker-outside-graph" ? outcome.markerHash : contractHashAtMarker(outcome.liveMarker),
7302
- targetHash: outcome.targetHash
7504
+ targetHash: outcome.targetHash,
7505
+ position: databasePositionOf(outcome.kind === "marker-outside-graph" ? outcome.markerHash : outcome.liveMarker?.storageHash)
7303
7506
  }, {
7304
7507
  appSpaceId: aggregate.app.spaceId,
7305
- toArgument: toArgumentFor(requestedTarget, appGraph),
7508
+ appSpace: appSpaceOf(aggregate),
7509
+ target: requestedTarget,
7306
7510
  invocation: options.invocation
7307
7511
  }));
7308
7512
  if (outcome.kind === "unsatisfiable") return notOk(errorRuntime("MIGRATION.NO_INVARIANT_PATH", `Missing required invariants for space "${outcome.spaceId}"`, {
@@ -7864,11 +8068,17 @@ function getReachableRefs(refs, graph) {
7864
8068
  hash: entry.hash
7865
8069
  }] : []).sort((a, b) => a.name.localeCompare(b.name));
7866
8070
  }
7867
- function assertFromIsGraphNode(fromHash, graph, refs) {
8071
+ function assertFromIsGraphNode(fromHash, graph, refs, invocation) {
7868
8072
  try {
7869
8073
  assertHashIsGraphNode(fromHash, graph);
7870
8074
  } catch (error) {
7871
- if (MigrationToolsError.is(error) && error.code === "MIGRATION.HASH_NOT_IN_GRAPH") throw errorPlanForgotTheFlag(fromHash, getReachableRefs(refs, graph), { cause: error });
8075
+ if (MigrationToolsError.is(error) && error.code === "MIGRATION.HASH_NOT_IN_GRAPH") throw errorPlanForgotTheFlag(fromHash, getReachableRefs(refs, graph), {
8076
+ graph,
8077
+ refs
8078
+ }, {
8079
+ cause: error,
8080
+ invocation
8081
+ });
7872
8082
  throw error;
7873
8083
  }
7874
8084
  }
@@ -7881,7 +8091,7 @@ function assertFromIsGraphNode(fromHash, graph, refs) {
7881
8091
  * plan` materialises the contract on top of this; `migration new` needs only
7882
8092
  * the hash.
7883
8093
  */
7884
- function resolveDefaultOriginHash(space) {
8094
+ function resolveDefaultOriginHash(space, invocation) {
7885
8095
  const refs = space.refs;
7886
8096
  const dbRef = refs["db"];
7887
8097
  if (graphIsEmpty(space)) return ok(dbRef ? {
@@ -7893,9 +8103,12 @@ function resolveDefaultOriginHash(space) {
7893
8103
  fromHash: null
7894
8104
  });
7895
8105
  const graph = space.graph();
7896
- if (!dbRef) return notOk(errorPlanOriginUnknown(getReachableRefs(refs, graph)));
8106
+ if (!dbRef) return notOk(errorPlanOriginUnknown(getReachableRefs(refs, graph), {
8107
+ graph,
8108
+ refs
8109
+ }, invocation));
7897
8110
  try {
7898
- assertFromIsGraphNode(dbRef.hash, graph, refs);
8111
+ assertFromIsGraphNode(dbRef.hash, graph, refs, invocation);
7899
8112
  } catch (error) {
7900
8113
  if (CliStructuredError$1.is(error)) return notOk(error);
7901
8114
  throw error;
@@ -7944,7 +8157,7 @@ async function resolveFromPolicy(parsed, input, refs, explicitFromLabel) {
7944
8157
  });
7945
8158
  const graph = input.space.graph();
7946
8159
  try {
7947
- assertFromIsGraphNode(hash, graph, refs);
8160
+ assertFromIsGraphNode(hash, graph, refs, input.invocation);
7948
8161
  } catch (error) {
7949
8162
  if (CliStructuredError$1.is(error)) return notOk(error);
7950
8163
  throw error;
@@ -7968,7 +8181,10 @@ async function resolveFromForPlan(input) {
7968
8181
  fromContract: null,
7969
8182
  defaulted: true
7970
8183
  });
7971
- return notOk(errorPlanOriginUnknown(getReachableRefs(refs, graph)));
8184
+ return notOk(errorPlanOriginUnknown(getReachableRefs(refs, graph), {
8185
+ graph,
8186
+ refs
8187
+ }, input.invocation));
7972
8188
  }
7973
8189
  const resolved = await resolveFromPolicy({
7974
8190
  hash: dbRef.hash,
@@ -7999,7 +8215,10 @@ async function resolveFromForPlan(input) {
7999
8215
  if (!refResult.ok) {
8000
8216
  if (looksLikeFullHash(optionsFrom)) {
8001
8217
  if (graphIsEmpty(space)) return notOk(errorSnapshotMissing(optionsFrom, { viaRef: false }));
8002
- return notOk(errorPlanForgotTheFlag(optionsFrom, getReachableRefs(refs, graph)));
8218
+ return notOk(errorPlanForgotTheFlag(optionsFrom, getReachableRefs(refs, graph), {
8219
+ graph,
8220
+ refs
8221
+ }, { invocation: input.invocation }));
8003
8222
  }
8004
8223
  return notOk(mapRefResolutionError(refResult.failure));
8005
8224
  }
@@ -8020,11 +8239,11 @@ async function resolveToForPlan(optionsTo, input) {
8020
8239
  refs
8021
8240
  });
8022
8241
  if (!refResult.ok) return notOk(mapRefResolutionError(refResult.failure));
8023
- if (refResult.value.provenance.kind === "reserved-empty") return notOk(mapRefResolutionError({
8242
+ if (refResult.value.provenance.kind === "reserved-empty" || refResult.value.hash === "empty") return notOk(mapRefResolutionError({
8024
8243
  kind: "wrong-grammar",
8025
8244
  input: optionsTo,
8026
8245
  expectedGrammar: "contract",
8027
- message: "`@empty` is only valid as an origin (`--from`); planning a migration to the empty contract is not supported through this shortcut",
8246
+ message: "The empty contract is only valid as an origin (`--from @empty`); planning a migration to the empty contract is not supported through this shortcut",
8028
8247
  fix: "Pass `--to` a contract hash, ref name, or migration directory name. To plan starting from an empty database, use `--from @empty`."
8029
8248
  }));
8030
8249
  const resolution = await resolveContractRef(refResult.value, space, {
@@ -8118,11 +8337,15 @@ async function executeMigrationNewCommand(options) {
8118
8337
  }));
8119
8338
  fromHash = matchedHashes[0] ?? null;
8120
8339
  } else {
8121
- const origin = resolveDefaultOriginHash(aggregate.app);
8340
+ const origin = resolveDefaultOriginHash(aggregate.app, {
8341
+ cwd,
8342
+ configPath: options.configPath,
8343
+ dbGiven: false
8344
+ });
8122
8345
  if (!origin.ok) return notOk(origin.failure);
8123
8346
  if (origin.value.kind === "ref-needs-baseline") return notOk(errorRuntime("MIGRATION.HASH_NOT_IN_GRAPH", "The db ref is not a graph node yet", {
8124
8347
  why: `The db ref points at ${origin.value.fromHash}, but ${appMigrationsRelative} contains no migrations, so that contract is not a graph node and nothing can chain from it.`,
8125
- fix: "Run `{bin} migration plan` first: on an empty graph it writes the baseline migration for the db ref alongside the delta, after which `migration new` can chain from it.",
8348
+ fix: "Run `{bin} migration plan` first: on an empty graph it writes the baseline migration for the db ref, and a delta to the emitted contract when the contract changed. Then run `migration new` with `--from` the contract the new migration starts at, which `{bin} migration list` shows: without it, `migration new` starts from the db ref, where a contract that did not change leaves nothing to scaffold.",
8126
8349
  meta: {
8127
8350
  refName: origin.value.refName,
8128
8351
  resolvedHash: origin.value.fromHash
@@ -8444,9 +8667,11 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
8444
8667
  const resolutionSpace = tolerantAggregateResult.value.app;
8445
8668
  const resolutionResult = await resolveFromForPlan({
8446
8669
  optionsFrom: options.from,
8447
- space: resolutionSpace
8670
+ space: resolutionSpace,
8671
+ invocation: invocationOf(options)
8448
8672
  });
8449
8673
  if (!resolutionResult.ok) return notOk(resolutionResult.failure);
8674
+ const fromResolution = resolutionResult.value;
8450
8675
  const warnings = [];
8451
8676
  const plannerWarnings = [];
8452
8677
  const warnForks = (forks) => {
@@ -8505,8 +8730,13 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
8505
8730
  }
8506
8731
  const refusedWith = (texts, resolved) => (conflicts) => planningRefusedError(conflicts, {
8507
8732
  invocation: invocationOf(options),
8508
- from: fromHash ?? void 0,
8509
- to: options.to,
8733
+ migrationPlan: {
8734
+ from: migrationPlanFromRun(options.from, fromResolution),
8735
+ to: options.to === void 0 ? { kind: "default" } : {
8736
+ kind: "reference",
8737
+ reference: options.to
8738
+ }
8739
+ },
8510
8740
  statements: texts,
8511
8741
  resolved
8512
8742
  });
@@ -8585,6 +8815,16 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
8585
8815
  appSpaceId: aggregate.app.spaceId,
8586
8816
  command: "migration plan",
8587
8817
  invocation: invocationOf(options),
8818
+ migrationPlan: {
8819
+ from: migrationPlanFromRun(options.from, fromResolution),
8820
+ to: migrationPlanTo({
8821
+ graph: resolutionSpace.graph(),
8822
+ refs: resolutionSpace.refs
8823
+ }, {
8824
+ kind: "ref",
8825
+ name: toRef.name
8826
+ })
8827
+ },
8588
8828
  forbidden: forbiddingSettingsOfRef(toRef),
8589
8829
  dataLoss: plannedOperations(leg, leg.dataLoss, planned),
8590
8830
  accessChanges: plannedOperations(leg, leg.accessChanges, planned)
@@ -8866,10 +9106,6 @@ function buildAutoBaselinePlanSummary(baselineOpsCount, deltaOpsCount, emittedEx
8866
9106
  if (emittedExtensionDirsCount === 0) return base;
8867
9107
  return `${base}; materialised ${emittedExtensionDirsCount} ${emittedExtensionDirsCount === 1 ? "extension-space migration" : "extension-space migrations"}`;
8868
9108
  }
8869
- /** True when the on-disk graph contains a path fromHash → toHash. */
8870
- function hasMigrationPath(graph, fromHash, toHash) {
8871
- return findPath(graph, fromHash, toHash) !== null;
8872
- }
8873
9109
  function deriveStatusEdgeAnnotations(input) {
8874
9110
  const annotations = /* @__PURE__ */ new Map();
8875
9111
  if (input.showAppliedOverlay) {
@@ -8979,6 +9215,6 @@ async function executeRefListCommand(options) {
8979
9215
  }
8980
9216
  }
8981
9217
  //#endregion
8982
- export { planEverySpace as $, executeMigrationNewCommand as A, labelsText as B, errorPermitPolicyChangeNeedsRef as C, statusForMigrationHash as Ct, executeDbUpdate as D, executeDbSign as E, withWarningFindings as Et, executeRefSetCommand as F, loadContractSource as G, liveMarkerUse as H, findPackageByDirPath as I, looksLikePath as J, loadContractSourceWithStack as K, formatSourceDiagnostic as L, executeRefAdvancement as M, executeRefDeleteCommand as N, executeDbVerify as O, executeRefListCommand as P, migrationSpaceListEntriesFromAggregate as Q, hasMigrationPath as R, enumerateCheckSpaces as S, sourceWarningDiagnostic as St, executeDbInit as T, validateLoadedContract as Tt, loadAggregateIntegrityViolations as U, listRefsByContractHash as V, loadContractRawSafely as W, mapIntegrityViolations as X, mapContractAtError as Y, matchConsents as Z, databasePoliciesInForce as _, runContractSpaceSeedPhase as _t, advanceRefSafely as a, refusePackageCorruptionOnAggregate as at, disposeEmitQueue as b, skippedOperationsText as bt, buildContractSpaceAggregate as c, requireDatabaseForLiveMarkerUse as ct, buildRefAdvancementFields as d, resolveContractRefToSnapshot as dt, preflightRefAdvancement as et, checkSingleTarget as f, resolveFromForPlan as ft, createControlClient as g, retryCommandFor as gt, convertAndDelete as h, resolveToForPlan as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, refuseMissingInvariantPath as it, executeMigrationPlanCommand as j, executeMigrateShowPlan as k, buildMigrationSpaceGraphEntries as l, resolveAppTargetPath as lt, contractValidationMeta as m, resolveStatements as mt, NO_REF_ADVANCEMENT as n, refuseContractSpaceIntegrity as nt, appContractStandInFromIdentity as o, refuseUnknownInvariants as ot, computeRefAdvancementName as p, resolveMigrationRef as pt, loadContractSpaceAggregateForCli as q, RECORDED_CONTRACT_REF_FORMS as r, refuseDeclaredExtensionTargetMismatch as rt, appliedHashesFromLedger as s, renamedAndDeleted as st, ALL_CONTRACT_REF_FORMS as t, readMigrationRefs as tt, buildReadAggregate as u, resolveContractRef$1 as ut, declaredSettingsText as v, runMigrationCheck as vt, executeContractEmit as w, toDeclaredExtensionsFromRaw as wt, enrichContract as x, snapshotVerifierFor as xt, deriveStatusEdgeAnnotations as y, runMigrationList as yt, isStatementVerb as z };
9218
+ export { preflightRefAdvancement as $, executeMigrationNewCommand as A, listRefsByContractHash as B, errorPermitPolicyChangeNeedsRef as C, toDeclaredExtensionsFromRaw as Ct, executeDbUpdate as D, executeDbSign as E, writeAdvancedRef as Et, executeRefSetCommand as F, loadContractSourceWithStack as G, loadAggregateIntegrityViolations as H, findPackageByDirPath as I, mapContractAtError as J, loadContractSpaceAggregateForCli as K, formatSourceDiagnostic as L, executeRefAdvancement as M, executeRefDeleteCommand as N, executeDbVerify as O, executeRefListCommand as P, planEverySpace as Q, isStatementVerb as R, enumerateCheckSpaces as S, statusForMigrationHash as St, executeDbInit as T, withWarningFindings as Tt, loadContractRawSafely as U, liveMarkerUse as V, loadContractSource as W, matchConsents as X, mapIntegrityViolations as Y, migrationSpaceListEntriesFromAggregate as Z, databasePoliciesInForce as _, runMigrationCheck as _t, advanceRefSafely as a, refuseUnknownInvariants as at, disposeEmitQueue as b, snapshotVerifierFor as bt, buildContractSpaceAggregate as c, resolveAppTargetPath as ct, buildRefAdvancementFields as d, resolveFromForPlan as dt, readMigrationRefs as et, checkSingleTarget as f, resolveMigrationRef as ft, createControlClient as g, runContractSpaceSeedPhase as gt, convertAndDelete as h, retryCommandFor as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, refusePackageCorruptionOnAggregate as it, executeMigrationPlanCommand as j, executeMigrateShowPlan as k, buildMigrationSpaceGraphEntries as l, resolveContractRef$1 as lt, contractValidationMeta as m, resolveToForPlan as mt, NO_REF_ADVANCEMENT as n, refuseDeclaredExtensionTargetMismatch as nt, appContractStandInFromIdentity as o, renamedAndDeleted as ot, computeRefAdvancementName as p, resolveStatements as pt, looksLikePath as q, RECORDED_CONTRACT_REF_FORMS as r, refuseMissingInvariantPath as rt, appliedHashesFromLedger as s, requireDatabaseForLiveMarkerUse as st, ALL_CONTRACT_REF_FORMS as t, refuseContractSpaceIntegrity as tt, buildReadAggregate as u, resolveContractRefToSnapshot as ut, declaredSettingsText as v, runMigrationList as vt, executeContractEmit as w, validateLoadedContract as wt, enrichContract as x, sourceWarningDiagnostic as xt, deriveStatusEdgeAnnotations as y, skippedOperationsText as yt, labelsText as z };
8983
9219
 
8984
- //# sourceMappingURL=ref-Ba6Mk6Rg-DKaPWk2l.mjs.map
9220
+ //# sourceMappingURL=ref-C7TozKnq-C4UYYbRT.mjs.map