@hygraph/cli 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3258,6 +3258,48 @@ const SchemaDefinitionDocument = new TypedDocumentString(`
3258
3258
  }
3259
3259
  __typename
3260
3260
  }
3261
+ ... on UnionField {
3262
+ isMemberType
3263
+ union {
3264
+ id
3265
+ __typename
3266
+ }
3267
+ displayName
3268
+ description
3269
+ isList
3270
+ visibility
3271
+ position
3272
+ relationalFieldRules {
3273
+ connections {
3274
+ min
3275
+ max
3276
+ errorMessage
3277
+ __typename
3278
+ }
3279
+ __typename
3280
+ }
3281
+ visibilityCondition {
3282
+ baseField {
3283
+ apiId
3284
+ __typename
3285
+ }
3286
+ ... on BooleanFieldCondition {
3287
+ operator
3288
+ booleanValue: value
3289
+ __typename
3290
+ }
3291
+ ... on EnumerableFieldCondition {
3292
+ operator
3293
+ enumerationValues: value {
3294
+ apiId
3295
+ __typename
3296
+ }
3297
+ __typename
3298
+ }
3299
+ __typename
3300
+ }
3301
+ __typename
3302
+ }
3261
3303
  __typename
3262
3304
  }
3263
3305
  __typename
@@ -3559,8 +3601,10 @@ function isRename(change) {
3559
3601
  * enumeration or a taxonomy deletes every field that uses it. Deleting a
3560
3602
  * value or a node is counted too, although Hygraph refuses it while entries
3561
3603
  * hold the value or a node of the subtree. A union
3562
- * update that drops a member deletes that member's content, and a rich text
3563
- * update that drops an embedded model deletes the embeds of its entries.
3604
+ * update that drops a member deletes that member's content, a union
3605
+ * reference's update that drops a model deletes that model's field back, and
3606
+ * a rich text update that drops an embedded model deletes the embeds of its
3607
+ * entries.
3564
3608
  */
3565
3609
  function isDestructive(change) {
3566
3610
  return change.action === "delete" || dropsUnionMember(change) || dropsEmbed(change);
@@ -3585,11 +3629,12 @@ function dropsEmbed(change) {
3585
3629
  }
3586
3630
  /**
3587
3631
  * A union update whose new members leave out an old one: Hygraph deletes
3588
- * that component's content from every entry.
3632
+ * that component's content from every entry, or that model's field back
3633
+ * and its values.
3589
3634
  */
3590
3635
  function dropsUnionMember(change) {
3591
- if (change.resource !== "field" || change.action !== "update" || change.kind !== "componentUnion") return false;
3592
- const members = change.changes.components;
3636
+ if (change.resource !== "field" || change.action !== "update") return false;
3637
+ const members = change.kind === "componentUnion" ? change.changes.components : change.kind === "referenceUnion" ? change.changes.to : void 0;
3593
3638
  return members !== void 0 && members.from.some((apiId) => !members.to.includes(apiId));
3594
3639
  }
3595
3640
  //#endregion
@@ -5443,6 +5488,8 @@ const FIELD_FAMILY = {
5443
5488
  referenceOneWay: "Relational",
5444
5489
  referenceTwoWay: "Relational",
5445
5490
  asset: "Relational",
5491
+ referenceUnion: "Union",
5492
+ referenceUnionMember: "Union",
5446
5493
  component: "Component",
5447
5494
  componentUnion: "ComponentUnion",
5448
5495
  taxonomy: "Taxonomy"
@@ -5501,6 +5548,10 @@ const FIELD_BUILDERS = {
5501
5548
  create: createRelationalField,
5502
5549
  update: updateRelationalField
5503
5550
  },
5551
+ Union: {
5552
+ create: createUnionField,
5553
+ update: updateUnionField
5554
+ },
5504
5555
  Taxonomy: {
5505
5556
  create: createTaxonomyField,
5506
5557
  update: updateTaxonomyField
@@ -5921,6 +5972,68 @@ function embeddableModelsInput(from, to) {
5921
5972
  };
5922
5973
  }
5923
5974
  /**
5975
+ * A union reference and, on a model, every member's field back. The batch
5976
+ * gives all members the values of the first by model apiId, and ignores
5977
+ * their positions; the plan sends what differs, and every position, with an
5978
+ * update per member after the creates. On a component, the server makes
5979
+ * hidden members of its own and ignores everything but the models.
5980
+ */
5981
+ function createUnionField({ parent, members = [], memberName }, field) {
5982
+ if (field.kind !== "referenceUnion") throw new Error(`${parent}.${field.apiId} is a union member, which its union creates`);
5983
+ const [first] = members;
5984
+ return {
5985
+ apiId: field.apiId,
5986
+ parentApiId: parent,
5987
+ displayName: field.displayName,
5988
+ description: field.description,
5989
+ isList: field.list,
5990
+ visibility: field.visibility,
5991
+ visibilityCondition: field.visibilityCondition,
5992
+ relationalFieldRules: field.rules,
5993
+ position: field.position,
5994
+ reverseField: first === void 0 ? { modelApiIds: field.to } : {
5995
+ apiId: first.field.apiId,
5996
+ displayName: memberName ?? first.field.displayName,
5997
+ description: first.field.description,
5998
+ isList: first.field.list,
5999
+ visibility: first.field.visibility,
6000
+ modelApiIds: field.to,
6001
+ positions: members.map((member) => ({
6002
+ modelApiId: member.parent,
6003
+ position: member.field.position
6004
+ }))
6005
+ }
6006
+ };
6007
+ }
6008
+ /**
6009
+ * Only the attributes that change are sent. A union's member models are
6010
+ * sent whole, with every member's position: the server moves a member it
6011
+ * is not given a position for to 0. On a member, the update changes that
6012
+ * member's field only, a rename included.
6013
+ */
6014
+ function updateUnionField(change) {
6015
+ const { apiId, displayName, description, visibility, visibilityCondition, position, rules, to } = change.changes;
6016
+ const input = {
6017
+ apiId: change.apiId,
6018
+ parentApiId: change.parent
6019
+ };
6020
+ if (apiId) input.newApiId = apiId.to;
6021
+ if (displayName) input.displayName = displayName.to;
6022
+ if (description) input.description = description.to;
6023
+ if (visibility) input.visibility = visibility.to;
6024
+ if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
6025
+ if (position) input.position = position.to;
6026
+ if (rules) input.relationalFieldRules = rules.to;
6027
+ if (to) input.reverseField = {
6028
+ modelApiIds: to.to,
6029
+ positions: Object.entries(change.memberPositions ?? {}).map(([modelApiId, memberPosition]) => ({
6030
+ modelApiId,
6031
+ position: memberPosition
6032
+ }))
6033
+ };
6034
+ return input;
6035
+ }
6036
+ /**
5924
6037
  * A slug's settings under Studio's names. A create takes them as the
5925
6038
  * `formConfig`, an update as its `config`: the server ignores them
5926
6039
  * anywhere else (checked against the dev project).
@@ -6248,7 +6361,8 @@ function renderFieldChange(change, width, colors) {
6248
6361
  attribute: "migrationValue",
6249
6362
  text: value(change.migrationValue)
6250
6363
  }],
6251
- ...change.partner === void 0 ? [] : [partnerRow(change.partner)]
6364
+ ...change.partner === void 0 ? [] : [partnerRow(change.partner)],
6365
+ ...(change.members ?? []).map(memberRow)
6252
6366
  ], colors)];
6253
6367
  case "update": {
6254
6368
  if (unsupportedFieldMove(change)) return [` ${colors.yellow(`~ ${op}`)} ${subject} ${colors.dim(change.type)}`, ...renderAttributes(change.changes, colors)];
@@ -6257,8 +6371,8 @@ function renderFieldChange(change, width, colors) {
6257
6371
  return [` ${colors.yellow(`~ ${op}`)} ${apiId ? `${subject} → ${apiId.to}` : subject}${warning}`, ...renderAttributes(attributes, colors, change.migrationValue)];
6258
6372
  }
6259
6373
  case "delete": {
6260
- const { partner } = change;
6261
- const deletes = partner === void 0 ? "the field and all its values" : `the field, its partner ${partner.parent}.${partner.apiId} and all their values`;
6374
+ const { partner, members } = change;
6375
+ const deletes = partner !== void 0 ? `the field, its partner ${partner.parent}.${partner.apiId} and all their values` : members !== void 0 ? `the field, its members ${members.map((member) => `${member.parent}.${member.apiId}`).join(", ")} and all their values` : "the field and all its values";
6262
6376
  return [` ${colors.red(`- ${op}`)} ${subject} ${colors.yellow(`⚠ deletes ${deletes}`)}`];
6263
6377
  }
6264
6378
  }
@@ -6294,6 +6408,14 @@ function partnerRow(partner) {
6294
6408
  entries: settingRows(partner, UNSHOWN_ON_PARTNER).map(({ attribute, text }) => [attribute, text])
6295
6409
  };
6296
6410
  }
6411
+ /** A union member's field back, created with the union, one entry per setting. */
6412
+ function memberRow({ parent, field }) {
6413
+ return {
6414
+ attribute: `${parent}.${field.apiId}`,
6415
+ text: "",
6416
+ entries: settingRows(field, UNSHOWN_ON_PARTNER).map(({ attribute, text }) => [attribute, text])
6417
+ };
6418
+ }
6297
6419
  /**
6298
6420
  * One line per changed attribute, old value to new, under the change. A
6299
6421
  * migration value is one more line in the same column: the value existing
@@ -12594,6 +12716,13 @@ const referenceTwoWayFieldSchema$1 = strictObject({
12594
12716
  rules: referenceRulesSchema.nullable(),
12595
12717
  required: literal(false)
12596
12718
  });
12719
+ const referenceUnionMemberFieldSchema$1 = strictObject({
12720
+ ...fieldAttributes,
12721
+ kind: literal("referenceUnionMember"),
12722
+ to: string$1(),
12723
+ reverse: string$1(),
12724
+ required: literal(false)
12725
+ });
12597
12726
  const fieldSchema$1 = discriminatedUnion("kind", [
12598
12727
  strictObject({
12599
12728
  ...fieldAttributes,
@@ -12700,6 +12829,15 @@ const fieldSchema$1 = discriminatedUnion("kind", [
12700
12829
  required: literal(false)
12701
12830
  }),
12702
12831
  referenceTwoWayFieldSchema$1,
12832
+ strictObject({
12833
+ ...fieldAttributes,
12834
+ kind: literal("referenceUnion"),
12835
+ to: array(string$1()),
12836
+ reverse: string$1().nullable(),
12837
+ rules: referenceRulesSchema.nullable(),
12838
+ required: literal(false)
12839
+ }),
12840
+ referenceUnionMemberFieldSchema$1,
12703
12841
  strictObject({
12704
12842
  ...fieldAttributes,
12705
12843
  kind: literal("asset")
@@ -12725,7 +12863,12 @@ const changeSchema = discriminatedUnion("resource", [
12725
12863
  parent: string$1(),
12726
12864
  field: fieldSchema$1,
12727
12865
  migrationValue: migrationValueSchema.optional(),
12728
- partner: referenceTwoWayFieldSchema$1.optional()
12866
+ partner: referenceTwoWayFieldSchema$1.optional(),
12867
+ members: array(strictObject({
12868
+ parent: string$1(),
12869
+ field: referenceUnionMemberFieldSchema$1
12870
+ })).optional(),
12871
+ memberName: string$1().optional()
12729
12872
  }),
12730
12873
  discriminatedUnion("kind", [strictObject({
12731
12874
  action: literal("update"),
@@ -12749,6 +12892,8 @@ const changeSchema = discriminatedUnion("resource", [
12749
12892
  "componentUnion",
12750
12893
  "referenceOneWay",
12751
12894
  "referenceTwoWay",
12895
+ "referenceUnion",
12896
+ "referenceUnionMember",
12752
12897
  "asset"
12753
12898
  ]),
12754
12899
  changes: strictObject({
@@ -12767,11 +12912,13 @@ const changeSchema = discriminatedUnion("resource", [
12767
12912
  validations: attributeChangeSchema(union([stringValidationRulesSchema$1, numberValidationRulesSchema]).nullable()),
12768
12913
  slug: attributeChangeSchema(slugSettingsSchema.nullable()),
12769
12914
  components: attributeChangeSchema(array(string$1())),
12915
+ to: attributeChangeSchema(array(string$1())),
12770
12916
  rules: attributeChangeSchema(referenceRulesSchema.nullable()),
12771
12917
  embeds: attributeChangeSchema(array(string$1()).nullable()),
12772
12918
  actions: attributeChangeSchema(richTextActionsSchema.nullable())
12773
12919
  }).partial(),
12774
- migrationValue: migrationValueSchema.optional()
12920
+ migrationValue: migrationValueSchema.optional(),
12921
+ memberPositions: record(string$1(), number()).optional()
12775
12922
  }), strictObject({
12776
12923
  action: literal("update"),
12777
12924
  resource: literal("field"),
@@ -12786,7 +12933,8 @@ const changeSchema = discriminatedUnion("resource", [
12786
12933
  resource: literal("field"),
12787
12934
  parent: string$1(),
12788
12935
  apiId: string$1(),
12789
- partner: fieldRefSchema.optional()
12936
+ partner: fieldRefSchema.optional(),
12937
+ members: array(fieldRefSchema).optional()
12790
12938
  })
12791
12939
  ])
12792
12940
  ]);
@@ -13636,7 +13784,7 @@ function convertCreateReferenceTwoWayFieldToIR(input, models, partners) {
13636
13784
  description: isEmpty(field.description) ? null : field.description,
13637
13785
  to: reverse.modelApiId,
13638
13786
  reverse: reverse.apiId,
13639
- rules: convertRules(field.relationalFieldRules),
13787
+ rules: convertRules$1(field.relationalFieldRules),
13640
13788
  position: field.position,
13641
13789
  list: field.isList ?? false,
13642
13790
  required: false,
@@ -13652,7 +13800,7 @@ function convertCreateReferenceTwoWayFieldToIR(input, models, partners) {
13652
13800
  description: isEmpty(reverse.description) ? null : reverse.description,
13653
13801
  to: field.parentApiId,
13654
13802
  reverse: field.apiId,
13655
- rules: convertRules(partner?.relationalFieldRules),
13803
+ rules: convertRules$1(partner?.relationalFieldRules),
13656
13804
  position: reverse.position,
13657
13805
  list: reverse.isList ?? false,
13658
13806
  required: false,
@@ -13661,7 +13809,7 @@ function convertCreateReferenceTwoWayFieldToIR(input, models, partners) {
13661
13809
  }
13662
13810
  }];
13663
13811
  }
13664
- function convertRules(rules) {
13812
+ function convertRules$1(rules) {
13665
13813
  const connections = convertRange(rules?.connections);
13666
13814
  return connections === null ? null : { connections };
13667
13815
  }
@@ -13958,6 +14106,117 @@ function convertCreateTaxonomyFieldToIR(input) {
13958
14106
  };
13959
14107
  }
13960
14108
  //#endregion
14109
+ //#region src/live/resources/union.zod.ts
14110
+ const createReferenceUnionFieldSchema = object$1({
14111
+ apiId: string$1(),
14112
+ parentApiId: string$1(),
14113
+ displayName: string$1(),
14114
+ description: string$1().nullish(),
14115
+ isList: boolean().nullish(),
14116
+ visibility: fieldVisibilitySchema.nullish(),
14117
+ position: number(),
14118
+ visibilityCondition: liveVisibilityConditionSchema.nullish(),
14119
+ relationalFieldRules: object$1({ connections: liveRangeSchema.nullish() }).nullish(),
14120
+ reverseField: object$1({
14121
+ apiId: string$1(),
14122
+ modelApiIds: array(string$1())
14123
+ })
14124
+ });
14125
+ //#endregion
14126
+ //#region src/live/resources/union.ts
14127
+ const NO_UNION_LOOKUP = {
14128
+ owners: /* @__PURE__ */ new Map(),
14129
+ members: /* @__PURE__ */ new Map()
14130
+ };
14131
+ /**
14132
+ * A union's members on `models`, each with its own apiId: by the union's
14133
+ * id where `lookup` has it, otherwise under `reverse`. A model with no
14134
+ * member found is left out.
14135
+ */
14136
+ function findMembers(lookup, union, reverse, models) {
14137
+ const id = lookup.owners.get(`${union.parentApiId}.${union.apiId}`);
14138
+ const found = /* @__PURE__ */ new Map();
14139
+ for (const model of models) {
14140
+ if (id === void 0) {
14141
+ const settings = lookup.members.get(`${model}.${reverse}`);
14142
+ if (settings) found.set(model, {
14143
+ apiId: reverse,
14144
+ settings
14145
+ });
14146
+ continue;
14147
+ }
14148
+ for (const [key, settings] of lookup.members) if (settings.union === id && key.startsWith(`${model}.`)) found.set(model, {
14149
+ apiId: key.slice(model.length + 1),
14150
+ settings
14151
+ });
14152
+ }
14153
+ return found;
14154
+ }
14155
+ /**
14156
+ * A union reference on one of `models` or `components`, in the same
14157
+ * canonical form the config gives it, and on a model each member's field
14158
+ * back. A component's members are hidden and have no slot. `null` for a
14159
+ * union the CLI does not read: one listing a model that is not one of
14160
+ * `models`, such as a system model, or on a model, one whose members
14161
+ * `lookup` does not hold, have different apiIds, differ in `list`, or have
14162
+ * rules, which Studio cannot set.
14163
+ */
14164
+ function convertCreateReferenceUnionFieldToIR(input, models, components, lookup) {
14165
+ const parsed = createReferenceUnionFieldSchema.safeParse(input);
14166
+ if (!parsed.success) throw new Error(`Invalid createUnionField params: \n${renderIssues(parsed.error.issues)}`);
14167
+ const field = parsed.data;
14168
+ const { modelApiIds, apiId: reverse } = field.reverseField;
14169
+ const onModel = models.has(field.parentApiId);
14170
+ if (!onModel && !components.has(field.parentApiId) || !modelApiIds.every((apiId) => models.has(apiId))) return null;
14171
+ const owner = {
14172
+ parentApiId: field.parentApiId,
14173
+ field: {
14174
+ kind: "referenceUnion",
14175
+ apiId: field.apiId,
14176
+ displayName: field.displayName,
14177
+ description: isEmpty(field.description) ? null : field.description,
14178
+ to: modelApiIds.toSorted(),
14179
+ reverse: onModel ? reverse : null,
14180
+ rules: convertRules(field.relationalFieldRules),
14181
+ position: field.position,
14182
+ list: field.isList ?? false,
14183
+ required: false,
14184
+ visibility: field.visibility ?? "READ_WRITE",
14185
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
14186
+ }
14187
+ };
14188
+ if (!onModel) return [owner];
14189
+ const members = findMembers(lookup, field, reverse, modelApiIds);
14190
+ const sides = [];
14191
+ for (const model of modelApiIds) {
14192
+ const found = members.get(model);
14193
+ if (found === void 0 || found.apiId !== reverse || convertRules(found.settings.relationalFieldRules)) return null;
14194
+ const member = found.settings;
14195
+ sides.push({
14196
+ parentApiId: model,
14197
+ field: {
14198
+ kind: "referenceUnionMember",
14199
+ apiId: reverse,
14200
+ displayName: member.displayName,
14201
+ description: isEmpty(member.description) ? null : member.description,
14202
+ to: field.parentApiId,
14203
+ reverse: field.apiId,
14204
+ position: member.position,
14205
+ list: member.isList,
14206
+ required: false,
14207
+ visibility: member.visibility,
14208
+ visibilityCondition: convertVisibilityCondition(member.visibilityCondition)
14209
+ }
14210
+ });
14211
+ }
14212
+ if (new Set(sides.map((side) => side.field.list)).size > 1) return null;
14213
+ return [owner, ...sides];
14214
+ }
14215
+ function convertRules(rules) {
14216
+ const connections = convertRange(rules?.connections);
14217
+ return connections === null ? null : { connections };
14218
+ }
14219
+ //#endregion
13961
14220
  //#region src/live/resources/unsupported.zod.ts
13962
14221
  /** Not strict, as every live schema: the IR reads only the slot. */
13963
14222
  const createUnsupportedFieldSchema = object$1({
@@ -14046,17 +14305,61 @@ function findUnsupportedPairs(ops, environment) {
14046
14305
  }]] : [];
14047
14306
  });
14048
14307
  }
14049
- /** The union's field, and its other side on each member model. */
14050
- function convertCreateUnionFieldToIR(input) {
14308
+ /**
14309
+ * The unions on models that `environment` holds as unsupported fields,
14310
+ * with their members that are too. Deleting the union deletes its members,
14311
+ * so the diff sends one delete for all of them.
14312
+ */
14313
+ function findUnsupportedUnions(ops, environment, unions = NO_UNION_LOOKUP) {
14314
+ const models = new Map(environment.models.map((model) => [model.apiId, model]));
14315
+ const unsupported = (parent, apiId) => models.get(parent)?.fields[apiId]?.kind === "unsupported";
14316
+ return ops.flatMap((op) => {
14317
+ const parsed = createUnionFieldSchema.safeParse(op.createUnionField);
14318
+ if (!parsed.success || !unsupported(parsed.data.parentApiId, parsed.data.apiId)) return [];
14319
+ const { apiId, parentApiId } = parsed.data;
14320
+ const members = memberSlots(parsed.data, unions).filter(({ modelApiId, apiId: member }) => unsupported(modelApiId, member)).map(({ modelApiId, apiId: member }) => ({
14321
+ parent: modelApiId,
14322
+ apiId: member
14323
+ }));
14324
+ return members.length === 0 ? [] : [{
14325
+ owner: {
14326
+ parent: parentApiId,
14327
+ apiId
14328
+ },
14329
+ members
14330
+ }];
14331
+ });
14332
+ }
14333
+ /**
14334
+ * The union's field, and its other side on each member model, under the
14335
+ * apiId `unions` finds it by. A union on one of `components` has hidden
14336
+ * ones, which the server does not number, so they have no slot.
14337
+ */
14338
+ function convertCreateUnionFieldToIR(input, components, unions = NO_UNION_LOOKUP) {
14051
14339
  const field = parse$1("createUnionField", createUnionFieldSchema, input);
14052
- return [{
14340
+ const owner = {
14053
14341
  parentApiId: field.parentApiId,
14054
14342
  field: unsupportedField(field.apiId, "UNION", field.position)
14055
- }, ...field.reverseField.positions.map(({ modelApiId, position }) => ({
14343
+ };
14344
+ if (components.has(field.parentApiId)) return [owner];
14345
+ return [owner, ...memberSlots(field, unions).map(({ modelApiId, apiId, position }) => ({
14056
14346
  parentApiId: modelApiId,
14057
- field: unsupportedField(field.reverseField.apiId, "UNION", position)
14347
+ field: unsupportedField(apiId, "UNION", position)
14058
14348
  }))];
14059
14349
  }
14350
+ /**
14351
+ * Each member's model, apiId and position. `schemaDefinition` names them
14352
+ * all after the first member; `unions` has each one's own.
14353
+ */
14354
+ function memberSlots(field, unions) {
14355
+ const { apiId, positions } = field.reverseField;
14356
+ const members = findMembers(unions, field, apiId, positions.map(({ modelApiId }) => modelApiId));
14357
+ return positions.map(({ modelApiId, position }) => ({
14358
+ modelApiId,
14359
+ apiId: members.get(modelApiId)?.apiId ?? apiId,
14360
+ position
14361
+ }));
14362
+ }
14060
14363
  function unsupportedField(apiId, type, position) {
14061
14364
  return {
14062
14365
  kind: "unsupported",
@@ -14084,9 +14387,11 @@ function parse$1(operation, schema, input) {
14084
14387
  * op, `createLocale` and `createStage` included, and fields on anything
14085
14388
  * but a model or a component, are skipped until the IR has a place for
14086
14389
  * them. A two-way relation's other side takes its rules and condition from
14087
- * `partners`, which `schemaDefinition` leaves out.
14390
+ * `partners`, which `schemaDefinition` leaves out, and a union's members
14391
+ * their apiIds and settings from `unions`: `schemaDefinition` gives the
14392
+ * first one's.
14088
14393
  */
14089
- function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map()) {
14394
+ function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map(), unions = NO_UNION_LOOKUP) {
14090
14395
  const enumerations = [];
14091
14396
  const taxonomies = [];
14092
14397
  const components = [];
@@ -14099,6 +14404,7 @@ function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map())
14099
14404
  }
14100
14405
  const parents = new Map([...models, ...components].map((parent) => [parent.apiId, parent]));
14101
14406
  const modelApiIds = new Set(models.map((model) => model.apiId));
14407
+ const componentApiIds = new Set(components.map((component) => component.apiId));
14102
14408
  for (const op of ops) {
14103
14409
  const [operationName] = Object.keys(op);
14104
14410
  switch (operationName) {
@@ -14129,7 +14435,7 @@ function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map())
14129
14435
  break;
14130
14436
  }
14131
14437
  case "createUnionField":
14132
- for (const live of convertCreateUnionFieldToIR(op.createUnionField)) addField(parents, live);
14438
+ for (const live of convertCreateReferenceUnionFieldToIR(op.createUnionField, modelApiIds, componentApiIds, unions) ?? convertCreateUnionFieldToIR(op.createUnionField, componentApiIds, unions)) addField(parents, live);
14133
14439
  break;
14134
14440
  case "createTaxonomyField":
14135
14441
  addField(parents, convertCreateTaxonomyFieldToIR(op.createTaxonomyField));
@@ -14237,8 +14543,9 @@ var LiveSchemaFailure = class extends Failure {};
14237
14543
  * same request lists the other components, and only those are kept. It
14238
14544
  * also leaves out the default locale, and Draft and Published, so the
14239
14545
  * locales and stages come from the same request's `contentModel`, and a
14240
- * two-way relation's other side without its rules and condition, so they
14241
- * come from its `models`.
14546
+ * two-way relation's other side without its rules and condition, and a
14547
+ * union's members with the first one's settings, so they come from its
14548
+ * `models`.
14242
14549
  */
14243
14550
  async function readLiveEnvironment(target, fetch) {
14244
14551
  if (isEmpty(target.token)) throw new LiveSchemaFailure(`target "${target.name}" has no token`);
@@ -14254,11 +14561,13 @@ async function readLiveEnvironment(target, fetch) {
14254
14561
  throw new LiveSchemaFailure(describeManagementError(error, target.endpoint));
14255
14562
  }
14256
14563
  const { environment } = extractProject(result.viewer, target);
14257
- const live = convertSchemaDefinitionToIR(environment.schemaDefinition, partnerLookup(environment.contentModel.models));
14564
+ const unions = unionLookup(environment.contentModel.models);
14565
+ const live = convertSchemaDefinitionToIR(environment.schemaDefinition, partnerLookup(environment.contentModel.models), unions);
14258
14566
  const components = new Set(environment.contentModel.components.map(({ apiId }) => apiId));
14259
14567
  return {
14260
14568
  environmentId: environment.id,
14261
14569
  unsupportedPairs: findUnsupportedPairs(environment.schemaDefinition, live),
14570
+ unsupportedUnions: findUnsupportedUnions(environment.schemaDefinition, live, unions),
14262
14571
  environment: {
14263
14572
  locales: convertLocalesToIR(environment.contentModel.locales),
14264
14573
  stages: convertStagesToIR(environment.contentModel.stages),
@@ -14274,6 +14583,26 @@ function partnerLookup(models) {
14274
14583
  visibilityCondition: liveCondition(field.visibilityCondition)
14275
14584
  }]] : [])));
14276
14585
  }
14586
+ /** Every union's id, and every union member's settings, by `Model.field`. */
14587
+ function unionLookup(models) {
14588
+ const fields = models.flatMap((model) => model.fields.flatMap((field) => field.__typename === "UnionField" ? [{
14589
+ key: `${model.apiId}.${field.apiId}`,
14590
+ field
14591
+ }] : []));
14592
+ return {
14593
+ owners: new Map(fields.filter(({ field }) => !field.isMemberType).map(({ key, field }) => [key, field.union.id])),
14594
+ members: new Map(fields.filter(({ field }) => field.isMemberType).map(({ key, field }) => [key, {
14595
+ displayName: field.displayName,
14596
+ description: field.description ?? null,
14597
+ isList: field.isList,
14598
+ visibility: field.visibility,
14599
+ position: field.position,
14600
+ relationalFieldRules: field.relationalFieldRules,
14601
+ visibilityCondition: liveCondition(field.visibilityCondition),
14602
+ union: field.union.id
14603
+ }]))
14604
+ };
14605
+ }
14277
14606
  /** The query's condition in the names `schemaDefinition` gives it. */
14278
14607
  function liveCondition(condition) {
14279
14608
  if (condition === null) return null;
@@ -14661,6 +14990,15 @@ const messages = {
14661
14990
  ["field.referencePartnerMissing"]: (field, partner, problem) => `Field "${field}" names "${partner}" as its partner, which ${problem}.`,
14662
14991
  ["field.referencePartnerMismatch"]: (field, partner, partnerTarget) => `Field "${field}" names "${partner}" as its partner, which names "${partnerTarget}" instead.`,
14663
14992
  ["field.referenceSelfPartner"]: (field) => `Field "${field}" names itself as its partner.`,
14993
+ ["field.referenceUnionEmpty"]: (field) => `Field "${field}" lets editors choose from no model.`,
14994
+ ["field.referenceUnionDuplicate"]: (field, model) => `Field "${field}" lists model "${model}" more than once.`,
14995
+ ["field.referenceUnionReverseMissing"]: (field) => `Field "${field}" is a union reference on a model, and names no field back.`,
14996
+ ["field.referenceUnionReverseOnComponent"]: (field) => `Field "${field}" is a union reference on a component, which has no field back to name.`,
14997
+ ["field.referenceUnionMemberMissing"]: (field, member) => `Field "${field}" names "${member}" as its field back, which is not a union member.`,
14998
+ ["field.referenceUnionMemberMismatch"]: (field, member, memberTarget) => `Field "${field}" names "${member}" as its field back, which names "${memberTarget}" instead.`,
14999
+ ["field.referenceUnionMemberListMismatch"]: (field) => `Field "${field}" has fields back that differ in list, and Hygraph gives them all the same.`,
15000
+ ["field.referenceUnionMemberOnComponent"]: (field) => `Field "${field}" is a union member on a component. Only models have them.`,
15001
+ ["field.unionOwnerMissing"]: (field, owner) => `Field "${field}" names "${owner}" as its union, which is not a union reference listing this model with this field as its field back.`,
14664
15002
  ["field.requiredNotVisible"]: (field, visibility) => `Field "${field}" is required and ${visibility}, so editors cannot fill it in.`,
14665
15003
  ["field.assetReverseInvalid"]: (field, reverse) => `Field "${field}" gets the field "${reverse}" on Asset, which is not a valid apiId.`,
14666
15004
  ["field.richTextEmbedsEmpty"]: (field) => `Field "${field}" has embeds, but names no model to embed.`,
@@ -14683,6 +15021,8 @@ const messages = {
14683
15021
  ["change.unsupportedFieldMissing"]: (kind, parent, apiId) => `Unsupported field "${apiId}" is not on ${kind} "${parent}" in the environment.`,
14684
15022
  ["change.unsupportedFieldType"]: (kind, parent, apiId, type, live) => `Unsupported field "${apiId}" on ${kind} "${parent}" has type "${type}", but the environment has ${live}.`,
14685
15023
  ["change.unsupportedPartnerDeleted"]: (parent, apiId, partnerParent, partnerApiId) => `Unsupported field "${apiId}" on model "${parent}" is one side of a two-way relation, and the config deletes the other side, "${partnerApiId}" on model "${partnerParent}". Hygraph deletes the two together.`,
15024
+ ["change.unsupportedUnionDeleted"]: (parent, apiId, unionParent, unionApiId) => `Unsupported field "${apiId}" on model "${parent}" is a member of the union "${unionApiId}" on model "${unionParent}", which the config deletes. Hygraph deletes the members with it.`,
15025
+ ["change.unsupportedUnionEmptied"]: (parent, apiId) => `Unsupported field "${apiId}" on model "${parent}" is a union whose every member the config deletes. Hygraph deletes the union with its last member.`,
14686
15026
  ["change.enumerationRenameSourceMissing"]: (renamedFrom, apiId) => `Cannot rename enumeration "${renamedFrom}" to "${apiId}": neither apiId exists in the environment.`,
14687
15027
  ["change.valueRenameSourceMissing"]: (enumeration, renamedFrom, apiId) => `Cannot rename value "${renamedFrom}" to "${apiId}" in enumeration "${enumeration}": neither apiId exists there.`,
14688
15028
  ["change.valueRenameBothInUse"]: (enumeration, renamedFrom, apiId) => `Cannot rename value "${renamedFrom}" to "${apiId}" in enumeration "${enumeration}": both exist there.`,
@@ -14811,6 +15151,15 @@ const fixes = {
14811
15151
  ["field.referencePartnerMissing"]: "Add a define.field.referenceTwoWay to the model in to, with to set to this model and reverse set to this field's apiId. Or set reverse to the apiId of the one that is there.",
14812
15152
  ["field.referencePartnerMismatch"]: "Point the two fields at each other: each one's to is the other's model, and its reverse is the other's apiId.",
14813
15153
  ["field.referenceSelfPartner"]: "A two-way reference to its own model still has two fields. Set reverse to the apiId of another field on the model, which names this one back.",
15154
+ ["field.referenceUnionEmpty"]: "List at least one model in to.",
15155
+ ["field.referenceUnionDuplicate"]: "List each model once in to.",
15156
+ ["field.referenceUnionReverseMissing"]: "Set reverse to the apiId of the define.field.referenceUnionMember each model in to has.",
15157
+ ["field.referenceUnionReverseOnComponent"]: "Remove reverse, or move the field to a model.",
15158
+ ["field.referenceUnionMemberMissing"]: "Add a define.field.referenceUnionMember with this apiId to the model, with to set to this model and reverse set to this field's apiId.",
15159
+ ["field.referenceUnionMemberMismatch"]: "Point the field back at this union: its to is this model, and its reverse is this field's apiId.",
15160
+ ["field.referenceUnionMemberListMismatch"]: "Set the same list on every define.field.referenceUnionMember of the union.",
15161
+ ["field.referenceUnionMemberOnComponent"]: "Move the union reference and its field back to models, or remove the field back.",
15162
+ ["field.unionOwnerMissing"]: "Add this model to the union's to and set its reverse to this field's apiId, or remove this field.",
14814
15163
  ["field.requiredNotVisible"]: "Set required: false, or make the field READ_WRITE or READ_ONLY.",
14815
15164
  ["field.assetReverseInvalid"]: "Use a valid field apiId, and keep it and its model's or component's apiId within 64 characters together: shorten either one if they are too long.",
14816
15165
  ["field.richTextEmbedsEmpty"]: "List at least one model in embeds, or remove embeds to turn them off.",
@@ -14833,6 +15182,8 @@ const fixes = {
14833
15182
  ["change.unsupportedFieldMissing"]: "Remove it from the config, or run export again.",
14834
15183
  ["change.unsupportedFieldType"]: "Run export again to write the field as the environment has it.",
14835
15184
  ["change.unsupportedPartnerDeleted"]: "Keep both sides in the config, or remove both.",
15185
+ ["change.unsupportedUnionDeleted"]: "Keep the union and its members in the config, or remove all of them.",
15186
+ ["change.unsupportedUnionEmptied"]: "Keep at least one member in the config, or remove the union with them.",
14836
15187
  ["change.enumerationRenameSourceMissing"]: "Set renamedFrom to the apiId the enumeration has in Hygraph right now, or remove it to create the enumeration.",
14837
15188
  ["change.valueRenameSourceMissing"]: "Set renamedFrom to the apiId the value has in Hygraph right now, or remove it to create the value.",
14838
15189
  ["change.valueRenameBothInUse"]: "Delete one of the two values first, in a plan of its own, or remove renamedFrom.",
@@ -15079,28 +15430,19 @@ function validateReferenceField(parent, field) {
15079
15430
  */
15080
15431
  function validateReferenceModelReferences(parent, fields, models) {
15081
15432
  return fields.flatMap((field) => {
15082
- if (field.__typename !== "ReferenceOneWayField" && field.__typename !== "ReferenceTwoWayField") return [];
15083
- const target = field.to();
15084
- const { apiId } = target;
15085
- if (target.__typename === "Component") {
15086
- const code = "field.referenceToComponent";
15087
- return [{
15433
+ if (field.__typename !== "ReferenceOneWayField" && field.__typename !== "ReferenceTwoWayField" && field.__typename !== "ReferenceUnionField" && field.__typename !== "ReferenceUnionMemberField") return [];
15434
+ const targets = field.__typename === "ReferenceUnionField" ? field.to.map((model) => model()) : [field.to()];
15435
+ const path = fieldPath(parent, field.apiId, "to");
15436
+ return [...new Map(targets.map((target) => [target.apiId, target])).values()].flatMap(({ __typename, apiId }) => {
15437
+ const code = __typename === "Component" ? "field.referenceToComponent" : models.has(apiId) ? null : "field.referenceModelMissing";
15438
+ return code === null ? [] : [{
15088
15439
  code,
15089
15440
  severity: "error",
15090
- path: fieldPath(parent, field.apiId, "to"),
15441
+ path,
15091
15442
  message: messages[code](field.apiId, apiId),
15092
15443
  fix: fixes[code]
15093
15444
  }];
15094
- }
15095
- if (models.has(apiId)) return [];
15096
- const code = "field.referenceModelMissing";
15097
- return [{
15098
- code,
15099
- severity: "error",
15100
- path: fieldPath(parent, field.apiId, "to"),
15101
- message: messages[code](field.apiId, apiId),
15102
- fix: fixes[code]
15103
- }];
15445
+ });
15104
15446
  });
15105
15447
  }
15106
15448
  //#endregion
@@ -15154,6 +15496,108 @@ function validateReferenceTwoWayPartners(parent, fields, models) {
15154
15496
  return validations;
15155
15497
  }
15156
15498
  //#endregion
15499
+ //#region src/define/fields/referenceUnion.validation.ts
15500
+ /** A union reference lists at least one model, each once. */
15501
+ function validateReferenceUnionField(parent, field) {
15502
+ const path = fieldPath(parent, field.apiId, "to");
15503
+ if (field.to.length === 0) {
15504
+ const code = "field.referenceUnionEmpty";
15505
+ return [{
15506
+ code,
15507
+ severity: "error",
15508
+ path,
15509
+ message: messages[code](field.apiId),
15510
+ fix: fixes[code]
15511
+ }];
15512
+ }
15513
+ const apiIds = field.to.map((model) => model().apiId);
15514
+ return [...new Set(apiIds.filter((apiId, index) => apiIds.indexOf(apiId) !== index))].map((apiId) => {
15515
+ const code = "field.referenceUnionDuplicate";
15516
+ return {
15517
+ code,
15518
+ severity: "error",
15519
+ path,
15520
+ message: messages[code](field.apiId, apiId),
15521
+ fix: fixes[code]
15522
+ };
15523
+ });
15524
+ }
15525
+ /**
15526
+ * A union reference on a model names its field back in `reverse`, and
15527
+ * each model in `to` has that field: a union member whose `to` is this
15528
+ * model and whose `reverse` is this field. Hygraph gives every member the
15529
+ * same `list`. A union reference on a component names none, and a union
15530
+ * member is on a model, under a union that lists that model. A model in
15531
+ * `to` the environment does not have is `field.referenceModelMissing`.
15532
+ */
15533
+ function validateReferenceUnionMembers(parent, fields, models) {
15534
+ const validations = [];
15535
+ const report = (code, apiId, attribute, message) => {
15536
+ validations.push({
15537
+ code,
15538
+ severity: "error",
15539
+ path: fieldPath(parent, apiId, attribute),
15540
+ message,
15541
+ fix: fixes[code]
15542
+ });
15543
+ };
15544
+ for (const field of fields) {
15545
+ if (field.__typename === "ReferenceUnionMemberField") {
15546
+ if (parent.kind === "component") {
15547
+ const code = "field.referenceUnionMemberOnComponent";
15548
+ report(code, field.apiId, "to", messages[code](field.apiId));
15549
+ continue;
15550
+ }
15551
+ const to = field.to().apiId;
15552
+ const model = models.get(to);
15553
+ if (model === void 0) continue;
15554
+ const owner = model.fields.find(({ apiId }) => apiId === field.reverse);
15555
+ if (owner?.__typename !== "ReferenceUnionField" || owner.reverse !== field.apiId || !owner.to.some((member) => member().apiId === parent.apiId)) {
15556
+ const code = "field.unionOwnerMissing";
15557
+ report(code, field.apiId, "reverse", messages[code](field.apiId, `${to}.${field.reverse}`));
15558
+ }
15559
+ continue;
15560
+ }
15561
+ if (field.__typename !== "ReferenceUnionField") continue;
15562
+ if (parent.kind === "component") {
15563
+ if (field.reverse !== null) {
15564
+ const code = "field.referenceUnionReverseOnComponent";
15565
+ report(code, field.apiId, "reverse", messages[code](field.apiId));
15566
+ }
15567
+ continue;
15568
+ }
15569
+ if (field.reverse === null) {
15570
+ const code = "field.referenceUnionReverseMissing";
15571
+ report(code, field.apiId, "reverse", messages[code](field.apiId));
15572
+ continue;
15573
+ }
15574
+ const lists = /* @__PURE__ */ new Set();
15575
+ for (const to of new Set(field.to.map((model) => model().apiId))) {
15576
+ const model = models.get(to);
15577
+ if (model === void 0) continue;
15578
+ const memberName = `${to}.${field.reverse}`;
15579
+ const member = model.fields.find(({ apiId }) => apiId === field.reverse);
15580
+ if (member?.__typename !== "ReferenceUnionMemberField") {
15581
+ const code = "field.referenceUnionMemberMissing";
15582
+ report(code, field.apiId, "reverse", messages[code](field.apiId, memberName));
15583
+ continue;
15584
+ }
15585
+ const memberTarget = `${member.to().apiId}.${member.reverse}`;
15586
+ if (memberTarget !== `${parent.apiId}.${field.apiId}`) {
15587
+ const code = "field.referenceUnionMemberMismatch";
15588
+ report(code, field.apiId, "reverse", messages[code](field.apiId, memberName, memberTarget));
15589
+ continue;
15590
+ }
15591
+ lists.add(member.list);
15592
+ }
15593
+ if (lists.size > 1) {
15594
+ const code = "field.referenceUnionMemberListMismatch";
15595
+ report(code, field.apiId, "reverse", messages[code](field.apiId));
15596
+ }
15597
+ }
15598
+ return validations;
15599
+ }
15600
+ //#endregion
15157
15601
  //#region src/define/fields/richText.validation.ts
15158
15602
  /**
15159
15603
  * What only rich text checks, from the server's rules and Studio's form:
@@ -15569,6 +16013,8 @@ function validateTypeOptions(parent, field) {
15569
16013
  case "ComponentUnionField": return validateComponentUnionField(parent, field);
15570
16014
  case "ReferenceOneWayField":
15571
16015
  case "ReferenceTwoWayField": return validateReferenceField(parent, field);
16016
+ case "ReferenceUnionField": return [...validateReferenceUnionField(parent, field), ...validateReferenceField(parent, field)];
16017
+ case "ReferenceUnionMemberField": return [];
15572
16018
  case "AssetField": return validateAssetField(parent, field);
15573
16019
  case "RichTextField": return validateRichTextField(parent, field);
15574
16020
  case "ColorField": return validateColorField(parent, field);
@@ -16360,7 +16806,7 @@ function validateEnvironment(environment) {
16360
16806
  kind: parent.kind,
16361
16807
  apiId: parent.apiId
16362
16808
  };
16363
- validations.push(...validateEnumerationFieldReferences(fieldParent, parent.fields, enumerations), ...validateComponentFieldReferences(fieldParent, parent.fields, components), ...validateReferenceModelReferences(fieldParent, parent.fields, new Set(models.keys())), ...validateReferenceTwoWayPartners(fieldParent, parent.fields, models), ...validateRichTextEmbedReferences(fieldParent, parent.fields, new Set(models.keys())), ...validateTaxonomyFieldReferences(fieldParent, parent.fields, taxonomies));
16809
+ validations.push(...validateEnumerationFieldReferences(fieldParent, parent.fields, enumerations), ...validateComponentFieldReferences(fieldParent, parent.fields, components), ...validateReferenceModelReferences(fieldParent, parent.fields, new Set(models.keys())), ...validateReferenceTwoWayPartners(fieldParent, parent.fields, models), ...validateRichTextEmbedReferences(fieldParent, parent.fields, new Set(models.keys())), ...validateReferenceUnionMembers(fieldParent, parent.fields, models), ...validateTaxonomyFieldReferences(fieldParent, parent.fields, taxonomies));
16364
16810
  }
16365
16811
  return validations;
16366
16812
  }
@@ -16558,6 +17004,150 @@ function twoWay(models, parent, apiId) {
16558
17004
  return field?.kind === "referenceTwoWay" ? field : void 0;
16559
17005
  }
16560
17006
  //#endregion
17007
+ //#region src/diff/resources/referenceUnion.ts
17008
+ const NO_UNIONS = {
17009
+ inPlace: /* @__PURE__ */ new Set(),
17010
+ cascaded: /* @__PURE__ */ new Set(),
17011
+ dropped: /* @__PURE__ */ new Set(),
17012
+ renumbered: /* @__PURE__ */ new Set(),
17013
+ deletedMembers: /* @__PURE__ */ new Map(),
17014
+ orphans: [],
17015
+ createdMembers: /* @__PURE__ */ new Map(),
17016
+ memberNames: /* @__PURE__ */ new Map(),
17017
+ madeMembers: /* @__PURE__ */ new Map(),
17018
+ memberPositions: /* @__PURE__ */ new Map()
17019
+ };
17020
+ /**
17021
+ * How the unions of `to` meet those of `from`, its renames already applied.
17022
+ * `unsupportedUnions` are the live unions read as unsupported fields, named
17023
+ * by `from`'s model apiIds; they are only ever deleted, and a member the
17024
+ * config drops while its union stays has a delete of its own.
17025
+ */
17026
+ function groupUnionReferences(from, to, unsupportedUnions = []) {
17027
+ const fromParents = parentsByApiId(from);
17028
+ const toParents = parentsByApiId(to);
17029
+ const toModels = new Set(to.models.map((model) => model.apiId));
17030
+ const inPlace = /* @__PURE__ */ new Set();
17031
+ const cascaded = /* @__PURE__ */ new Set();
17032
+ const dropped = /* @__PURE__ */ new Set();
17033
+ const renumbered = /* @__PURE__ */ new Set();
17034
+ const deletedMembers = /* @__PURE__ */ new Map();
17035
+ const orphans = [];
17036
+ const createdMembers = /* @__PURE__ */ new Map();
17037
+ const memberNames = /* @__PURE__ */ new Map();
17038
+ const madeMembers = /* @__PURE__ */ new Map();
17039
+ const memberPositions = /* @__PURE__ */ new Map();
17040
+ const given = /* @__PURE__ */ new Map();
17041
+ for (const { parent, field } of unions(to)) {
17042
+ const key = sideKey(parent, field.apiId);
17043
+ const members = membersOf(toParents, field);
17044
+ memberPositions.set(key, Object.fromEntries(members.map((member) => [member.parent, member.field.position])));
17045
+ const live = fromParents.get(parent)?.fields[field.apiId];
17046
+ const liveMembers = live?.kind === "referenceUnion" ? membersOf(fromParents, live) : [];
17047
+ const kept = live?.kind === "referenceUnion" ? field.to.filter((model) => live.to.includes(model)) : [];
17048
+ if (live?.kind === "referenceUnion" && live.list === field.list && live.reverse === field.reverse && liveMembers[0]?.field.list === members[0]?.field.list && kept.length > 0) {
17049
+ inPlace.add(key);
17050
+ const [first] = liveMembers;
17051
+ for (const member of members) {
17052
+ const memberKey = sideKey(member.parent, member.field.apiId);
17053
+ if (kept.includes(member.parent)) inPlace.add(memberKey);
17054
+ else if (first !== void 0) madeMembers.set(memberKey, {
17055
+ displayName: first.field.displayName,
17056
+ description: first.field.description,
17057
+ visibility: "READ_WRITE",
17058
+ named: true
17059
+ });
17060
+ }
17061
+ continue;
17062
+ }
17063
+ const taken = (displayName) => field.to.some((model) => given.get(model)?.has(displayName) === true || Object.values(toParents.get(model)?.fields ?? {}).some((other) => other.kind !== "unsupported" && other.displayName === displayName && !(other.kind === "referenceUnionMember" && other.to === parent && other.reverse === field.apiId)));
17064
+ const free = members.find((member) => !taken(member.field.displayName));
17065
+ const ordered = free === void 0 ? members : [free, ...members.filter((member) => member !== free)];
17066
+ createdMembers.set(key, ordered);
17067
+ const [first] = ordered;
17068
+ const memberName = free === void 0 && first !== void 0 ? freeName(field.reverse ?? field.apiId, taken) : void 0;
17069
+ if (memberName !== void 0) memberNames.set(key, memberName);
17070
+ const name = memberName ?? first?.field.displayName;
17071
+ if (name !== void 0) for (const member of members) given.set(member.parent, /* @__PURE__ */ new Set([...given.get(member.parent) ?? [], name]));
17072
+ for (const member of members) madeMembers.set(sideKey(member.parent, member.field.apiId), {
17073
+ displayName: memberName ?? first?.field.displayName ?? member.field.displayName,
17074
+ description: first?.field.description ?? member.field.description,
17075
+ visibility: first?.field.visibility ?? member.field.visibility,
17076
+ named: false
17077
+ });
17078
+ }
17079
+ const deleted = (owner, members) => {
17080
+ for (const member of members) cascaded.add(sideKey(member.parent, member.apiId));
17081
+ const staying = members.filter((member) => toModels.has(member.parent));
17082
+ if (staying.length === 0) return;
17083
+ if (toParents.has(owner.parent)) deletedMembers.set(sideKey(owner.parent, owner.apiId), staying);
17084
+ else orphans.push({
17085
+ owner,
17086
+ members: staying
17087
+ });
17088
+ };
17089
+ for (const { parent, field } of unions(from)) {
17090
+ const key = sideKey(parent, field.apiId);
17091
+ const members = membersOf(fromParents, field).map(({ parent: model, field: member }) => ({
17092
+ parent: model,
17093
+ apiId: member.apiId
17094
+ }));
17095
+ if (!inPlace.has(key)) {
17096
+ deleted({
17097
+ parent,
17098
+ apiId: field.apiId
17099
+ }, members);
17100
+ continue;
17101
+ }
17102
+ const union = toParents.get(parent)?.fields[field.apiId];
17103
+ if (field.reverse === null && union?.kind === "referenceUnion") {
17104
+ for (const model of field.to) if (!union.to.includes(model) && toModels.has(model)) renumbered.add(model);
17105
+ }
17106
+ for (const member of members) if (union?.kind === "referenceUnion" && !union.to.includes(member.parent) && toModels.has(member.parent)) dropped.add(sideKey(member.parent, member.apiId));
17107
+ }
17108
+ for (const { owner, members } of unsupportedUnions) if (toParents.get(owner.parent)?.fields[owner.apiId]?.kind !== "unsupported") deleted(owner, members);
17109
+ return {
17110
+ inPlace,
17111
+ cascaded,
17112
+ dropped,
17113
+ renumbered,
17114
+ deletedMembers,
17115
+ orphans,
17116
+ createdMembers,
17117
+ memberNames,
17118
+ madeMembers,
17119
+ memberPositions
17120
+ };
17121
+ }
17122
+ /** `base`, or `base 2`, `base 3`… the first one `taken` leaves free. */
17123
+ function freeName(base, taken) {
17124
+ let name = base;
17125
+ for (let count = 2; taken(name); count += 1) name = `${base} ${count}`;
17126
+ return name;
17127
+ }
17128
+ function parentsByApiId(environment) {
17129
+ return new Map([...environment.models, ...environment.components].map((parent) => [parent.apiId, parent]));
17130
+ }
17131
+ /** Every union, in the order the diff creates them: by parent, then apiId. */
17132
+ function unions(environment) {
17133
+ return [...environment.models, ...environment.components].flatMap((parent) => Object.values(parent.fields).toSorted(byApiId$1).flatMap((field) => field.kind === "referenceUnion" ? [{
17134
+ parent: parent.apiId,
17135
+ field
17136
+ }] : []));
17137
+ }
17138
+ /** A union's members, by its models' apiId order. A component's are hidden. */
17139
+ function membersOf(parents, union) {
17140
+ const { reverse } = union;
17141
+ if (reverse === null) return [];
17142
+ return union.to.flatMap((model) => {
17143
+ const field = parents.get(model)?.fields[reverse];
17144
+ return field?.kind === "referenceUnionMember" ? [{
17145
+ parent: model,
17146
+ field
17147
+ }] : [];
17148
+ });
17149
+ }
17150
+ //#endregion
16561
17151
  //#region src/diff/resources/field.ts
16562
17152
  /**
16563
17153
  * The field changes that take `from`'s fields to `to`'s, on the model or
@@ -16567,34 +17157,44 @@ function twoWay(models, parent, apiId) {
16567
17157
  * change that makes a field required and nowhere else. An unsupported field is
16568
17158
  * moved or deleted, never created: `validateUnsupportedFields` refuses one that
16569
17159
  * live does not have. `pairs` says which two-way sides change in place,
16570
- * and which one of a pair sends its delete or its create.
17160
+ * and which one of a pair sends its delete or its create; `unions` the
17161
+ * same for union references and their members.
16571
17162
  */
16572
- function diffFields(from, to, migrationValues = /* @__PURE__ */ new Map(), pairs = NO_PAIRS) {
17163
+ function diffFields(from, to, migrationValues = /* @__PURE__ */ new Map(), pairs = NO_PAIRS, unions = NO_UNIONS) {
16573
17164
  const parent = to.apiId;
16574
17165
  const fromFields = from?.fields ?? {};
16575
17166
  const changes = {
16576
17167
  deletes: [],
16577
17168
  updates: [],
16578
17169
  creates: [],
16579
- conditions: []
17170
+ conditions: [],
17171
+ memberDrops: [],
17172
+ memberAdds: []
16580
17173
  };
16581
- const inPlace = (fromField, toField) => fromField.kind === "referenceTwoWay" && toField.kind === "referenceTwoWay" ? pairs.inPlace.has(sideKey(parent, toField.apiId)) : changesInPlace(fromField, toField);
17174
+ const inPlace = (fromField, toField) => fromField.kind === "referenceTwoWay" && toField.kind === "referenceTwoWay" ? pairs.inPlace.has(sideKey(parent, toField.apiId)) : fromField.kind === "referenceUnion" && toField.kind === "referenceUnion" || fromField.kind === "referenceUnionMember" && toField.kind === "referenceUnionMember" ? unions.inPlace.has(sideKey(parent, toField.apiId)) : changesInPlace(fromField, toField);
16582
17175
  const cascaded = /* @__PURE__ */ new Set();
17176
+ const dropped = /* @__PURE__ */ new Set();
16583
17177
  for (const field of Object.values(fromFields).toSorted(byApiId$1)) {
16584
17178
  const toField = to.fields[field.apiId];
16585
17179
  if (!toField || !inPlace(field, toField)) {
16586
17180
  const key = sideKey(parent, field.apiId);
16587
- if (pairs.cascaded.has(key)) {
17181
+ if (pairs.cascaded.has(key) || unions.cascaded.has(key)) {
16588
17182
  cascaded.add(field.apiId);
16589
17183
  continue;
16590
17184
  }
17185
+ if (unions.dropped.has(key)) {
17186
+ dropped.add(field.apiId);
17187
+ continue;
17188
+ }
16591
17189
  const partner = pairs.deletedPartners.get(key);
17190
+ const members = unions.deletedMembers.get(key);
16592
17191
  changes.deletes.push({
16593
17192
  action: "delete",
16594
17193
  resource: "field",
16595
17194
  parent,
16596
17195
  apiId: field.apiId,
16597
- ...partner ? { partner } : {}
17196
+ ...partner ? { partner } : {},
17197
+ ...members ? { members } : {}
16598
17198
  });
16599
17199
  }
16600
17200
  }
@@ -16615,20 +17215,34 @@ function diffFields(from, to, migrationValues = /* @__PURE__ */ new Map(), pairs
16615
17215
  if (settings) changes.conditions.push(settings);
16616
17216
  continue;
16617
17217
  }
17218
+ const made = unions.madeMembers.get(key);
17219
+ if (made !== void 0) {
17220
+ const settings = memberSettings(parent, field, made);
17221
+ if (settings) changes.conditions.push(settings);
17222
+ continue;
17223
+ }
16618
17224
  const migrationValue = migrationValues.get(field.apiId);
16619
17225
  const partner = pairs.createdPartners.get(key);
17226
+ const members = unions.createdMembers.get(key);
17227
+ const memberName = unions.memberNames.get(key);
16620
17228
  changes.creates.push({
16621
17229
  action: "create",
16622
17230
  resource: "field",
16623
17231
  parent,
16624
17232
  field,
16625
17233
  ...field.required && migrationValue !== void 0 ? { migrationValue } : {},
16626
- ...partner ? { partner } : {}
17234
+ ...partner ? { partner } : {},
17235
+ ...members ? { members } : {},
17236
+ ...memberName === void 0 ? {} : { memberName }
16627
17237
  });
16628
17238
  } else stays.push([fromField, field]);
16629
17239
  }
16630
17240
  changes.creates = basesFirst(changes.creates);
16631
- const afterDeletes = changes.deletes.length === 0 ? null : positionsAfterDeletes(fromFields, /* @__PURE__ */ new Set([...changes.deletes.map((change) => change.apiId), ...cascaded]));
17241
+ const afterDeletes = changes.deletes.length === 0 && dropped.size === 0 && !unions.renumbered.has(parent) ? null : positionsAfterDeletes(fromFields, /* @__PURE__ */ new Set([
17242
+ ...changes.deletes.map((change) => change.apiId),
17243
+ ...cascaded,
17244
+ ...dropped
17245
+ ]));
16632
17246
  for (const [fromField, field] of stays) {
16633
17247
  const attributes = diffField(afterDeletes === null ? fromField : {
16634
17248
  ...fromField,
@@ -16642,6 +17256,23 @@ function diffFields(from, to, migrationValues = /* @__PURE__ */ new Map(), pairs
16642
17256
  kind: field.kind,
16643
17257
  changes: fieldChanges
16644
17258
  });
17259
+ const models = attributes.to;
17260
+ if (models) {
17261
+ delete attributes.to;
17262
+ const positions = unions.memberPositions.get(sideKey(parent, field.apiId)) ?? {};
17263
+ const kept = models.to.filter((model) => models.from.includes(model));
17264
+ if (kept.length < models.from.length) changes.memberDrops.push(update({ to: {
17265
+ from: models.from,
17266
+ to: kept
17267
+ } }));
17268
+ if (kept.length < models.to.length) changes.memberAdds.push({
17269
+ ...update({ to: {
17270
+ from: kept,
17271
+ to: models.to
17272
+ } }),
17273
+ memberPositions: Object.fromEntries(Object.entries(positions).filter(([model]) => !kept.includes(model)))
17274
+ });
17275
+ }
16645
17276
  const base = field.visibilityCondition?.baseField;
16646
17277
  if (base !== void 0 && created.has(base)) {
16647
17278
  delete attributes.visibilityCondition;
@@ -16691,6 +17322,38 @@ function partnerSettings(parent, field) {
16691
17322
  };
16692
17323
  }
16693
17324
  /**
17325
+ * The settings a union member gets once its union's create or update made
17326
+ * it at its position: what differs from what the server gave it, and its
17327
+ * condition. `null` when nothing differs.
17328
+ */
17329
+ function memberSettings(parent, field, made) {
17330
+ const changes = {};
17331
+ if (made.named || made.displayName !== field.displayName) changes.displayName = {
17332
+ from: made.displayName,
17333
+ to: field.displayName
17334
+ };
17335
+ if (made.named || made.description !== field.description) changes.description = {
17336
+ from: made.description,
17337
+ to: field.description
17338
+ };
17339
+ if (made.visibility !== field.visibility) changes.visibility = {
17340
+ from: made.visibility,
17341
+ to: field.visibility
17342
+ };
17343
+ if (field.visibilityCondition !== null) changes.visibilityCondition = {
17344
+ from: null,
17345
+ to: field.visibilityCondition
17346
+ };
17347
+ return Object.keys(changes).length === 0 ? null : {
17348
+ action: "update",
17349
+ resource: "field",
17350
+ parent,
17351
+ apiId: field.apiId,
17352
+ kind: field.kind,
17353
+ changes
17354
+ };
17355
+ }
17356
+ /**
16694
17357
  * The move an unsupported field needs, if any: the only change the plan makes to
16695
17358
  * one. Compared like any field's position, after the plan's deletes.
16696
17359
  */
@@ -16824,6 +17487,10 @@ function diffField(from, to) {
16824
17487
  to: to.actions
16825
17488
  };
16826
17489
  }
17490
+ if (from.kind === "referenceUnion" && to.kind === "referenceUnion" && hashJSON(from.to) !== hashJSON(to.to)) changes.to = {
17491
+ from: from.to,
17492
+ to: to.to
17493
+ };
16827
17494
  if ("rules" in from && "rules" in to && hashJSON(from.rules) !== hashJSON(to.rules)) changes.rules = {
16828
17495
  from: from.rules,
16829
17496
  to: to.rules
@@ -17150,17 +17817,21 @@ function parentsFirst(nodes) {
17150
17817
  * node renames, component renames, model renames, then field renames,
17151
17818
  * so that everything after them uses the new names;
17152
17819
  * 2. field deletes, the updates of rich text that drops a model the plan
17153
- * deletes (see `orderEmbeds`), model deletes, value deletes,
17154
- * enumeration deletes,
17155
- * taxonomy deletes, locale deletes, then stage deletes, which free the
17156
- * names a create may claim. A two-way pair has one delete, from the side
17820
+ * deletes (see `orderEmbeds`), model deletes, value deletes, enumeration
17821
+ * deletes, taxonomy deletes, locale deletes, then stage deletes, which
17822
+ * free the names a create may claim. A two-way pair has one delete, from the side
17157
17823
  * on the lower model, so the side it takes along is gone before that
17158
- * model's own deletes renumber it. A deleted model's or component's
17159
- * fields go with it and are not listed, except a deleted component's
17160
- * fields that use another deleted component, and a deleted enumeration's
17161
- * values and a deleted taxonomy's nodes go with it. Deleting an
17162
- * enumeration or a taxonomy deletes the fields that use it, so it waits
17163
- * for the field deletes;
17824
+ * model's own deletes renumber it. A union's delete, which takes its
17825
+ * members along, comes before every other field delete for the same
17826
+ * reason, and is sent even when its model goes, if a member's model
17827
+ * stays. The union updates that drop models follow the field deletes:
17828
+ * the server deletes the dropped members, which renumbers their models
17829
+ * before any move. A deleted model's or component's fields go with it
17830
+ * and are not listed, except a deleted component's fields that use
17831
+ * another deleted component, and a deleted enumeration's values and a
17832
+ * deleted taxonomy's nodes go with it. Deleting an enumeration or a
17833
+ * taxonomy deletes the fields that use it, so it waits for the field
17834
+ * deletes;
17164
17835
  * 3. locale updates, locale creates, then the update that makes a created
17165
17836
  * locale the default, so that every locale exists before the fields
17166
17837
  * localized into it. Then stage updates, stage creates, and the moves
@@ -17179,8 +17850,10 @@ function parentsFirst(nodes) {
17179
17850
  * updates that drop them;
17180
17851
  * 7. model creates, then field creates, so a new field's parent exists. A
17181
17852
  * base field is created before the fields whose condition names it;
17853
+ * then the union updates that add models, which may be new;
17182
17854
  * 8. conditions that name a field created in step 7, on fields that stay,
17183
- * and the updates of rich text that embeds a model created in step 7.
17855
+ * the settings of the members a union's create or update made, and the
17856
+ * updates of rich text that embeds a model created in step 7.
17184
17857
  *
17185
17858
  * Locales, stages, enumerations, taxonomies, components and models follow
17186
17859
  * apiId order within each step, but stage creates and moves follow the
@@ -17193,10 +17866,14 @@ function diffEnvironment({ from, to, intents = {
17193
17866
  valueRenames: [],
17194
17867
  nodeRenames: [],
17195
17868
  migrationValues: []
17196
- }, unsupportedPairs = [] }) {
17869
+ }, unsupportedPairs = [], unsupportedUnions = [] }) {
17197
17870
  const { renamed, renames } = applyRenames(from, intents);
17198
17871
  const renameParent = followModelRenames(from, intents);
17199
17872
  const pairs = pairTwoWayReferences(renamed, to, unsupportedPairs.map(([a, b]) => [renameParent(a), renameParent(b)]));
17873
+ const unions = groupUnionReferences(renamed, to, unsupportedUnions.map(({ owner, members }) => ({
17874
+ owner: renameParent(owner),
17875
+ members: members.map(renameParent)
17876
+ })));
17200
17877
  const fromModels = new Map(renamed.models.map((model) => [model.apiId, model]));
17201
17878
  const toApiIds = new Set(to.models.map((model) => model.apiId));
17202
17879
  const modelDeletes = renamed.models.filter((model) => !toApiIds.has(model.apiId)).map((model) => ({
@@ -17204,15 +17881,26 @@ function diffEnvironment({ from, to, intents = {
17204
17881
  resource: "model",
17205
17882
  apiId: model.apiId
17206
17883
  }));
17884
+ const unionDeletes = unions.orphans.map(({ owner, members }) => ({
17885
+ action: "delete",
17886
+ resource: "field",
17887
+ parent: owner.parent,
17888
+ apiId: owner.apiId,
17889
+ members
17890
+ }));
17207
17891
  const fieldDeletes = [];
17208
17892
  const fieldUpdates = [];
17209
17893
  const fieldCreates = [];
17894
+ const memberDrops = [];
17895
+ const memberAdds = [];
17210
17896
  const fieldConditions = [];
17211
17897
  const pushFields = (fromParent, parent) => {
17212
- const fields = diffFields(fromParent, parent, new Map(intents.migrationValues.filter((migration) => migration.parent === parent.apiId).map((migration) => [migration.apiId, migration.value])), pairs);
17213
- fieldDeletes.push(...fields.deletes);
17898
+ const fields = diffFields(fromParent, parent, new Map(intents.migrationValues.filter((migration) => migration.parent === parent.apiId).map((migration) => [migration.apiId, migration.value])), pairs, unions);
17899
+ for (const fieldDelete of fields.deletes) (fieldDelete.members ? unionDeletes : fieldDeletes).push(fieldDelete);
17214
17900
  fieldUpdates.push(...fields.updates);
17215
17901
  fieldCreates.push(...fields.creates);
17902
+ memberDrops.push(...fields.memberDrops);
17903
+ memberAdds.push(...fields.memberAdds);
17216
17904
  fieldConditions.push(...fields.conditions);
17217
17905
  };
17218
17906
  const modelUpdates = [];
@@ -17273,7 +17961,9 @@ function diffEnvironment({ from, to, intents = {
17273
17961
  const embeds = orderEmbeds(fieldUpdates, new Set(modelDeletes.flatMap((change) => change.resource === "model" && change.action === "delete" ? [change.apiId] : [])), new Set(to.models.filter((model) => !fromModels.has(model.apiId)).map((model) => model.apiId)));
17274
17962
  return [
17275
17963
  ...renames,
17964
+ ...unionDeletes,
17276
17965
  ...fieldDeletes,
17966
+ ...memberDrops,
17277
17967
  ...embeds.beforeModelDeletes,
17278
17968
  ...modelDeletes,
17279
17969
  ...enumerations.valueDeletes,
@@ -17303,6 +17993,7 @@ function diffEnvironment({ from, to, intents = {
17303
17993
  ...componentDeletes,
17304
17994
  ...modelCreates,
17305
17995
  ...fieldCreates,
17996
+ ...memberAdds,
17306
17997
  ...fieldConditions,
17307
17998
  ...embeds.afterModelCreates
17308
17999
  ];
@@ -17672,15 +18363,23 @@ function applyModelRenames(from, intents) {
17672
18363
  }));
17673
18364
  const rename = (apiId) => newApiIds.get(apiId) ?? apiId;
17674
18365
  const parents = mapFields(from, (field) => {
17675
- if (field.kind === "referenceOneWay" || field.kind === "referenceTwoWay") return {
17676
- ...field,
17677
- to: rename(field.to)
17678
- };
17679
- if (field.kind === "richText" && field.embeds !== null) return {
17680
- ...field,
17681
- embeds: field.embeds.map(rename).toSorted()
17682
- };
17683
- return field;
18366
+ switch (field.kind) {
18367
+ case "referenceOneWay":
18368
+ case "referenceTwoWay":
18369
+ case "referenceUnionMember": return {
18370
+ ...field,
18371
+ to: rename(field.to)
18372
+ };
18373
+ case "referenceUnion": return {
18374
+ ...field,
18375
+ to: field.to.map(rename).toSorted()
18376
+ };
18377
+ case "richText": return field.embeds === null ? field : {
18378
+ ...field,
18379
+ embeds: field.embeds.map(rename).toSorted()
18380
+ };
18381
+ default: return field;
18382
+ }
17684
18383
  });
17685
18384
  const models = parents.models.map((model) => ({
17686
18385
  ...model,
@@ -17705,8 +18404,9 @@ function applyModelRenames(from, intents) {
17705
18404
  function applyFieldRenames(from, intents) {
17706
18405
  const renames = [];
17707
18406
  const renamedSides = /* @__PURE__ */ new Map();
18407
+ const allRenames = [...intents.fieldRenames, ...memberRenames(from, intents.fieldRenames)];
17708
18408
  const renameFields = (parent) => {
17709
- const fieldRenames = intents.fieldRenames.filter((rename) => rename.parent === parent.apiId && parent.fields[rename.renamedFrom] !== void 0 && parent.fields[rename.apiId] === void 0);
18409
+ const fieldRenames = allRenames.filter((rename) => rename.parent === parent.apiId && parent.fields[rename.renamedFrom] !== void 0 && parent.fields[rename.apiId] === void 0);
17710
18410
  if (fieldRenames.length === 0) return parent;
17711
18411
  const fields = { ...parent.fields };
17712
18412
  for (const rename of fieldRenames) {
@@ -17754,11 +18454,25 @@ function applyFieldRenames(from, intents) {
17754
18454
  components: from.components.map(renameFields)
17755
18455
  };
17756
18456
  const parents = mapFields(renamed, (field) => {
17757
- const apiId = field.kind === "referenceTwoWay" ? renamedSides.get(sideKey(field.to, field.reverse)) : void 0;
17758
- return field.kind === "referenceTwoWay" && apiId ? {
17759
- ...field,
17760
- reverse: apiId
17761
- } : field;
18457
+ switch (field.kind) {
18458
+ case "referenceTwoWay":
18459
+ case "referenceUnionMember": {
18460
+ const apiId = renamedSides.get(sideKey(field.to, field.reverse));
18461
+ return apiId ? {
18462
+ ...field,
18463
+ reverse: apiId
18464
+ } : field;
18465
+ }
18466
+ case "referenceUnion": {
18467
+ const { reverse } = field;
18468
+ const apiId = reverse === null ? void 0 : field.to.map((model) => renamedSides.get(sideKey(model, reverse))).find((each) => each !== void 0);
18469
+ return apiId ? {
18470
+ ...field,
18471
+ reverse: apiId
18472
+ } : field;
18473
+ }
18474
+ default: return field;
18475
+ }
17762
18476
  });
17763
18477
  return {
17764
18478
  renamed: {
@@ -17768,6 +18482,29 @@ function applyFieldRenames(from, intents) {
17768
18482
  renames
17769
18483
  };
17770
18484
  }
18485
+ /**
18486
+ * A union's members share their apiId, and the server renames each on its
18487
+ * own: renaming one member renames the union's other members too, those
18488
+ * the config renames as well included once.
18489
+ */
18490
+ function memberRenames(from, renames) {
18491
+ const parents = new Map([...from.models, ...from.components].map((parent) => [parent.apiId, parent]));
18492
+ const added = /* @__PURE__ */ new Map();
18493
+ for (const rename of renames) {
18494
+ const member = parents.get(rename.parent)?.fields[rename.renamedFrom];
18495
+ if (member?.kind !== "referenceUnionMember") continue;
18496
+ const union = parents.get(member.to)?.fields[member.reverse];
18497
+ if (union?.kind !== "referenceUnion") continue;
18498
+ for (const model of union.to) {
18499
+ const key = sideKey(model, rename.renamedFrom);
18500
+ if (!added.has(key) && !renames.some((each) => each.parent === model && each.renamedFrom === rename.renamedFrom)) added.set(key, {
18501
+ ...rename,
18502
+ parent: model
18503
+ });
18504
+ }
18505
+ }
18506
+ return [...added.values()];
18507
+ }
17771
18508
  /** The enumeration changes that take `from` to `to`, grouped by step. */
17772
18509
  function diffEnumerations(from, to) {
17773
18510
  const fromEnumerations = new Map(from.enumerations.map((enumeration) => [enumeration.apiId, enumeration]));
@@ -17966,6 +18703,30 @@ function validateFieldIntents(from, to, intents) {
17966
18703
  fix: fixes[code]
17967
18704
  });
17968
18705
  }
18706
+ const liveModels = new Map(from.models.map((model) => [model.apiId, model]));
18707
+ for (const rename of intents.fieldRenames) {
18708
+ const member = liveParent(from, intents, rename.parent)?.fields[rename.renamedFrom];
18709
+ const union = member?.kind === "referenceUnionMember" ? liveModels.get(member.to)?.fields[member.reverse] : void 0;
18710
+ if (union?.kind !== "referenceUnion") continue;
18711
+ for (const model of union.to) {
18712
+ const fields = liveModels.get(model)?.fields ?? {};
18713
+ if (fields[rename.renamedFrom]?.kind !== "referenceUnionMember" || fields[rename.apiId] === void 0 || intents.fieldRenames.some((each) => liveParent(from, intents, each.parent) === liveModels.get(model) && each.renamedFrom === rename.renamedFrom)) continue;
18714
+ const code = "change.fieldRenameBothInUse";
18715
+ validations.push({
18716
+ code,
18717
+ severity: "error",
18718
+ path: [
18719
+ "models",
18720
+ model,
18721
+ "fields",
18722
+ rename.apiId,
18723
+ "renamedFrom"
18724
+ ],
18725
+ message: messages[code]("model", model, rename.renamedFrom, rename.apiId),
18726
+ fix: fixes[code]
18727
+ });
18728
+ }
18729
+ }
17969
18730
  return validations;
17970
18731
  }
17971
18732
  /**
@@ -18062,9 +18823,11 @@ function validateTaxonomyIntents(from, intents) {
18062
18823
  * Whether every unsupported field in the config is live with the same
18063
18824
  * type. The plan cannot create one, and one of another type is another
18064
18825
  * field, so either stops the plan. A side of an unsupported two-way pair
18065
- * is kept only with its partner: Hygraph deletes the two together.
18826
+ * is kept only with its partner: Hygraph deletes the two together. A
18827
+ * member of an unsupported union is kept only with its union, and a union
18828
+ * only with a member.
18066
18829
  */
18067
- function validateUnsupportedFields({ from, to, intents, unsupportedPairs = [] }) {
18830
+ function validateUnsupportedFields({ from, to, intents, unsupportedPairs = [], unsupportedUnions = [] }) {
18068
18831
  const validations = [];
18069
18832
  const parents = [...to.models.map((parent) => ({
18070
18833
  kind: "model",
@@ -18129,6 +18892,40 @@ function validateUnsupportedFields({ from, to, intents, unsupportedPairs = [] })
18129
18892
  fix: fixes[code]
18130
18893
  });
18131
18894
  }
18895
+ for (const { owner, members } of unsupportedUnions) {
18896
+ const union = kept(owner);
18897
+ const keptMembers = members.map(kept).filter((member) => member.unsupported);
18898
+ if (!union.unsupported) for (const member of keptMembers) {
18899
+ const code = "change.unsupportedUnionDeleted";
18900
+ validations.push({
18901
+ code,
18902
+ severity: "error",
18903
+ path: [
18904
+ "models",
18905
+ member.model,
18906
+ "fields",
18907
+ member.apiId
18908
+ ],
18909
+ message: messages[code](member.model, member.apiId, union.model, union.apiId),
18910
+ fix: fixes[code]
18911
+ });
18912
+ }
18913
+ else if (keptMembers.length === 0) {
18914
+ const code = "change.unsupportedUnionEmptied";
18915
+ validations.push({
18916
+ code,
18917
+ severity: "error",
18918
+ path: [
18919
+ "models",
18920
+ union.model,
18921
+ "fields",
18922
+ union.apiId
18923
+ ],
18924
+ message: messages[code](union.model, union.apiId),
18925
+ fix: fixes[code]
18926
+ });
18927
+ }
18928
+ }
18132
18929
  return validations;
18133
18930
  }
18134
18931
  /**
@@ -18331,14 +19128,14 @@ function validateChangeSet({ from, changes }) {
18331
19128
  for (const apiId of embedded.filter((each) => !models.has(each))) report("change.modelMissing", path, `${change.action} a field that embeds`, apiId);
18332
19129
  }
18333
19130
  function validateModelReferenced(change) {
18334
- if (change.action !== "create" || change.field.kind !== "referenceOneWay" && change.field.kind !== "referenceTwoWay" || models.has(change.field.to)) return;
19131
+ const referenced = change.action === "create" ? change.field.kind === "referenceOneWay" || change.field.kind === "referenceTwoWay" ? [change.field.to] : change.field.kind === "referenceUnion" ? change.field.to : [] : change.action === "update" && change.kind === "referenceUnion" ? change.changes.to?.to ?? [] : [];
18335
19132
  const kind = componentApiIds.has(change.parent) ? "components" : "models";
18336
- report("change.modelMissing", [
19133
+ for (const apiId of referenced.filter((each) => !models.has(each))) report("change.modelMissing", [
18337
19134
  kind,
18338
19135
  change.parent,
18339
19136
  "fields",
18340
- change.field.apiId
18341
- ], "create a field that references", change.field.to);
19137
+ fieldApiIdOf(change)
19138
+ ], `${change.action} a field that references`, apiId);
18342
19139
  }
18343
19140
  function validateLocaleChange(change) {
18344
19141
  switch (change.action) {
@@ -18773,6 +19570,41 @@ const referenceTwoWayFieldSchema = strictObject({
18773
19570
  renamedFrom: string$1().nullable()
18774
19571
  });
18775
19572
  //#endregion
19573
+ //#region src/define/fields/referenceUnion.zod.ts
19574
+ const referenceUnionFieldSchema = strictObject({
19575
+ __typename: literal("ReferenceUnionField"),
19576
+ apiId: string$1(),
19577
+ displayName: string$1(),
19578
+ description: string$1().nullable(),
19579
+ to: array(custom((value) => typeof value === "function")),
19580
+ reverse: string$1().nullable(),
19581
+ list: boolean(),
19582
+ required: literal(false),
19583
+ rules: strictObject({ connections: strictObject({
19584
+ min: number().nullable(),
19585
+ max: number().nullable(),
19586
+ errorMessage: string$1().nullable()
19587
+ }) }).nullable(),
19588
+ visibility: fieldVisibilitySchema,
19589
+ visibilityCondition: visibilityConditionSchema.nullable(),
19590
+ renamedFrom: string$1().nullable()
19591
+ });
19592
+ //#endregion
19593
+ //#region src/define/fields/referenceUnionMember.zod.ts
19594
+ const referenceUnionMemberFieldSchema = strictObject({
19595
+ __typename: literal("ReferenceUnionMemberField"),
19596
+ apiId: string$1(),
19597
+ displayName: string$1(),
19598
+ description: string$1().nullable(),
19599
+ to: custom((value) => typeof value === "function"),
19600
+ reverse: string$1(),
19601
+ list: boolean(),
19602
+ required: literal(false),
19603
+ visibility: fieldVisibilitySchema,
19604
+ visibilityCondition: visibilityConditionSchema.nullable(),
19605
+ renamedFrom: string$1().nullable()
19606
+ });
19607
+ //#endregion
18776
19608
  //#region src/define/fields/string.zod.ts
18777
19609
  const regexRuleSchema = strictObject({
18778
19610
  regex: string$1(),
@@ -18888,6 +19720,8 @@ const fieldSchema = discriminatedUnion("__typename", [
18888
19720
  componentUnionFieldSchema,
18889
19721
  referenceOneWayFieldSchema,
18890
19722
  referenceTwoWayFieldSchema,
19723
+ referenceUnionFieldSchema,
19724
+ referenceUnionMemberFieldSchema,
18891
19725
  assetFieldSchema
18892
19726
  ]);
18893
19727
  //#endregion
@@ -19155,7 +19989,7 @@ async function computePlan(target, fetch) {
19155
19989
  maybeRefuse(configValidations, "the config has");
19156
19990
  const desired = convertEnvironmentToIR(target.apply);
19157
19991
  const intents = collectIntents(target.apply);
19158
- const { environmentId, environment: live, unsupportedPairs } = await readLiveEnvironment(target, fetch);
19992
+ const { environmentId, environment: live, unsupportedPairs, unsupportedUnions } = await readLiveEnvironment(target, fetch);
19159
19993
  maybeRefuse(validateIntents({
19160
19994
  from: live,
19161
19995
  to: desired,
@@ -19165,13 +19999,15 @@ async function computePlan(target, fetch) {
19165
19999
  from: live,
19166
20000
  to: desired,
19167
20001
  intents,
19168
- unsupportedPairs
20002
+ unsupportedPairs,
20003
+ unsupportedUnions
19169
20004
  }), `the unsupported fields do not match ${target.environment},`);
19170
20005
  const changes = diffEnvironment({
19171
20006
  from: live,
19172
20007
  to: desired,
19173
20008
  intents,
19174
- unsupportedPairs
20009
+ unsupportedPairs,
20010
+ unsupportedUnions
19175
20011
  });
19176
20012
  maybeRefuse(validateChangeSet({
19177
20013
  from: live,
@@ -19509,6 +20345,27 @@ function printField(field) {
19509
20345
  ["rules", printRules(field.rules)]
19510
20346
  ]);
19511
20347
  }
20348
+ case "referenceUnion": {
20349
+ const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `[${field.to.map((apiId) => `() => ${apiId}`).join(", ")}]`]);
20350
+ return printBuilder("referenceUnion", [
20351
+ apiId,
20352
+ displayName,
20353
+ to,
20354
+ ["reverse", field.reverse === null ? void 0 : string(field.reverse)],
20355
+ ...options,
20356
+ ["rules", printRules(field.rules)]
20357
+ ]);
20358
+ }
20359
+ case "referenceUnionMember": {
20360
+ const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${field.to}`]);
20361
+ return printBuilder("referenceUnionMember", [
20362
+ apiId,
20363
+ displayName,
20364
+ to,
20365
+ ["reverse", string(field.reverse)],
20366
+ ...options
20367
+ ]);
20368
+ }
19512
20369
  }
19513
20370
  }
19514
20371
  /** The builder that makes each text form renderer, with its defaults. */