@prisma/orm-toolchain 8.0.0-rc.22-dev.7 → 8.0.0-rc.22-dev.9

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.
@@ -8,25 +8,26 @@ import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigratio
8
8
  import { i as findPathWithDecision, r as findPath } from "./migration-graph-BoiiZAaU-DLht12k7.mjs";
9
9
  import { a as isValidSpaceId, c as spaceMigrationDirectory, l as spaceRefsDirectory, o as listContractSpaceDirectories, s as readContractSpaceHeadRef, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-B12R3P5U-CfBKlBjj.mjs";
10
10
  import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-CW5yVjgx.mjs";
11
- import { B as errorRefSetEmptySentinel, D as errorFromCaught, E as errorFileNotFound, F as errorPathUnreachable, G as errorSpaceNotFound, H as errorRuntime, I as errorPlanForgotTheFlag, J as errorStatementInvalid, K as errorStatementAnswersNoQuestion, L as errorPlanOriginUnknown, N as errorMigrationPlanningFailed, Q as errorTargetMigrationNotSupported, R as errorPlanProducedNoOperations, S as errorContractValidationFailed, V as errorRefSetHashNotInGraph, W as errorSnapshotMissing, X as errorStatementOriginUnknown, Y as errorStatementNeedsMigrationFile, Z as errorStatementUnresolved, _ as errorAmbiguousMigrationRef, _t as toStructuralEdge, at as printedPath, c as cliCommand, d as closeQuietly, dt as resolveMigrationPaths, et as errorUnexpected, f as collectDeclaredInvariants, ft as runCommandAction, h as editFileAction, ht as statementFlag, it as migrationsDirFor, k as errorInvalidSpaceId, l as cliErrorFromStructured, lt as requireLiveDatabase, n as CliStructuredError$1, nt as mapRefResolutionError, ot as printedPlanCommand, pt as selfEmitCommand, q as errorStatementDidNotResolveLoss, r as STORE_ORIGIN_SNAPSHOT_STEPS, s as chooseAction, st as readContractEnvelope, t as ActionableCliError, tt as getTargetMigrations, ut as resolveContractPath, v as errorConfigValidation$1, vt as writtenMigrationRunCommand, x as errorContractConfigMissing, y as errorConsentUnused, z as errorRefSetBundleNotFound } from "./caught-errors-DRiDJHfQ-Du9rLuFa.mjs";
11
+ import { $ as errorTargetMigrationNotSupported, B as errorRefSetBundleNotFound, D as errorFromCaught, E as errorFileNotFound, G as errorSnapshotMissing, H as errorRefSetHashNotInGraph, I as errorPathUnreachable, J as errorStatementDidNotResolveLoss, K as errorSpaceNotFound, L as errorPlanForgotTheFlag, M as errorMigrationHasUnfilledPlaceholders, P as errorMigrationPlanningFailed, Q as errorStatementUnresolved, R as errorPlanOriginUnknown, S as errorContractValidationFailed, U as errorRuntime, V as errorRefSetEmptySentinel, X as errorStatementNeedsMigrationFile, Y as errorStatementInvalid, Z as errorStatementOriginUnknown, _ as errorAmbiguousMigrationRef, at as migrationsDirFor, c as cliCommand, ct as readContractEnvelope, d as closeQuietly, dt as resolveContractPath, f as collectDeclaredInvariants, ft as resolveMigrationPaths, gt as statementFlag, h as editFileAction, k as errorInvalidSpaceId, l as cliErrorFromStructured, mt as selfEmitCommand, n as CliStructuredError$1, nt as getTargetMigrations, ot as printedPath, pt as runCommandAction, q as errorStatementAnswersNoQuestion, r as STORE_ORIGIN_SNAPSHOT_STEPS, rt as mapRefResolutionError, s as chooseAction, st as printedPlanCommand, t as ActionableCliError, tt as errorUnexpected, ut as requireLiveDatabase, v as errorConfigValidation$1, vt as toStructuralEdge, x as errorContractConfigMissing, y as errorConsentUnused, yt as writtenMigrationRunCommand, z as errorPlanProducedNoOperations } from "./caught-errors-Cll-zcA1-9iYL-SM_.mjs";
12
12
  import { r as getEmittedArtifactPaths, t as emit } from "./exports-CVgs3YWV-BF4rqnxF.mjs";
13
13
  import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-DxpNgxfZ-BfqA-H7V.mjs";
14
14
  import { d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o as refsByContractHash, t as HEAD_REF_NAME, u as validateRefValue } from "./refs-DM3q3IZC-BC6H6P0X.mjs";
15
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-DS_usja4.mjs";
16
+ import { a as writeMigrationTs, n as formatMigrationTs } from "./migration-ts-DDgjsR1O.mjs";
16
17
  import { c as internalImportRoot, o as importRootForDependencies, r as createImportSpecifierResolver, t as ImportRootError } from "./import-roots-C67dScb8.mjs";
17
18
  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-Eo0QHp4f.mjs";
18
- import { a as writeMigrationTs } from "./migration-ts-DDgjsR1O.mjs";
19
19
  import { createRequire } from "node:module";
20
20
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
21
21
  import { CliStructuredError } from "@prisma/orm-framework/errors/control";
22
- import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, enumValueCoordinateFromJson, enumValueStatementText, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, planOriginOf } from "@prisma/orm-framework/components/control";
22
+ import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, enumValueCoordinateFromJson, enumValueStatementText, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, planOriginOf, valueObjectFieldStatementText } from "@prisma/orm-framework/components/control";
23
23
  import { InternalError } from "@prisma/orm-framework/utils/internal-error";
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
26
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
27
27
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
28
+ import { type } from "arktype";
28
29
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
29
- import { asNamespaceId, valueObjectAt } from "@prisma/orm-framework/contract/types";
30
+ import { asNamespaceId, valueObjectAt, valueObjectsWithCoordinates } from "@prisma/orm-framework/contract/types";
30
31
  import { keepInternalSpecifiers } from "@prisma/orm-framework/components/emission";
31
32
  import { UNBOUND_NAMESPACE_ID, changedElementCoordinates } from "@prisma/orm-framework/components/ir";
32
33
  import { notOk, ok } from "@prisma/orm-framework/utils/result";
@@ -35,7 +36,7 @@ import { isDeepStrictEqual } from "node:util";
35
36
  import { canonicalStringify } from "@prisma/orm-framework/utils/canonical-stringify";
36
37
  import { abortable } from "@prisma/orm-framework/utils/abortable";
37
38
  import { resolve as resolve$1 } from "node:path";
38
- //#region ../../../1-framework/3-tooling/cli/dist/ref-CKUrXPT8.mjs
39
+ //#region ../../../1-framework/3-tooling/cli/dist/ref-hKV9pGrC.mjs
39
40
  /**
40
41
  * 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
42
  */
@@ -177,6 +178,35 @@ function enrichContract(ir, components) {
177
178
  extensions: sortDeepTyped(extensions)
178
179
  };
179
180
  }
181
+ const OPEN = " return [\n ";
182
+ const CLOSE = ",\n ];";
183
+ /**
184
+ * `calls`, a call or calls separated by commas, as a written `migration.ts` holds them in its
185
+ * `operations` list: formatted as `migration plan` formats the file, with the indentation it gives
186
+ * each line after the first.
187
+ */
188
+ async function asWritten(calls) {
189
+ const formatted = await formatMigrationTs(`class M {\n get operations() {\n return [${calls}];\n }\n}\n`);
190
+ const start = formatted.indexOf(OPEN);
191
+ const end = formatted.lastIndexOf(CLOSE);
192
+ return start === -1 || end === -1 ? calls : formatted.slice(start + 19, end);
193
+ }
194
+ /** The facts, with each edit that keeps data quoted as the written `migration.ts` holds its calls. */
195
+ async function withEditsAsWritten(facts) {
196
+ if (facts.rowsHoldingValue === void 0) return facts;
197
+ const written = async (edit) => ({
198
+ ...edit,
199
+ remove: await asWritten(edit.remove),
200
+ replaceWith: await asWritten(edit.replaceWith)
201
+ });
202
+ return {
203
+ ...facts,
204
+ rowsHoldingValue: await Promise.all(facts.rowsHoldingValue.map(async (report) => report.keepDataEdit === void 0 ? report : {
205
+ ...report,
206
+ keepDataEdit: await written(report.keepDataEdit)
207
+ }))
208
+ };
209
+ }
180
210
  /** The operation classes `db update` applies. */
181
211
  const DB_UPDATE_POLICY = { allowedOperationClasses: [
182
212
  "additive",
@@ -248,50 +278,60 @@ function dbUpdateRowsWithoutValueAdvice(reports, databaseStorageHash, invocation
248
278
  ];
249
279
  return [...planned, editFileAction("Make the field optional in the contract source")];
250
280
  }
251
- function renameToNewMember(report) {
252
- return statementFlag({
253
- verb: "rename",
254
- text: `${report.enumValue}:${report.enumName}.<new member>`
255
- });
281
+ function distinct(values) {
282
+ return [...new Set(values)];
256
283
  }
257
- function newMember(report, invocation) {
258
- return `To keep that data under a new enum value, add a member to enum "${report.enumName}" in the contract source, run ${quoted$1(cliCommand(invocation, "contract emit"))}`;
284
+ /** The first report of each enum value, in the order the reports name them. */
285
+ function onePerEnumValue(reports) {
286
+ return reports.filter((report, index) => reports.findIndex(({ enumValue }) => enumValue === report.enumValue) === index);
259
287
  }
260
- /** The edit the target gives that keeps the data, as the advice writes it. */
261
- function swapCalls(edit) {
262
- return `replace ${edit.remove} with ${edit.replaceWith}`;
288
+ function renameFlags(reports) {
289
+ return onePerEnumValue(reports).map(({ enumValue, enumName }) => statementFlag({
290
+ verb: "rename",
291
+ text: `${enumValue}:${enumName}.<new member>`
292
+ }));
263
293
  }
264
- const KEPT_VALUE = "where \"<stored value>\" is a stored value the enum keeps";
265
- /** The run's statements, without the delete of `enumValue` that failed. */
266
- function otherStatements$1(invocation, enumValue) {
267
- const failed = statementFlag({
294
+ function deleteFlags(reports) {
295
+ return onePerEnumValue(reports).map(({ enumValue }) => statementFlag({
268
296
  verb: "delete",
269
297
  text: enumValue
270
- });
271
- return (invocation.statementArgs ?? []).filter((flag) => flag !== failed);
272
- }
273
- /** The way out when a required column's data holds a stored value `db update` removes. */
274
- function dbUpdateRowsHoldingValueAdvice(report, databaseStorageHash, invocation) {
275
- const others = otherStatements$1(invocation, report.enumValue);
276
- const deleteFlag = statementFlag({
277
- verb: "delete",
278
- text: report.enumValue
279
- });
280
- const rename = chooseAction(`${newMember(report, invocation)}, then run ${quoted$1(cliCommand(invocation, "db update", [...others, renameToNewMember(report)]))}`);
281
- if (databaseStorageHash === void 0) return [rename, chooseAction(`To keep that data under another stored value, change the stored value ${JSON.stringify(report.value)} to one the enum keeps in the database yourself, then re-run ${quoted$1(cliCommand(invocation, "db update", [...others, deleteFlag]))}`)];
282
- const { keepDataEdit } = report;
283
- if (keepDataEdit === void 0) return [rename];
284
- return [rename, chooseAction(`To keep that data by hand, plan the change with ${quoted$1(printedPlanCommand(invocation, databaseStorageHash, [...others, deleteFlag]))}, ${swapCalls(keepDataEdit)} in the migration.ts it writes, ${KEPT_VALUE}, ${runWrittenFile(invocation)}`)];
298
+ }));
285
299
  }
286
- function migrateRowsHoldingValueAdvice(report, failedMigration, invocation) {
300
+ function newMember(reports, invocation) {
301
+ const enumNames = distinct(reports.map(({ enumName }) => `"${enumName}"`));
302
+ return `To keep that data under a new enum value, add a member to ${enumNames.length === 1 ? `enum ${enumNames[0]}` : `each of enums ${enumNames.join(", ")}`} in the contract source, run ${quoted$1(cliCommand(invocation, "contract emit"))}`;
303
+ }
304
+ /** The edits the target gives that keep the data, each call on its own lines as the migration.ts holds it; undefined when it gives none. */
305
+ function swapCalls(reports) {
306
+ const swaps = reports.flatMap(({ keepDataEdit }) => keepDataEdit === void 0 ? [] : [`Replace:\n${keepDataEdit.remove}\nwith:\n${keepDataEdit.replaceWith}`]);
307
+ return swaps.length === 0 ? void 0 : swaps.join("\n");
308
+ }
309
+ const KEPT_VALUE = "where <stored value> is a stored value the enum keeps";
310
+ /** The run's statements, without the deletes of the enum values that failed. */
311
+ function otherStatements$1(invocation, reports) {
312
+ const failed = deleteFlags(reports);
313
+ return (invocation.statementArgs ?? []).filter((flag) => !failed.includes(flag));
314
+ }
315
+ function storedValuesText(reports) {
316
+ const values = distinct(reports.map(({ value }) => JSON.stringify(value)));
317
+ 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`;
318
+ }
319
+ /** The way out when the data of required columns holds stored values `db update` removes. */
320
+ function dbUpdateRowsHoldingValueAdvice(reports, databaseStorageHash, invocation) {
321
+ const others = otherStatements$1(invocation, reports);
322
+ const deletes = deleteFlags(reports);
323
+ const rename = chooseAction(`${newMember(reports, invocation)}, then run ${quoted$1(cliCommand(invocation, "db update", [...others, ...renameFlags(reports)]))}`);
324
+ 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(cliCommand(invocation, "db update", [...others, ...deletes]))}`)];
325
+ const swaps = swapCalls(reports);
326
+ if (swaps === void 0) return [rename];
327
+ 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}`)];
328
+ }
329
+ function migrateRowsHoldingValueAdvice(reports, failedMigration, invocation) {
287
330
  const { file, run } = failedMigrationFile(failedMigration);
288
- const { keepDataEdit } = report;
289
- const byHand = keepDataEdit === void 0 ? [] : [editFileAction(`To keep that data by hand, ${swapCalls(keepDataEdit)} in ${file}, ${KEPT_VALUE}, ${run}, and re-run ${dbMigrateCommand(invocation)}`)];
331
+ const swaps = swapCalls(reports);
332
+ const byHand = swaps === void 0 ? [] : [editFileAction(`To keep that data by hand, make the edits below in ${file}, ${KEPT_VALUE}, ${run}, and re-run ${dbMigrateCommand(invocation)}.\n${swaps}`)];
290
333
  if (failedMigration === void 0) return byHand;
291
- return [replan(`${newMember(report, invocation)}, delete`, [renameToNewMember(report)], failedMigration, `\`${statementFlag({
292
- verb: "delete",
293
- text: report.enumValue
294
- })}\``, `put any code you copied into the migration.ts it writes, ${runWrittenFile(invocation)}`), ...byHand];
334
+ 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];
295
335
  }
296
336
  /** Where the operation that updates the rows goes among the operations of a migration.ts that replaces a check. */
297
337
  function betweenTheChecks(report, replacedCheck) {
@@ -672,18 +712,19 @@ function parseConsentStatement(statement) {
672
712
  });
673
713
  }
674
714
  function formsFix(verb) {
675
- return `Write the statement as --${verb} <field>, where the field is Model.field or namespace.Model.field as the destination contract names it, for example --${verb} User.age.`;
715
+ return verb === "convert" ? "Write the statement as --convert <field>, where the field is Model.field or namespace.Model.field as the destination contract names it, for example --convert User.age, or as --convert <variant>, Variant or namespace.Variant, for a variant whose discriminator value changed." : `Write the statement as --${verb} <field>, where the field is Model.field or namespace.Model.field as the destination contract names it, for example --${verb} User.age.`;
676
716
  }
677
- /** Parses the text of one convert or backfill statement, `Model.field` or `namespace.Model.field`. */
717
+ /** Parses the text of one convert or backfill statement, `Model.field` or `namespace.Model.field`, or a convert's `Variant`. */
678
718
  function parseFieldStatement(statement) {
679
719
  const invalid = (why) => notOk(errorStatementInvalid(statement, why, formsFix(statement.verb)));
680
720
  if (statement.text.includes(":")) return invalid("The statement names one field, not an old and a new name.");
681
721
  const segments = statement.text.split(".");
682
722
  if (segments.some((segment) => segment === "")) return invalid(`"${statement.text}" has an empty name.`);
683
723
  const [first, second, third] = segments;
684
- if (first === void 0 || second === void 0) return invalid(`"${statement.text}" names a model; a --${statement.verb} statement names a field.`);
724
+ if (first === void 0) return invalid(`"${statement.text}" has an empty name.`);
725
+ if (second === void 0 && statement.verb !== "convert") return invalid(`"${statement.text}" names a model; a --${statement.verb} statement names a field.`);
685
726
  if (segments.length > 3) return invalid(`"${statement.text}" has ${segments.length} names; at most three are allowed.`);
686
- const field = third === void 0 ? [first, second] : [
727
+ const field = second === void 0 ? [first] : third === void 0 ? [first, second] : [
687
728
  first,
688
729
  second,
689
730
  third
@@ -773,16 +814,60 @@ const ENTITY_WORDS = {
773
814
  model: "model",
774
815
  field: "field",
775
816
  enumValue: "enum value",
817
+ valueObjectField: "value object field",
776
818
  storage: "storage"
777
819
  };
820
+ function modelOf(contract, coordinate) {
821
+ const namespaces = contract.domain.namespaces;
822
+ const namespace = Object.hasOwn(namespaces, coordinate.namespaceId) ? namespaces[coordinate.namespaceId] : void 0;
823
+ return namespace !== void 0 && Object.hasOwn(namespace.models, coordinate.model) ? namespace.models[coordinate.model] : void 0;
824
+ }
825
+ /** The discriminator value a variant has in its base model, or `undefined` when the model is no variant of the contract. */
826
+ function variantValue(contract, coordinate) {
827
+ const base = modelOf(contract, coordinate)?.base;
828
+ if (base === void 0) return void 0;
829
+ const variants = modelOf(contract, {
830
+ namespaceId: base.namespace,
831
+ model: base.model
832
+ })?.variants;
833
+ return Object.entries(variants ?? {}).find(([, variant]) => variant.namespace === coordinate.namespaceId && variant.model === coordinate.model)?.[0];
834
+ }
835
+ /** Whether a model is a variant in both contracts whose discriminator value changed between them. */
836
+ function variantValueChanged(origin, originModel, destination, destinationModel) {
837
+ const from = variantValue(origin, originModel);
838
+ const to = variantValue(destination, destinationModel);
839
+ return from !== void 0 && to !== void 0 && from !== to;
840
+ }
841
+ /**
842
+ * The variants a base model has in the destination and not in the origin, other than `renamedTo`:
843
+ * the models a removed variant of that base can have been renamed to.
844
+ */
845
+ function newVariantsOfBase(origin, destination, variant, renamedTo) {
846
+ const base = modelOf(origin, variant)?.base;
847
+ if (base === void 0) return [];
848
+ const baseCoordinate = {
849
+ namespaceId: base.namespace,
850
+ model: base.model
851
+ };
852
+ const models = (contract) => Object.values(modelOf(contract, baseCoordinate)?.variants ?? {}).map((each) => ({
853
+ namespaceId: each.namespace,
854
+ model: each.model
855
+ }));
856
+ const before = models(origin);
857
+ const same = (left) => (right) => left.namespaceId === right.namespaceId && left.model === right.model;
858
+ return models(destination).filter((each) => !before.some(same(each)) && !renamedTo.some(same(each))).map((each) => ({
859
+ ...each,
860
+ namespaceId: asNamespaceId(each.namespaceId)
861
+ }));
862
+ }
778
863
  const NAMESPACE_RENAMES = "namespace";
779
864
  const ENUM_VALUE_RENAMES = "enumValue";
865
+ const VALUE_OBJECT_FIELD_RENAMES = "valueObjectField";
780
866
  const MODEL_RENAMES = "model";
781
867
  const FIELD_RENAMES = "field";
782
868
  const LISTED_LIMIT = 20;
783
869
  const CHECK_NAMES_FIX = "The old name must exist in the origin contract and not in the destination contract, and the new name the other way round. Names match exactly, including case.";
784
870
  const STORED_NAME_ONLY = "If only the stored name changed (@map or @@map), a statement cannot state that in this release, and a plan without it drops and creates what the model or field is stored in, with its data. With migration plan, edit the planned migration.ts to rename the stored name instead of dropping and creating it. With db update, rename it in the database yourself first, then run db update, which then finds nothing that loses data.";
785
- const VALUE_OBJECT_FIX = "Leave value objects and their fields out of the statements.";
786
871
  const REPEATED_NAME_FIX = "Give each model, field or enum value at most one statement, and each new name to one model, field or enum value only.";
787
872
  function qualifiedModel(coordinate) {
788
873
  return modelDisplayName(coordinate);
@@ -806,6 +891,9 @@ function enumText(contract, namespaceId, name) {
806
891
  function qualifiedEnumValue(coordinate) {
807
892
  return `${displayName(coordinate.namespaceId, coordinate.enum)}.${coordinate.member}`;
808
893
  }
894
+ function qualifiedValueObjectField(coordinate) {
895
+ return `${displayName(coordinate.namespaceId, coordinate.valueObject)}.${coordinate.field}`;
896
+ }
809
897
  function listed(names) {
810
898
  if (names.length === 0) return "(none)";
811
899
  const sorted = [...names].sort();
@@ -849,7 +937,7 @@ function missing(reason) {
849
937
  function valueObjectRefusal(name) {
850
938
  return {
851
939
  reason: `"${name}" is a value object, and value object renames are not supported in this release`,
852
- fix: VALUE_OBJECT_FIX,
940
+ fix: `Leave the value object itself out of the statements. A statement can rename, delete or backfill its fields, as --rename ${name}.<field>:${name}.<new name>.`,
853
941
  valueObject: name
854
942
  };
855
943
  }
@@ -958,11 +1046,62 @@ function readEnumValue(state, side, namespaceId, name, member) {
958
1046
  function declaresEnums(contract) {
959
1047
  return Object.values(contract.contract.domain.namespaces).some((namespace) => Object.keys(enumsOf(namespace)).length > 0);
960
1048
  }
1049
+ function lookupValueObject(contract, namespaceId, name) {
1050
+ const storage = contract.contract.storage;
1051
+ const declaring = Object.keys(storage.namespaces).flatMap((id) => {
1052
+ if (namespaceId !== void 0 && id !== namespaceId) return [];
1053
+ const valueObject = valueObjectAt(storage, {
1054
+ plane: "storage",
1055
+ namespaceId: id,
1056
+ entityKind: "valueObject",
1057
+ entityName: name
1058
+ });
1059
+ return valueObject === void 0 ? [] : [{
1060
+ namespaceId: id,
1061
+ valueObject
1062
+ }];
1063
+ });
1064
+ const [only] = declaring;
1065
+ if (only !== void 0 && declaring.length === 1) return {
1066
+ kind: "found",
1067
+ ...only
1068
+ };
1069
+ if (declaring.length > 1) {
1070
+ const candidates = declaring.map(({ namespaceId: id }) => `${id}.${name}`).sort();
1071
+ return {
1072
+ kind: "refused",
1073
+ reason: `"${name}" is a value object in more than one namespace of the ${contract.name} contract (${listed(candidates)})`,
1074
+ fix: `Name the value object with its namespace, for example ${candidates[0]}.`
1075
+ };
1076
+ }
1077
+ const within = namespaceId === void 0 ? "" : ` in namespace "${namespaceId}"`;
1078
+ return {
1079
+ kind: "missing",
1080
+ ...missing(`the ${contract.name} contract has no value object "${name}"${within}`)
1081
+ };
1082
+ }
1083
+ function readValueObjectField(state, side, namespaceId, name, field) {
1084
+ const contract = side === "old" ? state.origin : state.destination;
1085
+ const lookup = lookupValueObject(contract, (side === "old" && namespaceId !== void 0 ? state.originOfRenamedNamespace.get(namespaceId) : void 0) ?? namespaceId, name);
1086
+ if (lookup.kind !== "found") return notOk(lookup);
1087
+ const fields = Object.keys(lookup.valueObject.fields);
1088
+ if (!fields.includes(field)) return notOk(missing(`the ${contract.name} value object "${enumText(contract, lookup.namespaceId, name)}" has no field "${field}" (fields: ${listed(fields)})`));
1089
+ return ok({
1090
+ entity: "valueObjectField",
1091
+ coordinate: {
1092
+ namespaceId: asNamespaceId(lookup.namespaceId),
1093
+ valueObject: name,
1094
+ field
1095
+ },
1096
+ fields
1097
+ });
1098
+ }
961
1099
  function readingText(reading) {
962
1100
  switch (reading.entity) {
963
1101
  case "model": return `namespace "${reading.coordinate.namespaceId}" model "${reading.coordinate.model}"`;
964
1102
  case "field": return `model "${reading.coordinate.model}" field "${reading.coordinate.field}"`;
965
1103
  case "enumValue": return `enum "${reading.coordinate.enum}" value "${reading.coordinate.member}"`;
1104
+ case "valueObjectField": return `value object "${reading.coordinate.valueObject}" field "${reading.coordinate.field}"`;
966
1105
  }
967
1106
  }
968
1107
  function qualifiedReading(reading) {
@@ -970,6 +1109,7 @@ function qualifiedReading(reading) {
970
1109
  case "model": return qualifiedModel(reading.coordinate);
971
1110
  case "field": return qualifiedField(reading.coordinate);
972
1111
  case "enumValue": return qualifiedEnumValue(reading.coordinate);
1112
+ case "valueObjectField": return qualifiedValueObjectField(reading.coordinate);
973
1113
  }
974
1114
  }
975
1115
  /** What a reading sits in, which a rename can give another name so that the reading stops colliding. */
@@ -978,21 +1118,27 @@ function readingContainer(reading) {
978
1118
  case "model": return `namespace "${reading.coordinate.namespaceId}"`;
979
1119
  case "field": return `model "${reading.coordinate.model}"`;
980
1120
  case "enumValue": return `enum "${reading.coordinate.enum}"`;
1121
+ case "valueObjectField": return `value object "${reading.coordinate.valueObject}"`;
981
1122
  }
982
1123
  }
1124
+ function joinedAs(texts) {
1125
+ return texts.length === 2 ? `both as ${texts[0]} and as ${texts[1]}` : `as ${texts.slice(0, -1).join(", as ")} and as ${texts.at(-1)}`;
1126
+ }
983
1127
  /**
984
- * An enum value reading beside the model and field readings of the same name: the one that
985
- * resolves, or a refusal naming each reading when more than one does.
1128
+ * The enum value and value object field readings beside the model or field reading of the same
1129
+ * name: the one that resolves, `primary`'s failure when none does, or a refusal naming each
1130
+ * reading when more than one does.
986
1131
  */
987
- function withEnumValueReading(text, other, enumValue) {
988
- if (!enumValue.ok) return other;
989
- if (!other.ok) return enumValue;
990
- const readings = [other.value, enumValue.value];
1132
+ function oneReading(text, primary, others) {
1133
+ const readings = [primary, ...others].flatMap((reading) => reading.ok ? [reading.value] : []);
1134
+ const [only] = readings;
1135
+ if (only === void 0) return primary;
1136
+ if (readings.length === 1) return ok(only);
991
1137
  const nameable = readings.filter((reading) => qualifiedReading(reading) !== text);
992
1138
  const unnameable = readings.find((reading) => qualifiedReading(reading) === text);
993
1139
  const written = nameable.map((reading) => `${qualifiedReading(reading)} for the ${ENTITY_WORDS[reading.entity]}`);
994
1140
  return notOk({
995
- reason: `"${text}" resolves both as ${readingText(other.value)} and as ${readingText(enumValue.value)}`,
1141
+ reason: `"${text}" resolves ${joinedAs(readings.map(readingText))}`,
996
1142
  fix: unnameable === void 0 ? `Name it with its namespace: ${written.join(", ")}.` : `Write ${written.join(", ")}. The ${ENTITY_WORDS[unnameable.entity]} cannot be named apart from it: rename ${readings.map(readingContainer).join(" or ")} so that only one reading resolves.`
997
1143
  });
998
1144
  }
@@ -1063,6 +1209,17 @@ function readNewField(state, namespaceId, modelName, field) {
1063
1209
  function readField(state, side, namespaceId, modelName, field) {
1064
1210
  return side === "old" ? readOldField(state, namespaceId, modelName, field) : readNewField(state, namespaceId, modelName, field);
1065
1211
  }
1212
+ /** A value object field named as `Model.field.valueObjectField`, which a statement names through its value object instead. */
1213
+ function valueObjectFieldThroughModel(contract, modelName, fieldName, valueObjectField) {
1214
+ const lookup = lookupModel(contract, void 0, modelName);
1215
+ if (lookup.kind !== "found" || !hasField(lookup.model, fieldName)) return void 0;
1216
+ const type = lookup.model.fields[fieldName]?.type;
1217
+ if (type?.kind !== "valueObject") return void 0;
1218
+ return {
1219
+ reason: `"${modelName}.${fieldName}" holds value object "${type.entityName}", and a statement names a value object field through its value object, not through a model field`,
1220
+ fix: `Name the field as ${type.entityName}.${valueObjectField}.`
1221
+ };
1222
+ }
1066
1223
  function readSide(state, side, segments) {
1067
1224
  if (segments.length === 1) return readModel(state, side, void 0, segments[0]);
1068
1225
  const contract = side === "old" ? state.origin : state.destination;
@@ -1076,7 +1233,12 @@ function readSide(state, side, segments) {
1076
1233
  });
1077
1234
  const asField = qualified.ok || !dotted.ok ? qualified : dotted;
1078
1235
  const asEnumValue = readEnumValue(state, side, first, second, third);
1079
- if (asField.ok || asEnumValue.ok || !declaresEnums(contract)) return withEnumValueReading(segments.join("."), asField, asEnumValue);
1236
+ const asValueObjectField = readValueObjectField(state, side, first, second, third);
1237
+ if (asField.ok || asEnumValue.ok || asValueObjectField.ok) return oneReading(segments.join("."), asField, [asEnumValue, asValueObjectField]);
1238
+ const throughModel = valueObjectFieldThroughModel(contract, first, second, third);
1239
+ if (throughModel !== void 0) return notOk(throughModel);
1240
+ if (containerNames(contract).valueObjects.has(second)) return asValueObjectField;
1241
+ if (!declaresEnums(contract)) return asField;
1080
1242
  return notOk({
1081
1243
  ...missing(`"${segments.join(".")}" resolves neither as namespace.Model.field (${asField.failure.reason}) nor as namespace.Enum.value (${asEnumValue.failure.reason})`),
1082
1244
  ...ifDefined("modelWithoutCounterpart", asField.failure.modelWithoutCounterpart)
@@ -1086,13 +1248,14 @@ function readSide(state, side, segments) {
1086
1248
  const asModel = readModel(state, side, first, second);
1087
1249
  const asField = readField(state, side, void 0, first, second);
1088
1250
  const asEnumValue = readEnumValue(state, side, void 0, first, second);
1251
+ const asValueObjectField = readValueObjectField(state, side, void 0, first, second);
1089
1252
  if (asModel.ok && asField.ok) return notOk({
1090
1253
  reason: `"${first}.${second}" resolves both as namespace "${first}" model "${second}" and as model "${first}" field "${second}"`,
1091
1254
  fix: "Write the field as namespace.Model.field if you mean the field."
1092
1255
  });
1093
- if (asModel.ok || asField.ok) return withEnumValueReading(`${first}.${second}`, asModel.ok ? asModel : asField, asEnumValue);
1094
- if (asEnumValue.ok) return asEnumValue;
1256
+ if (asModel.ok || asField.ok || asEnumValue.ok || asValueObjectField.ok) return oneReading(`${first}.${second}`, asModel.ok ? asModel : asField, [asEnumValue, asValueObjectField]);
1095
1257
  const names = containerNames(contract);
1258
+ if (names.valueObjects.has(first) && !names.namespaces.has(first) && !names.models.has(first)) return asValueObjectField;
1096
1259
  if (names.enums.has(first) && !names.namespaces.has(first) && !names.models.has(first)) return asEnumValue;
1097
1260
  const hasNamespaces = names.namespaces.size > 0;
1098
1261
  const hasEnums = declaresEnums(contract);
@@ -1113,13 +1276,14 @@ function readSide(state, side, segments) {
1113
1276
  ...ifDefined("modelWithoutCounterpart", asField.failure.modelWithoutCounterpart)
1114
1277
  });
1115
1278
  }
1116
- /** The names a side's first segment can be: a namespace, a model, or an enum of the contract. */
1279
+ /** The names a side's first segment can be: a namespace, a model, an enum or a value object of the contract. */
1117
1280
  function containerNames(contract) {
1118
1281
  const namespaces = Object.entries(contract.contract.domain.namespaces);
1119
1282
  return {
1120
1283
  namespaces: new Set(namespaces.flatMap(([id]) => id === UNBOUND_NAMESPACE_ID ? [] : [id])),
1121
1284
  models: new Set(namespaces.flatMap(([, namespace]) => Object.keys(namespace.models))),
1122
- enums: new Set(namespaces.flatMap(([, namespace]) => Object.keys(enumsOf(namespace))))
1285
+ enums: new Set(namespaces.flatMap(([, namespace]) => Object.keys(enumsOf(namespace)))),
1286
+ valueObjects: new Set(valueObjectsWithCoordinates(contract.contract.storage).map(({ coordinate }) => coordinate.entityName))
1123
1287
  };
1124
1288
  }
1125
1289
  function resolveModelRename(state, statement, from, to) {
@@ -1226,6 +1390,33 @@ function resolveEnumValueRename(state, statement, from, to) {
1226
1390
  to: to.coordinate
1227
1391
  });
1228
1392
  }
1393
+ function resolveValueObjectFieldRename(state, statement, from, to) {
1394
+ const oldValueObject = enumText(state.origin, from.coordinate.namespaceId, from.coordinate.valueObject);
1395
+ const newValueObject = enumText(state.destination, to.coordinate.namespaceId, to.coordinate.valueObject);
1396
+ const toNamespaceInOrigin = state.originOfRenamedNamespace.get(to.coordinate.namespaceId) ?? to.coordinate.namespaceId;
1397
+ if (from.coordinate.namespaceId !== toNamespaceInOrigin || from.coordinate.valueObject !== to.coordinate.valueObject) return notOk(errorStatementInvalid(statement, `The old name is a field of value object "${oldValueObject}" and the new name a field of value object "${newValueObject}"; a field cannot move between value objects.`, `Rename a field within one value object: --${statement.verb} ${statement.from.join(".")}:${statement.from.slice(0, -1).join(".")}.<new name>.`));
1398
+ const oldField = from.coordinate.field;
1399
+ const newField = to.coordinate.field;
1400
+ const fromKey = `${VALUE_OBJECT_FIELD_RENAMES}:${qualifiedValueObjectField(from.coordinate)}`;
1401
+ const toKey = `${VALUE_OBJECT_FIELD_RENAMES}:${qualifiedValueObjectField(to.coordinate)}`;
1402
+ if (state.renamedFrom.has(fromKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames "${qualifiedValueObjectField(from.coordinate)}".`, REPEATED_NAME_FIX));
1403
+ if (state.renamedTo.has(toKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames a field to "${qualifiedValueObjectField(to.coordinate)}".`, REPEATED_NAME_FIX));
1404
+ if (oldField === newField) return notOk(errorStatementInvalid(statement, `The statement renames value object field "${qualifiedValueObjectField(from.coordinate)}" to itself.`, `Leave out --${statement.verb} ${statement.text}.`));
1405
+ const newInOrigin = from.fields.includes(newField);
1406
+ const oldInDestination = to.fields.includes(oldField);
1407
+ if (newInOrigin && oldInDestination) return notOk(swapRefusal(statement, "valueObjectField", `${newValueObject}.${oldField}`, `${newValueObject}.${newField}`));
1408
+ if (newInOrigin) return notOk(errorStatementUnresolved(statement, `The field "${newField}" already exists in the origin value object "${oldValueObject}", so it cannot be the new name of a field.`, CHECK_NAMES_FIX));
1409
+ if (oldInDestination) return notOk(errorStatementUnresolved(statement, `The field "${oldField}" still exists in the destination value object "${newValueObject}", so it was not renamed.`, CHECK_NAMES_FIX));
1410
+ state.renamedFrom.add(fromKey);
1411
+ state.renamedTo.add(toKey);
1412
+ state.originOfRenamedValueObjectField.set(qualifiedValueObjectField(to.coordinate), from.coordinate);
1413
+ return ok({
1414
+ kind: "rename",
1415
+ entity: "valueObjectField",
1416
+ from: from.coordinate,
1417
+ to: to.coordinate
1418
+ });
1419
+ }
1229
1420
  /**
1230
1421
  * Two names that trade places: each is an old name and a new name, which one plan cannot do.
1231
1422
  * Statements resolve against contracts, so the swap takes three plans through a temporary name.
@@ -1334,14 +1525,17 @@ function resolveStatement(state, statement, later) {
1334
1525
  const from = readSide(state, "old", statement.from);
1335
1526
  if (!from.ok) return notOk(oldSideRefusal(state, statement, later, from.failure));
1336
1527
  const to = readSide(state, "new", statement.to);
1337
- if (!to.ok && from.value.entity === "enumValue" && statement.to.length === 1) {
1338
- const enumPart = statement.from.slice(0, -1).join(".");
1339
- return notOk(errorStatementUnresolved(statement, sentence(to.failure.reason), `Write the new name with its enum: --${statement.verb} ${statement.from.join(".")}:${enumPart}.${statement.to[0]}.`));
1528
+ if (!to.ok && (from.value.entity === "enumValue" || from.value.entity === "valueObjectField") && statement.to.length === 1) {
1529
+ const container = statement.from.slice(0, -1).join(".");
1530
+ const word = from.value.entity === "enumValue" ? "enum" : "value object";
1531
+ return notOk(errorStatementUnresolved(statement, sentence(to.failure.reason), `Write the new name with its ${word}: --${statement.verb} ${statement.from.join(".")}:${container}.${statement.to[0]}.`));
1340
1532
  }
1341
1533
  if (!to.ok) return notOk(unresolved(statement, to.failure));
1342
1534
  if (from.value.entity === "model" && to.value.entity === "model") return resolveModelRename(state, statement, from.value.coordinate, to.value.coordinate);
1343
1535
  if (from.value.entity === "field" && to.value.entity === "field") return resolveFieldRename(state, statement, from.value, to.value);
1344
1536
  if (from.value.entity === "enumValue" && to.value.entity === "enumValue") return resolveEnumValueRename(state, statement, from.value, to.value);
1537
+ if (from.value.entity === "valueObjectField" && to.value.entity === "valueObjectField") return resolveValueObjectFieldRename(state, statement, from.value, to.value);
1538
+ if (from.value.entity === "valueObjectField" || to.value.entity === "valueObjectField") return notOk(errorStatementInvalid(statement, "The statement names a value object field on one side and something else on the other.", "Rename a value object field to another field of the same value object, as ValueObject.field:ValueObject.<new name>."));
1345
1539
  if (from.value.entity === "enumValue" || to.value.entity === "enumValue") return notOk(errorStatementInvalid(statement, "The statement names an enum value on one side and a model or field on the other.", "Rename an enum value to another value of the same enum, as Enum.value:Enum.<new name>."));
1346
1540
  return notOk(errorStatementInvalid(statement, "The statement names a model on one side and a field on the other.", mixedSidesFix(statement.verb, statement.from, statement.to)));
1347
1541
  }
@@ -1364,14 +1558,117 @@ function sameType(origin, destination) {
1364
1558
  return isDeepStrictEqual(shape(origin), shape(destination));
1365
1559
  }
1366
1560
  /**
1561
+ * A convert of a variant: the model must be a variant in both contracts, followed through a rename,
1562
+ * and its discriminator value must have changed.
1563
+ */
1564
+ function resolveVariantConvert(state, statement, variant) {
1565
+ const flag = statementFlag(statement);
1566
+ const refuse = (reason) => notOk(unresolved(statement, {
1567
+ reason,
1568
+ fix: `Leave out ${flag}.`
1569
+ }));
1570
+ const shown = modelStatementText(state.destination.contract, variant.coordinate);
1571
+ const key = `convert:${qualifiedModel(variant.coordinate)}`;
1572
+ if (state.fieldStatements.has(key)) return notOk(errorStatementInvalid(statement, `An earlier statement already converts "${shown}".`, "Give each variant at most one --convert statement."));
1573
+ const counterpart = originCounterpart(state, variant.coordinate);
1574
+ const from = counterpart === void 0 ? void 0 : variantValue(state.origin.contract, counterpart.coordinate);
1575
+ const to = variantValue(state.destination.contract, variant.coordinate);
1576
+ if (from === void 0 || to === void 0) return refuse(`the model "${shown}" is not a variant in both contracts; a --convert statement names a field, or a variant whose discriminator value changed`);
1577
+ if (from === to) return refuse(`the variant "${shown}" has the discriminator value "${to}" in the origin and destination contracts, so it has no values to convert`);
1578
+ state.fieldStatements.add(key);
1579
+ return ok({
1580
+ kind: "convert",
1581
+ entity: "model",
1582
+ model: variant.coordinate
1583
+ });
1584
+ }
1585
+ /** A convert with one name, which names a variant as the destination contract names it. */
1586
+ function resolveOneNameConvert(state, statement, name) {
1587
+ const lookup = lookupModel(state.destination, void 0, name);
1588
+ if (lookup.kind === "found") return resolveVariantConvert(state, statement, lookup);
1589
+ return notOk(unresolved(statement, {
1590
+ reason: lookup.reason,
1591
+ fix: lookup.kind === "missing" ? "A --convert statement with one name names a variant as the destination contract names it, Variant or namespace.Variant. Names match exactly, including case." : lookup.fix
1592
+ }));
1593
+ }
1594
+ /**
1595
+ * The variant a two-name convert reads as, `namespace.Variant`, when the destination has that
1596
+ * model: `undefined` leaves the statement to the field reading, and a refusal names both readings
1597
+ * when the field reading resolves too.
1598
+ */
1599
+ function readNamespaceVariant(state, statement, first, second) {
1600
+ const asVariant = lookupModel(state.destination, first, second);
1601
+ if (asVariant.kind !== "found") return void 0;
1602
+ const asFieldModel = lookupModel(state.destination, void 0, first);
1603
+ if (asFieldModel.kind !== "found" || !hasField(asFieldModel.model, second)) return ok(asVariant);
1604
+ const field = qualifiedField({
1605
+ ...asFieldModel.coordinate,
1606
+ field: second
1607
+ });
1608
+ return notOk(unresolved(statement, {
1609
+ reason: `"${statement.text}" reads both as variant "${qualifiedModel(asVariant.coordinate)}" and as field "${field}"`,
1610
+ fix: `Write the field as namespace.Model.field if you mean the field: --convert ${field}.`
1611
+ }));
1612
+ }
1613
+ /**
1614
+ * A backfill of a value object's field: the field must be required in the destination value object,
1615
+ * and absent or optional in the origin one, under its origin name when a rename gave it a new one.
1616
+ */
1617
+ function resolveValueObjectFieldBackfill(state, statement, namespaceId, name, field) {
1618
+ const leaveOut = `Leave out ${statementFlag(statement)}.`;
1619
+ const refuse = (reason, fix = leaveOut) => notOk(unresolved(statement, {
1620
+ reason,
1621
+ fix
1622
+ }));
1623
+ const destination = lookupValueObject(state.destination, namespaceId, name);
1624
+ if (destination.kind !== "found") return refuse(destination.reason, destination.fix);
1625
+ const coordinate = {
1626
+ namespaceId: asNamespaceId(destination.namespaceId),
1627
+ valueObject: name,
1628
+ field
1629
+ };
1630
+ const shown = valueObjectFieldStatementText(state.destination.contract, coordinate);
1631
+ const destinationFields = destination.valueObject.fields;
1632
+ const destinationField = Object.hasOwn(destinationFields, field) ? destinationFields[field] : void 0;
1633
+ if (destinationField === void 0) return refuse(`the destination value object "${enumText(state.destination, destination.namespaceId, name)}" has no field "${field}" (fields: ${listed(Object.keys(destinationFields))})`, "A --backfill statement names the field as the destination contract names it. Names match exactly, including case.");
1634
+ const key = `backfill:${qualifiedValueObjectField(coordinate)}`;
1635
+ if (state.fieldStatements.has(key)) return notOk(errorStatementInvalid(statement, `An earlier statement already backfills "${shown}".`, "Give each field at most one --backfill statement."));
1636
+ if (destinationField.nullable) return refuse(`the field "${shown}" is optional in the destination contract, so no existing value needs it`, `${leaveOut} A --backfill statement fills a required field.`);
1637
+ const originNamespace = state.originOfRenamedNamespace.get(destination.namespaceId) ?? destination.namespaceId;
1638
+ const origin = valueObjectAt(state.origin.contract.storage, {
1639
+ plane: "storage",
1640
+ namespaceId: originNamespace,
1641
+ entityKind: "valueObject",
1642
+ entityName: name
1643
+ });
1644
+ if (origin === void 0) return refuse(`the origin contract has no value object "${enumText(state.origin, originNamespace, name)}", so no existing value lacks the field`);
1645
+ const originName = state.originOfRenamedValueObjectField.get(qualifiedValueObjectField(coordinate))?.field ?? field;
1646
+ const originField = Object.hasOwn(origin.fields, originName) ? origin.fields[originName] : void 0;
1647
+ if (originField !== void 0 && !originField.nullable) return refuse(`the field "${shown}" is already required in the origin contract, so every existing value has it`);
1648
+ state.fieldStatements.add(key);
1649
+ return ok({
1650
+ kind: "backfill",
1651
+ entity: "valueObjectField",
1652
+ field: coordinate
1653
+ });
1654
+ }
1655
+ /**
1367
1656
  * A convert or backfill statement names a field as the destination contract names it. A convert
1368
1657
  * needs the field in the origin contract, under its origin name when a rename gave it a new one,
1369
- * with another type. A backfill needs the field required in the destination contract and, on a
1370
- * model the origin has, either new or optional there.
1658
+ * with another type; a convert with one name, or a two-name convert that reads as
1659
+ * `namespace.Variant`, names a variant instead. A backfill needs the field required in the
1660
+ * destination contract and, on a model the origin has, either new or optional there; a backfill
1661
+ * whose first name is a value object names a field of the value object.
1371
1662
  */
1372
1663
  function resolveFieldStatement(state, statement) {
1373
1664
  const { verb } = statement;
1374
- const [namespaceId, modelName, field] = statement.field.length === 3 ? statement.field : [void 0, ...statement.field];
1665
+ const names = statement.field;
1666
+ if (names.length === 1) return resolveOneNameConvert(state, statement, names[0]);
1667
+ if (verb === "convert" && names.length === 2) {
1668
+ const variant = readNamespaceVariant(state, statement, names[0], names[1]);
1669
+ if (variant !== void 0) return variant.ok ? resolveVariantConvert(state, statement, variant.value) : variant;
1670
+ }
1671
+ const [namespaceId, modelName, field] = names.length === 3 ? names : [void 0, ...names];
1375
1672
  const flag = statementFlag(statement);
1376
1673
  const leaveOut = `Leave out ${flag}.`;
1377
1674
  const refuse = (reason, fix = leaveOut) => notOk(unresolved(statement, {
@@ -1380,7 +1677,8 @@ function resolveFieldStatement(state, statement) {
1380
1677
  }));
1381
1678
  const destination = lookupModel(state.destination, namespaceId, modelName);
1382
1679
  if (destination.kind !== "found") {
1383
- if (destination.valueObject !== void 0) return refuse(`"${destination.valueObject}" is a value object; a --${verb} statement names a field of a model`);
1680
+ if (destination.valueObject !== void 0 && verb === "backfill") return resolveValueObjectFieldBackfill(state, statement, namespaceId, modelName, field);
1681
+ if (destination.valueObject !== void 0) return refuse(`"${destination.valueObject}" is a value object; a --${verb} statement names a field of a model or a variant`);
1384
1682
  return refuse(destination.reason, destination.kind === "missing" ? `A --${verb} statement names a field as the destination contract names it, Model.field or namespace.Model.field. Names match exactly, including case.` : destination.fix);
1385
1683
  }
1386
1684
  const coordinate = {
@@ -1439,6 +1737,32 @@ function renamedAndDeleted(statements) {
1439
1737
  });
1440
1738
  return deleteOfRenamed(statements.filter(({ verb }) => verb === "delete"), renames);
1441
1739
  }
1740
+ function namesFieldOnly(destination, names) {
1741
+ const namespaces = destination.domain.namespaces;
1742
+ const modelAtName = (namespaceId, model) => {
1743
+ const namespace = Object.hasOwn(namespaces, namespaceId) ? namespaces[namespaceId] : void 0;
1744
+ return namespace === void 0 ? void 0 : modelIn(namespace, model);
1745
+ };
1746
+ const modelHasField = (namespaceId, model, field) => {
1747
+ const found = modelAtName(namespaceId, model);
1748
+ return found !== void 0 && hasField(found, field);
1749
+ };
1750
+ if (names.length === 3) return modelHasField(...names);
1751
+ if (names.length === 1) return false;
1752
+ const [model, field] = names;
1753
+ return Object.keys(namespaces).some((namespaceId) => modelHasField(namespaceId, model, field)) && modelAtName(model, field) === void 0;
1754
+ }
1755
+ /** The convert statements the destination contract reads only as a field, which need no origin contract to be told apart from a variant convert. */
1756
+ function fieldConvertsInDestination(statements, destination) {
1757
+ return statements.filter((entry) => {
1758
+ if (entry.verb !== "convert") return false;
1759
+ const parsed = parseFieldStatement({
1760
+ ...entry,
1761
+ verb: entry.verb
1762
+ });
1763
+ return parsed.ok && namesFieldOnly(destination, parsed.value.field);
1764
+ });
1765
+ }
1442
1766
  /**
1443
1767
  * Resolves the statements a user gave against the origin and destination contracts. Renames
1444
1768
  * resolve first, in the order given, so a convert or backfill statement can name a renamed field
@@ -1495,6 +1819,7 @@ function resolveStatements(input) {
1495
1819
  },
1496
1820
  originOfRenamedModel: /* @__PURE__ */ new Map(),
1497
1821
  originOfRenamedField: /* @__PURE__ */ new Map(),
1822
+ originOfRenamedValueObjectField: /* @__PURE__ */ new Map(),
1498
1823
  originOfRenamedNamespace: /* @__PURE__ */ new Map(),
1499
1824
  renamedFrom: /* @__PURE__ */ new Set(),
1500
1825
  renamedTo: /* @__PURE__ */ new Set(),
@@ -1573,6 +1898,26 @@ function renamedEnumValue(value, contracts) {
1573
1898
  return contracts.destination?.domain.namespaces[statement.to]?.enum?.[value.enum] === void 0 ? void 0 : renamed;
1574
1899
  }
1575
1900
  }
1901
+ /** The fields of a value object in a contract's storage; `undefined` when the contract has no such value object. */
1902
+ function valueObjectFields(contract, field) {
1903
+ const valueObject = valueObjectAt(contract.storage, {
1904
+ plane: "storage",
1905
+ namespaceId: field.namespaceId,
1906
+ entityKind: "valueObject",
1907
+ entityName: field.valueObject
1908
+ });
1909
+ return valueObject === void 0 ? void 0 : Object.keys(valueObject.fields);
1910
+ }
1911
+ /** A value object field under the namespace a namespace rename of `contracts` gives its value object, when the destination has the value object there. */
1912
+ function renamedValueObjectField(field, contracts) {
1913
+ for (const statement of resolvedRenames(contracts)) if (statement.kind === "rename" && statement.entity === "namespace" && statement.from === field.namespaceId) {
1914
+ const renamed = {
1915
+ ...field,
1916
+ namespaceId: statement.to
1917
+ };
1918
+ return contracts.destination === void 0 || valueObjectFields(contracts.destination, renamed) === void 0 ? void 0 : renamed;
1919
+ }
1920
+ }
1576
1921
  /**
1577
1922
  * The subject as a statement names it: `Model` or `Model.field`, with the namespace when its
1578
1923
  * contract has several, or the storage name when no model stores what the operation is about. A
@@ -1593,6 +1938,10 @@ function subjectText(subject, contracts) {
1593
1938
  const renamed = renamedEnumValue(subject, contracts);
1594
1939
  return renamed === void 0 || contracts.destination === void 0 ? enumValueStatementText(contracts.origin, subject) : enumValueStatementText(contracts.destination, renamed);
1595
1940
  }
1941
+ case "valueObjectField": {
1942
+ const renamed = renamedValueObjectField(subject, contracts);
1943
+ return renamed === void 0 || contracts.destination === void 0 ? valueObjectFieldStatementText(contracts.origin, subject) : valueObjectFieldStatementText(contracts.destination, renamed);
1944
+ }
1596
1945
  case "storage": return subject.name;
1597
1946
  }
1598
1947
  }
@@ -1610,6 +1959,7 @@ function lossText(subject, text, originKnown, loss) {
1610
1959
  case "model": return `would lose the data of model "${text}"`;
1611
1960
  case "field": return loss === "typeChange" ? `would change the type of field "${text}" and can change or lose its values` : `would lose the values of field "${text}"`;
1612
1961
  case "enumValue": return `would lose enum value "${text}" from the data that holds it`;
1962
+ case "valueObjectField": return `would lose the values of value object field "${text}"`;
1613
1963
  case "storage": return originKnown ? `would lose the data in "${text}", which no model of the origin contract stores` : `would lose the data in "${text}", named by its storage name because the origin contract is unknown; --delete loses that data`;
1614
1964
  }
1615
1965
  }
@@ -1622,6 +1972,7 @@ function lossText(subject, text, originKnown, loss) {
1622
1972
  const ORIGIN_SNAPSHOT_RECOVERY = ["If it was renamed, keep its data instead: store the snapshot of the contract the database is at, then run this command again and answer with --rename.", ...STORE_ORIGIN_SNAPSHOT_STEPS.map((step) => step.replaceAll("{bin}", "prisma"))].join("\n");
1623
1973
  function sameCoordinate(statement, subject) {
1624
1974
  if (statement.kind !== "rename" || statement.entity === "namespace" || subject.kind === "storage") return false;
1975
+ if (statement.entity === "valueObjectField" || subject.kind === "valueObjectField") return statement.entity === "valueObjectField" && subject.kind === "valueObjectField" && statement.from.namespaceId === subject.namespaceId && statement.from.valueObject === subject.valueObject && statement.from.field === subject.field;
1625
1976
  if (statement.entity === "enumValue" || subject.kind === "enumValue") return statement.entity === "enumValue" && subject.kind === "enumValue" && statement.from.namespaceId === subject.namespaceId && statement.from.enum === subject.enum && statement.from.member === subject.member;
1626
1977
  const { from } = statement;
1627
1978
  if (from.namespaceId !== subject.namespaceId || from.model !== subject.model) return false;
@@ -1646,10 +1997,49 @@ function onlyNewMember(subject, contracts) {
1646
1997
  const added = (contracts.destination.domain.namespaces[value.namespaceId]?.enum?.[value.enum]?.members ?? []).filter(({ name }) => !renamedTo.has(name) && !originMembers.some((member) => member.name === name));
1647
1998
  return added.length === 1 ? added[0]?.name : void 0;
1648
1999
  }
1649
- function renameForm(subject, text, contracts) {
1650
- if (subject.kind === "field" || subject.kind === "enumValue") return `${text}:${text.slice(0, text.lastIndexOf("."))}.${(subject.kind === "enumValue" ? onlyNewMember(subject, contracts) : void 0) ?? "<new name>"}`;
1651
- return `${text}:<new name>`;
2000
+ /**
2001
+ * The field a value object field can only have been renamed to: the one field of the destination
2002
+ * value object that the origin one does not have and no rename of the plan names.
2003
+ */
2004
+ function newValueObjectFields(subject, contracts) {
2005
+ const field = renamedValueObjectField(subject, contracts) ?? subject;
2006
+ const originFields = valueObjectFields(contracts.origin, subject) ?? [];
2007
+ const renamedTo = new Set(resolvedRenames(contracts).flatMap((statement) => statement.kind === "rename" && statement.entity === "valueObjectField" ? [statement.to.field] : []));
2008
+ return (valueObjectFields(contracts.destination, field) ?? []).filter((name) => !renamedTo.has(name) && !originFields.includes(name));
2009
+ }
2010
+ function onlyNewValueObjectField(subject, contracts) {
2011
+ const added = newValueObjectFields(subject, contracts);
2012
+ return added.length === 1 ? added[0] : void 0;
2013
+ }
2014
+ /** The value object fields the plan's backfill statements name, resolved; empty when they do not resolve. */
2015
+ function backfilledValueObjectFields(contracts) {
2016
+ if (!contracts.statements.some((statement) => statement.verb === "backfill")) return [];
2017
+ const resolved = resolveStatements({
2018
+ statements: contracts.statements,
2019
+ origin: {
2020
+ kind: "contract",
2021
+ contract: contracts.origin
2022
+ },
2023
+ destination: contracts.destination
2024
+ });
2025
+ if (!resolved.ok) return [];
2026
+ return resolved.value.flatMap((statement) => statement.kind === "backfill" && statement.entity === "valueObjectField" ? [statement.field] : []);
1652
2027
  }
2028
+ function renameForm(subject, text, contracts) {
2029
+ if (subject.kind === "storage") return `${text}:<new name>`;
2030
+ if (subject.kind === "model") {
2031
+ const renamedTo = resolvedRenames(contracts).flatMap((statement) => statement.kind === "rename" && statement.entity === "model" ? [statement.to] : []);
2032
+ const added = newVariantsOfBase(contracts.origin, contracts.destination, subject, renamedTo);
2033
+ const [only] = added;
2034
+ return `${text}:${only !== void 0 && added.length === 1 ? modelStatementText(contracts.destination, only) : "<new name>"}`;
2035
+ }
2036
+ return `${text}:${text.slice(0, text.lastIndexOf("."))}.${(subject.kind === "enumValue" ? onlyNewMember(subject, contracts) : subject.kind === "valueObjectField" ? onlyNewValueObjectField(subject, contracts) : void 0) ?? "<new name>"}`;
2037
+ }
2038
+ const SUBJECTS_OF_SEVERAL_OPERATIONS = /* @__PURE__ */ new Set([
2039
+ "model",
2040
+ "enumValue",
2041
+ "valueObjectField"
2042
+ ]);
1653
2043
  /** The labels of the operations a question is about, as one phrase. */
1654
2044
  function labelsText(labels) {
1655
2045
  const [first, ...rest] = [...new Set(labels)];
@@ -1669,6 +2059,10 @@ function inDestination(subject, contracts) {
1669
2059
  const value = renamedEnumValue(subject, contracts) ?? subject;
1670
2060
  return (contracts.destination.domain.namespaces[value.namespaceId]?.enum?.[value.enum])?.members.some(({ name }) => name === subject.member) === true;
1671
2061
  }
2062
+ if (subject.kind === "valueObjectField") {
2063
+ const field = renamedValueObjectField(subject, contracts) ?? subject;
2064
+ return valueObjectFields(contracts.destination, field)?.includes(subject.field) === true;
2065
+ }
1672
2066
  const model = renamedModel(subject, contracts) ?? subject;
1673
2067
  const destinationModel = contracts.destination.domain.namespaces[model.namespaceId]?.models[model.model];
1674
2068
  if (destinationModel === void 0) return false;
@@ -1698,9 +2092,55 @@ function missingFieldModel(subject, contracts) {
1698
2092
  return contracts.destination.domain.namespaces[model.namespaceId]?.models[model.model] === void 0 ? model : void 0;
1699
2093
  }
1700
2094
  /**
2095
+ * The variant a model subject is in the destination, under the name a rename of the plan gives it,
2096
+ * when it is a variant in both contracts whose discriminator value changed: a convert rewrites its
2097
+ * stored value instead of deleting its rows.
2098
+ */
2099
+ function changedVariant(subject, contracts) {
2100
+ if (subject.kind !== "model") return void 0;
2101
+ const model = renamedModel(subject, contracts) ?? subject;
2102
+ return variantValueChanged(contracts.origin, subject, contracts.destination, model) ? model : void 0;
2103
+ }
2104
+ /**
2105
+ * What `--delete` of a value object field leaves in the required fields the value object gained:
2106
+ * `migration plan` needs a backfill statement for each the run does not backfill, and `db update`
2107
+ * fills a temporary value.
2108
+ */
2109
+ function newRequiredFieldNote(subject, text, contracts) {
2110
+ if (subject.kind !== "valueObjectField" || inDestination(subject, contracts)) return [];
2111
+ const field = renamedValueObjectField(subject, contracts) ?? subject;
2112
+ const valueObject = valueObjectAt(contracts.destination.storage, {
2113
+ plane: "storage",
2114
+ namespaceId: field.namespaceId,
2115
+ entityKind: "valueObject",
2116
+ entityName: field.valueObject
2117
+ });
2118
+ const backfilled = contracts.canConvert ? backfilledValueObjectFields(contracts) : [];
2119
+ const unfilled = newValueObjectFields(subject, contracts).filter((name) => valueObject?.fields[name]?.nullable === false && !backfilled.some((backfill) => backfill.namespaceId === field.namespaceId && backfill.valueObject === field.valueObject && backfill.field === name));
2120
+ if (unfilled.length === 0) return [];
2121
+ const parent = text.slice(0, text.lastIndexOf("."));
2122
+ const added = unfilled.map((name) => `${parent}.${name}`);
2123
+ const named = `${added.length === 1 ? "field" : "fields"} ${quotedList(added)}`;
2124
+ const deleted = statementFlag({
2125
+ verb: "delete",
2126
+ text
2127
+ });
2128
+ if (!contracts.canConvert) return [`With ${deleted}, the existing objects get a temporary value in the new required ${named}.`];
2129
+ const backfills = added.map((each) => statementFlag({
2130
+ verb: "backfill",
2131
+ text: each
2132
+ })).join(" ");
2133
+ return [added.length === 1 ? `With ${deleted}, the new required ${named} still needs a value: add ${backfills} to write it in migration.ts.` : `With ${deleted}, the new required ${named} still need a value: add ${backfills} to write them in migration.ts.`];
2134
+ }
2135
+ function quotedList(items) {
2136
+ const quoted = items.map((item) => `"${item}"`);
2137
+ return quoted.length === 1 ? quoted.join("") : `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`;
2138
+ }
2139
+ /**
1701
2140
  * The question for one operation that would lose data. A field whose type changes may be converted
1702
2141
  * where the command writes a migration to fill in; the convert names the field as the destination
1703
- * names it. A model or field the destination no longer has, and no rename of the plan renamed, may
2142
+ * names it. A variant whose discriminator value changed may be converted by any command, since
2143
+ * the convert needs no code the user writes. A model or field the destination no longer has, and no rename of the plan renamed, may
1704
2144
  * be renamed instead of deleted; a rename is resolved against the two contracts after the plan's
1705
2145
  * other renames, and its old name must be the subject. Anything else, and data no model stores,
1706
2146
  * can only be deleted. A field whose model the destination names differently can be renamed only
@@ -1712,13 +2152,20 @@ function dataLossQuestion(loss, contracts, edits = [], labels = [loss.label]) {
1712
2152
  const deleteNames = namesSubject("delete", subject);
1713
2153
  const missingModel = missingFieldModel(loss.subject, contracts);
1714
2154
  const keepData = edits.length === 0 || contracts.keepDataEditAdvice === void 0 ? void 0 : contracts.keepDataEditAdvice(subject, edits, (contracts.keptSubjects ?? []).filter((other) => other !== subject));
1715
- const question = [
1716
- `${labelsText(labels)} ${lossText(loss.subject, subject, contracts.originKnown, loss.loss)}.`,
2155
+ const lost = lossText(loss.subject, subject, contracts.originKnown, loss.loss);
2156
+ const operations = [...new Set(labels)];
2157
+ const advice = [
1717
2158
  ...missingModel === void 0 ? [] : [modelRenameAdvice(missingModel, contracts)],
1718
2159
  ...loss.keepDataAdvice === void 0 ? [] : [loss.keepDataAdvice],
1719
2160
  ...keepData?.lead === void 0 ? [] : [keepData.lead],
1720
- ...keepData?.ways ?? []
1721
- ].join(" ");
2161
+ ...keepData?.ways ?? [],
2162
+ ...newRequiredFieldNote(loss.subject, subject, contracts)
2163
+ ];
2164
+ const question = operations.length > 1 ? [
2165
+ `These operations ${lost}:`,
2166
+ ...operations.map((label) => `- ${label}`),
2167
+ ...advice.length === 0 ? [] : [advice.join(" ")]
2168
+ ].join("\n") : [`${labelsText(operations)} ${lost}.`, ...advice].join(" ");
1722
2169
  if (loss.loss === "typeChange" && loss.subject.kind === "field") {
1723
2170
  if (!contracts.canConvert) return {
1724
2171
  question,
@@ -1750,6 +2197,29 @@ function dataLossQuestion(loss, contracts, edits = [], labels = [loss.label]) {
1750
2197
  }
1751
2198
  };
1752
2199
  }
2200
+ const variant = changedVariant(loss.subject, contracts);
2201
+ if (variant !== void 0) {
2202
+ const convert = modelStatementText(contracts.destination, variant);
2203
+ return {
2204
+ question,
2205
+ ...ifDefined("keepDataWays", keepData?.ways),
2206
+ subject,
2207
+ verbs: ["convert", "delete"],
2208
+ forms: { convert },
2209
+ validate: (verb, text) => {
2210
+ if (verb !== "convert") return deleteNames(text);
2211
+ if (text !== convert) return `convert names the variant as the destination contract names it: ${statementFlag({
2212
+ verb: "convert",
2213
+ text: convert
2214
+ })}.`;
2215
+ const resolved = resolvesWith({
2216
+ verb: "convert",
2217
+ text
2218
+ }, contracts);
2219
+ return resolved.ok ? void 0 : resolved.failure;
2220
+ }
2221
+ };
2222
+ }
1753
2223
  const renamable = missingModel === void 0 && loss.subject.kind !== "storage" && !inDestination(loss.subject, contracts) && !renamedByPlan(loss.subject, contracts);
1754
2224
  return {
1755
2225
  question,
@@ -1940,7 +2410,7 @@ async function askPlanQuestions(input) {
1940
2410
  if (losses.length + accessChanges.length === 0 && round > 0) break;
1941
2411
  const questions = [...withNamespaceDeleteOnFirstQuestion(withRecoveryOnFirstStorageQuestion(losses.map((loss) => ({
1942
2412
  loss,
1943
- question: acceptingNamespaceAnswers(dataLossQuestion(loss, roundContracts, sameSubject(loss).flatMap((entry) => entry.keepDataEdit === void 0 ? [] : [entry.keepDataEdit]), loss.subject.kind === "enumValue" ? sameSubject(loss).map(({ label }) => label) : [loss.label]), removedNamespaceOf(loss.subject, plan.namespaces), contracts)
2413
+ question: acceptingNamespaceAnswers(dataLossQuestion(loss, roundContracts, sameSubject(loss).flatMap((entry) => entry.keepDataEdit === void 0 ? [] : [entry.keepDataEdit]), SUBJECTS_OF_SEVERAL_OPERATIONS.has(loss.subject.kind) ? sameSubject(loss).map(({ label }) => label) : [loss.label]), removedNamespaceOf(loss.subject, plan.namespaces), contracts)
1944
2414
  })), !input.originKnown), plan.namespaces?.added ?? []), ...accessChanges.map((change) => accessChangeQuestion(change, contracts))];
1945
2415
  const answers = await input.answer(questions);
1946
2416
  checkAnswers(questions, answers);
@@ -2119,12 +2589,23 @@ function reportConsentStatement(consented, operationIndexes) {
2119
2589
  description: consentDescription(consented.verb, consented.subject, consented.text, consented.loss)
2120
2590
  };
2121
2591
  }
2122
- /** The fields of `values` named as `destination` names them; a column no field stores is left out. */
2592
+ function statementText(subject, destination) {
2593
+ switch (subject.kind) {
2594
+ case "field": return fieldStatementText(destination, subject);
2595
+ case "valueObjectField": return valueObjectFieldStatementText(destination, subject);
2596
+ default: return;
2597
+ }
2598
+ }
2599
+ /** The fields of `values` named as `destination` names them, each field and value once however many columns it fills; a column no field stores is left out. */
2123
2600
  function reportTemporaryValues(values, destination) {
2124
- return values.flatMap(({ subject, value }) => subject.kind === "field" ? [{
2125
- field: fieldStatementText(destination, subject),
2126
- value
2127
- }] : []);
2601
+ const reports = values.flatMap(({ subject, value }) => {
2602
+ const field = statementText(subject, destination);
2603
+ return field === void 0 ? [] : [{
2604
+ field,
2605
+ value
2606
+ }];
2607
+ });
2608
+ return reports.filter((report, index) => reports.findIndex(({ field, value }) => field === report.field && value === report.value) === index);
2128
2609
  }
2129
2610
  /** The storage entities that differ between two contracts, as a result reports them. */
2130
2611
  function changedStorageEntities(fromContract, toContract) {
@@ -2538,7 +3019,7 @@ function failureReports(failure, resolutions) {
2538
3019
  statements: []
2539
3020
  });
2540
3021
  const { failedTypeChange, rowsWithoutValue, rowsHoldingValue, rowsFailingCheck } = failure.meta;
2541
- const operationIndex = failedTypeChange?.operationIndex ?? rowsWithoutValue?.[0]?.operationIndex ?? rowsHoldingValue?.operationIndex ?? rowsFailingCheck?.operationIndex;
3022
+ const operationIndex = failedTypeChange?.operationIndex ?? rowsWithoutValue?.[0]?.operationIndex ?? rowsHoldingValue?.[0]?.operationIndex ?? rowsFailingCheck?.operationIndex;
2542
3023
  const edge = operationIndex !== void 0 ? edgeOfOperation(resolution.entry.migrationEdges, operationIndex) : schemaCheckIssues(failure) !== void 0 ? resolution.entry.migrationEdges.at(-1) : void 0;
2543
3024
  return {
2544
3025
  ...ifDefined("failedTypeChange", failedTypeChange === void 0 ? void 0 : failedTypeChangeReport(failedTypeChange, fieldText(failedTypeChange.field))),
@@ -2547,7 +3028,7 @@ function failureReports(failure, resolutions) {
2547
3028
  reason,
2548
3029
  rows
2549
3030
  }))),
2550
- ...ifDefined("rowsHoldingValue", rowsHoldingValue === void 0 ? void 0 : rowsHoldingValueReport(rowsHoldingValue, resolution.entry.destinationContract)),
3031
+ ...ifDefined("rowsHoldingValue", rowsHoldingValue?.map((fact) => rowsHoldingValueReport(fact, resolution.entry.destinationContract))),
2551
3032
  ...ifDefined("rowsFailingCheck", rowsFailingCheckReport(rowsFailingCheck)),
2552
3033
  ...ifDefined("failedMigration", edge === void 0 ? void 0 : {
2553
3034
  spaceId: resolution.spaceId,
@@ -2759,7 +3240,13 @@ async function executeRun(options) {
2759
3240
  return resolved.value;
2760
3241
  };
2761
3242
  const consentTexts = statementTexts.filter((statement) => !isPlannedStatement(statement));
2762
- const firstResolved = resolveRenames(statementTexts);
3243
+ const fieldConverts = appOrigin?.origin.kind === "missing" ? fieldConvertsInDestination(statementTexts, contract) : [];
3244
+ const firstResolved = fieldConverts.length > 0 ? [] : resolveRenames(statementTexts);
3245
+ const needsMigrationFile = fieldConverts.length > 0 ? fieldConverts : statementsNeedingMigrationFile(statementTexts, firstResolved);
3246
+ if (needsMigrationFile.length > 0) {
3247
+ const markerHash = markerRows.get(aggregate.app.spaceId)?.storageHash;
3248
+ throw errorStatementNeedsMigrationFile(statementTexts, needsMigrationFile, options.invocation, aggregate.app.packages.some(({ metadata }) => metadata.to === markerHash) ? markerHash : void 0);
3249
+ }
2763
3250
  if (mode === "apply") {
2764
3251
  const orphanMarkerError = detectOrphanMarkers(aggregate, markerRows, familyInstance.markerLocation);
2765
3252
  if (orphanMarkerError !== null) throw orphanMarkerError;
@@ -2959,7 +3446,7 @@ async function executeRun(options) {
2959
3446
  ...ifDefined("onProgress", onProgress)
2960
3447
  });
2961
3448
  if (!applied.ok) {
2962
- const facts = runnerFailureFacts(applied.failure, orderedResolutions);
3449
+ const facts = await withEditsAsWritten(runnerFailureFacts(applied.failure, orderedResolutions));
2963
3450
  return notOk(action === "dbInit" ? dbInitRunnerFailureError(applied.failure, facts, options.invocation) : dbUpdateRunnerFailureError(applied.failure, facts, {
2964
3451
  databaseStorageHash,
2965
3452
  invocation: options.invocation
@@ -3182,6 +3669,17 @@ function recordedDatabaseContract(aggregate, markerRows) {
3182
3669
  return hash !== void 0 && aggregate.app.graph().nodes.has(hash) ? hash : void 0;
3183
3670
  }
3184
3671
  /**
3672
+ * The convert and backfill statements of `texts` that ask for code the user writes in a migration
3673
+ * file: every one but a variant convert, which rewrites a stored value the contracts already give.
3674
+ * `resolved` are the planned statements of `texts`, resolved in the order given.
3675
+ */
3676
+ function statementsNeedingMigrationFile(texts, resolved) {
3677
+ return texts.filter(isPlannedStatement).filter((_, index) => {
3678
+ const statement = resolved[index];
3679
+ return statement !== void 0 && statement.kind !== "rename" && !(statement.kind === "convert" && statement.entity === "model");
3680
+ });
3681
+ }
3682
+ /**
3185
3683
  * Execute `db init` against the configured contract.
3186
3684
  *
3187
3685
  * Routes through the loader → planner → runner pipeline (sub-spec
@@ -3539,8 +4037,6 @@ async function signContractSpaces(options) {
3539
4037
  }
3540
4038
  /** Execute `db update` against the configured contract. */
3541
4039
  async function executeDbUpdate(options) {
3542
- const statements = options.statements ?? [];
3543
- if (statements.some(({ verb }) => verb === "convert" || verb === "backfill")) throw errorStatementNeedsMigrationFile(statements, void 0);
3544
4040
  return await executeRun({
3545
4041
  driver: options.driver,
3546
4042
  adapter: options.adapter,
@@ -3814,6 +4310,14 @@ async function loadContractSource(config, options = {}) {
3814
4310
  warnings
3815
4311
  });
3816
4312
  }
4313
+ /**
4314
+ * What `db migrate` says it applied. The runner skips an operation whose postcheck already holds
4315
+ * before it runs, so when it ran fewer operations than the migrations hold, the summary says why.
4316
+ */
4317
+ function appliedSummary(counts) {
4318
+ const { migrations, planned, executed, spaces } = counts;
4319
+ return `Applied ${migrations} migration(s) (${executed < planned ? `${executed} of ${planned} operation(s); the other ${planned - executed} had nothing to do, since their postchecks already held` : `${executed} operation(s)`}) across ${spaces} contract space(s)`;
4320
+ }
3817
4321
  /** The ledger as `read` gives it, or undefined when the read fails: the error it explains must not fail with it. */
3818
4322
  async function readLedgerQuietly(read) {
3819
4323
  try {
@@ -3938,6 +4442,142 @@ function migrateRunnerFailureError(failure, facts, failedMigration, invocation)
3938
4442
  return runnerFailureError(failure, migrateAdvice(failure, facts, failedMigration, invocation));
3939
4443
  }
3940
4444
  /**
4445
+ * The directory of the first migration to apply whose `migration.ts` still calls `placeholder(...)`.
4446
+ * `migration plan` writes such a migration with an empty `ops.json`, and `node migration.ts` writes
4447
+ * none until every placeholder is filled, so only a migration with no operations is read. A call of
4448
+ * `placeholder` from another file the migration imports is not found.
4449
+ */
4450
+ async function migrationWithUnfilledPlaceholders(plans, applyOrder, migrationsDir) {
4451
+ for (const spaceId of applyOrder) for (const edge of plans.get(spaceId)?.migrationEdges ?? []) {
4452
+ if (edge.operationCount !== 0) continue;
4453
+ const directory = join(migrationsDir, spaceId, edge.dirName);
4454
+ if (callsPlaceholder(await migrationSource(directory))) return directory;
4455
+ }
4456
+ }
4457
+ async function migrationSource(directory) {
4458
+ try {
4459
+ return await readFile(join(directory, "migration.ts"), "utf-8");
4460
+ } catch (error) {
4461
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return "";
4462
+ throw error;
4463
+ }
4464
+ }
4465
+ const PRISMA_MIGRATION_MODULE = /^@(prisma|internal)\/.+\/migration$/;
4466
+ const NAME_START = /[A-Za-z_$]/;
4467
+ const NAME_PART = /[\w$]/;
4468
+ /**
4469
+ * Whether the source calls the `placeholder` it imports from a Prisma migration module, by the
4470
+ * local name it imports it under or through a namespace import. Comments and the text of strings
4471
+ * are not code, so a `placeholder(` there is not a call.
4472
+ */
4473
+ function callsPlaceholder(source) {
4474
+ const tokens = tokenize(source);
4475
+ const { names, namespaces } = placeholderImports(tokens);
4476
+ return tokens.some((token, index) => {
4477
+ if (tokens[index + 1]?.text !== "(" || token.kind !== "name") return false;
4478
+ if (tokens[index - 1]?.text !== ".") return names.has(token.text);
4479
+ const owner = tokens[index - 2];
4480
+ return token.text === "placeholder" && owner?.kind === "name" && namespaces.has(owner.text);
4481
+ });
4482
+ }
4483
+ function placeholderImports(tokens) {
4484
+ const names = /* @__PURE__ */ new Set();
4485
+ const namespaces = /* @__PURE__ */ new Set();
4486
+ tokens.forEach((token, index) => {
4487
+ if (token.kind !== "name" || token.text !== "import") return;
4488
+ const fromAt = tokens.findIndex((each, at) => at > index && each.kind === "name" && each.text === "from");
4489
+ const module = tokens[fromAt + 1];
4490
+ if (fromAt < 0 || module?.kind !== "string" || !PRISMA_MIGRATION_MODULE.test(module.text)) return;
4491
+ const clause = tokens.slice(index + 1, fromAt);
4492
+ if (clause[0]?.text === "*" && clause[1]?.text === "as" && clause[2] !== void 0) {
4493
+ namespaces.add(clause[2].text);
4494
+ return;
4495
+ }
4496
+ clause.forEach((each, at) => {
4497
+ if (each.text !== "placeholder") return;
4498
+ const alias = clause[at + 1]?.text === "as" ? clause[at + 2] : void 0;
4499
+ names.add(alias?.text ?? each.text);
4500
+ });
4501
+ });
4502
+ return {
4503
+ names,
4504
+ namespaces
4505
+ };
4506
+ }
4507
+ /** The names, strings and punctuation of the source, with comments left out and template expressions read as code. */
4508
+ function tokenize(source) {
4509
+ const tokens = [];
4510
+ let at = 0;
4511
+ const templateDepths = [];
4512
+ let depth = 0;
4513
+ const readTemplate = () => {
4514
+ while (at < source.length) {
4515
+ const char = source[at];
4516
+ if (char === "\\") at += 2;
4517
+ else if (char === "`") {
4518
+ at += 1;
4519
+ return;
4520
+ } else if (char === "$" && source[at + 1] === "{") {
4521
+ at += 2;
4522
+ templateDepths.push(depth);
4523
+ depth += 1;
4524
+ return;
4525
+ } else at += 1;
4526
+ }
4527
+ };
4528
+ while (at < source.length) {
4529
+ const char = source[at] ?? "";
4530
+ const next = source[at + 1];
4531
+ if (char === "/" && next === "/") {
4532
+ const end = source.indexOf("\n", at);
4533
+ at = end < 0 ? source.length : end;
4534
+ } else if (char === "/" && next === "*") {
4535
+ const end = source.indexOf("*/", at + 2);
4536
+ at = end < 0 ? source.length : end + 2;
4537
+ } else if (char === "'" || char === "\"") {
4538
+ let text = "";
4539
+ at += 1;
4540
+ while (at < source.length && source[at] !== char) {
4541
+ if (source[at] === "\\") at += 1;
4542
+ text += source[at] ?? "";
4543
+ at += 1;
4544
+ }
4545
+ at += 1;
4546
+ tokens.push({
4547
+ kind: "string",
4548
+ text
4549
+ });
4550
+ } else if (char === "`") {
4551
+ at += 1;
4552
+ readTemplate();
4553
+ } else if (NAME_START.test(char)) {
4554
+ const start = at;
4555
+ while (at < source.length && NAME_PART.test(source[at] ?? "")) at += 1;
4556
+ tokens.push({
4557
+ kind: "name",
4558
+ text: source.slice(start, at)
4559
+ });
4560
+ } else if (/\s/.test(char)) at += 1;
4561
+ else {
4562
+ at += 1;
4563
+ if (char === "{") depth += 1;
4564
+ if (char === "}") {
4565
+ depth -= 1;
4566
+ if (templateDepths.at(-1) === depth) {
4567
+ templateDepths.pop();
4568
+ readTemplate();
4569
+ continue;
4570
+ }
4571
+ }
4572
+ tokens.push({
4573
+ kind: "punctuation",
4574
+ text: char
4575
+ });
4576
+ }
4577
+ }
4578
+ return tokens;
4579
+ }
4580
+ /**
3941
4581
  * Apply pending migrations across every contract space (app +
3942
4582
  * extensions). Replay-only: graph-walk against the on-disk graph for
3943
4583
  * every contract space; no synth, no introspection.
@@ -4038,6 +4678,8 @@ async function executeMigrate(options) {
4038
4678
  summary: totalSpaces === 0 ? "Already up to date — no contract spaces are loaded" : totalSpaces === 1 ? "Already up to date" : `Already up to date across ${totalSpaces} space(s)`
4039
4679
  }));
4040
4680
  }
4681
+ const unfilled = await migrationWithUnfilledPlaceholders(perSpacePlans, applyOrder, migrationsDir);
4682
+ if (unfilled !== void 0) return notOk(errorMigrationHasUnfilledPlaceholders(unfilled, options.invocation));
4041
4683
  const applied = await runMigration({
4042
4684
  aggregate,
4043
4685
  perSpacePlans,
@@ -4056,7 +4698,7 @@ async function executeMigrate(options) {
4056
4698
  ...ifDefined("onProgress", onProgress)
4057
4699
  });
4058
4700
  if (!applied.ok) {
4059
- const facts = runnerFailureFacts(applied.failure, collectOrdered(applyOrder, perSpacePlans));
4701
+ const facts = await withEditsAsWritten(runnerFailureFacts(applied.failure, collectOrdered(applyOrder, perSpacePlans)));
4060
4702
  return notOk(migrateRunnerFailureError(applied.failure, facts, facts.failedMigration === void 0 ? void 0 : failedMigrationOnDisk(facts.failedMigration, migrationsDir), options.invocation));
4061
4703
  }
4062
4704
  const orderedAll = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId) || plansKeptFromRunner.has(spaceId)).map((spaceId) => {
@@ -4072,7 +4714,12 @@ async function executeMigrate(options) {
4072
4714
  };
4073
4715
  });
4074
4716
  const perSpaceAll = buildPerSpaceBreakdown(orderedAll, aggregate.app.spaceId, { includeMarkers: true });
4075
- const summary = `Applied ${applied.value.orderedResolutions.reduce((sum, r) => sum + r.entry.migrationEdges.length, 0)} migration(s) (${applied.value.totalOpsExecuted} operation(s)) across ${orderedAll.length} contract space(s)`;
4717
+ const summary = appliedSummary({
4718
+ migrations: applied.value.orderedResolutions.reduce((sum, r) => sum + r.entry.migrationEdges.length, 0),
4719
+ planned: applied.value.totalOpsPlanned,
4720
+ executed: applied.value.totalOpsExecuted,
4721
+ spaces: orderedAll.length
4722
+ });
4076
4723
  return ok(buildSuccess({
4077
4724
  aggregate,
4078
4725
  orderedResolutions: orderedAll,
@@ -6780,24 +7427,36 @@ async function runPlannerLeg(planner, migrations, frameworkComponents, contract,
6780
7427
  });
6781
7428
  if (plannerResult.kind === "failure") return notOk(refused(plannerResult.conflicts));
6782
7429
  let resolved = [];
7430
+ let standingFor = [];
6783
7431
  let hasPlaceholders = false;
6784
7432
  try {
6785
- resolved = await Promise.all(plannerResult.plan.operations);
6786
- if (resolved.length === 0 && origin.kind === "empty") return notOk(errorPlanProducedNoOperations(destination));
7433
+ const settled = await Promise.allSettled(plannerResult.plan.operations);
7434
+ for (const entry of settled) {
7435
+ if (entry.status === "fulfilled") continue;
7436
+ const reason = entry.reason;
7437
+ if (!CliStructuredError$1.is(reason)) throw reason;
7438
+ if (reason.code !== "MIGRATION.UNFILLED_PLACEHOLDER") throw reason;
7439
+ hasPlaceholders = true;
7440
+ }
7441
+ resolved = settled.map((entry) => entry.status === "fulfilled" ? entry.value : void 0);
7442
+ standingFor = settled.map((entry) => entry.status === "rejected" ? placeholderOperationOf(entry.reason) : void 0);
6787
7443
  } catch (e) {
6788
7444
  if (CliStructuredError$1.is(e) && e.code === "MIGRATION.UNFILLED_PLACEHOLDER") {
6789
7445
  hasPlaceholders = true;
6790
- try {
6791
- resolved = (await Promise.allSettled(plannerResult.plan.operations)).map((entry) => entry.status === "fulfilled" ? entry.value : void 0);
6792
- } catch {
6793
- resolved = [];
6794
- }
7446
+ resolved = [];
6795
7447
  } else throw e;
6796
7448
  }
7449
+ if (!hasPlaceholders && resolved.length === 0 && origin.kind === "empty") return notOk(errorPlanProducedNoOperations(destination));
6797
7450
  const plannedOps = resolved.filter((op) => op !== void 0);
6798
- const position = resolvedPositions(resolved);
7451
+ const listed = resolved.map((op, index) => op === void 0 ? standingFor[index] : {
7452
+ id: op.id,
7453
+ label: op.label,
7454
+ operationClass: op.operationClass
7455
+ });
7456
+ const position = resolvedPositions(listed);
6799
7457
  return ok({
6800
7458
  plannedOps,
7459
+ listedOps: listed.filter((op) => op !== void 0),
6801
7460
  migrationTsContent: plannerResult.plan.renderTypeScript(resolveImportSpecifier),
6802
7461
  hasPlaceholders,
6803
7462
  dataLoss: plannerResult.dataLoss.map(({ operationIndex, subject, loss, label, keepDataAdvice, keepDataEdit }) => ({
@@ -6832,16 +7491,22 @@ function resolvedPositions(resolved) {
6832
7491
  }
6833
7492
  return (planIndex) => positions[planIndex];
6834
7493
  }
6835
- /**
6836
- * The operations a result lists. For a leg with unfilled placeholders these are the operations
6837
- * that resolved; the placeholders themselves are not operations yet.
6838
- */
6839
- function operationSummaries(ops) {
6840
- return ops.map((op) => ({
6841
- id: op.id,
6842
- label: op.label,
6843
- operationClass: op.operationClass
6844
- }));
7494
+ const PlaceholderOperation = type({
7495
+ code: "'MIGRATION.UNFILLED_PLACEHOLDER'",
7496
+ meta: { operation: {
7497
+ id: "string",
7498
+ label: "string",
7499
+ operationClass: "'additive' | 'widening' | 'destructive' | 'data'"
7500
+ } }
7501
+ });
7502
+ /** The operation an unfilled placeholder's rejection says it stands for, when it says. */
7503
+ function placeholderOperationOf(reason) {
7504
+ if (!CliStructuredError$1.is(reason)) return void 0;
7505
+ const read = PlaceholderOperation({
7506
+ code: reason.code,
7507
+ meta: reason.meta ?? {}
7508
+ });
7509
+ return read instanceof type.errors ? void 0 : read.meta.operation;
6845
7510
  }
6846
7511
  async function writePlannedMigrationPackage(packageDir, fromHash, toHash, createdAt, leg) {
6847
7512
  const opsForWrite = leg.hasPlaceholders ? [] : leg.plannedOps;
@@ -7147,7 +7812,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
7147
7812
  to: toStorageHash,
7148
7813
  dir: baselineDir,
7149
7814
  baselineDir,
7150
- operations: operationSummaries(baselineLeg.value.plannedOps),
7815
+ operations: baselineLeg.value.listedOps,
7151
7816
  emittedExtensionDirs,
7152
7817
  ...warnings.length > 0 ? { warnings } : {},
7153
7818
  pendingPlaceholders: true,
@@ -7195,8 +7860,8 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
7195
7860
  to: toStorageHash,
7196
7861
  dir: deltaDir,
7197
7862
  baselineDir,
7198
- operations: operationSummaries(deltaLeg.plannedOps),
7199
- baselineOperations: operationSummaries(baselineLeg.value.plannedOps),
7863
+ operations: deltaLeg.listedOps,
7864
+ baselineOperations: baselineLeg.value.listedOps,
7200
7865
  emittedExtensionDirs,
7201
7866
  ...warnings.length > 0 ? { warnings } : {},
7202
7867
  pendingPlaceholders: true,
@@ -7268,7 +7933,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
7268
7933
  from: fromHash,
7269
7934
  to: toStorageHash,
7270
7935
  dir,
7271
- operations: operationSummaries(deltaLeg.plannedOps),
7936
+ operations: deltaLeg.listedOps,
7272
7937
  emittedExtensionDirs,
7273
7938
  ...warnings.length > 0 ? { warnings } : {},
7274
7939
  pendingPlaceholders: true,
@@ -7463,4 +8128,4 @@ async function executeRefListCommand(options) {
7463
8128
  //#endregion
7464
8129
  export { refuseContractSpaceIntegrity as $, executeRefDeleteCommand as A, loadAggregateIntegrityViolations as B, executeDbSign as C, executeMigrationNewCommand as D, executeMigrateShowPlan as E, hasMigrationPath as F, looksLikePath as G, loadContractSource as H, isStatementVerb as I, matchConsents as J, mapContractAtError as K, labelsText as L, executeRefSetCommand as M, findPackageByDirPath as N, executeMigrationPlanCommand as O, formatSourceDiagnostic as P, readMigrationRefs as Q, listRefsByContractHash as R, executeDbInit as S, withWarningFindings as St, executeDbVerify as T, loadContractSourceWithStack as U, loadContractRawSafely as V, loadContractSpaceAggregateForCli as W, planEverySpace as X, migrationSpaceListEntriesFromAggregate as Y, preflightRefAdvancement as Z, deriveStatusEdgeAnnotations as _, snapshotVerifierFor as _t, advanceRefSafely as a, requireDatabaseForLiveMarkerUse as at, enumerateCheckSpaces as b, toDeclaredExtensionsFromRaw as bt, buildContractSpaceAggregate as c, resolveContractRefToSnapshot as ct, buildRefAdvancementFields as d, resolveStatements as dt, refuseDeclaredExtensionTargetMismatch as et, checkSingleTarget as f, resolveToForPlan as ft, createControlClient as g, runMigrationList as gt, convertAndDelete as h, runMigrationCheck as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, renamedAndDeleted as it, executeRefListCommand as j, executeRefAdvancement as k, buildMigrationSpaceGraphEntries as l, resolveFromForPlan as lt, contractValidationMeta as m, runContractSpaceSeedPhase as mt, NO_REF_ADVANCEMENT as n, refusePackageCorruptionOnAggregate as nt, appContractStandInFromIdentity as o, resolveAppTargetPath as ot, computeRefAdvancementName as p, retryCommandFor as pt, mapIntegrityViolations as q, RECORDED_CONTRACT_REF_FORMS as r, refuseUnknownInvariants as rt, appliedHashesFromLedger as s, resolveContractRef$1 as st, ALL_CONTRACT_REF_FORMS as t, refuseMissingInvariantPath as tt, buildReadAggregate as u, resolveMigrationRef as ut, disposeEmitQueue as v, sourceWarningDiagnostic as vt, executeDbUpdate as w, executeContractEmit as x, validateLoadedContract as xt, enrichContract as y, statusForMigrationHash as yt, liveMarkerUse as z };
7465
8130
 
7466
- //# sourceMappingURL=ref-CKUrXPT8-BM2llFfO.mjs.map
8131
+ //# sourceMappingURL=ref-hKV9pGrC-CnbsvXzC.mjs.map