@hygraph/cli 0.0.10 → 0.0.12

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
@@ -10,6 +10,7 @@ import { stripVTControlCharacters } from "node:util";
10
10
  import { createInterface } from "node:readline/promises";
11
11
  import { createHash } from "node:crypto";
12
12
  import { createJiti } from "jiti";
13
+ import { structuredPatch } from "diff";
13
14
  //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
14
15
  /**
15
16
  * CommanderError class
@@ -3222,11 +3223,16 @@ const SchemaDefinitionDocument = new TypedDocumentString(`
3222
3223
  apiId
3223
3224
  __typename
3224
3225
  }
3226
+ systemModels: models(includeSystemModels: true) {
3227
+ apiId
3228
+ __typename
3229
+ }
3225
3230
  models(includeSystemModels: false) {
3226
3231
  apiId
3227
3232
  fields(includeHiddenFields: true, includeApiOnlyFields: true) {
3228
3233
  apiId
3229
3234
  ... on RelationalField {
3235
+ isVariantEnabled
3230
3236
  relationalFieldRules {
3231
3237
  connections {
3232
3238
  min
@@ -3753,12 +3759,16 @@ function isRename(change) {
3753
3759
  * value or a node is counted too, although Hygraph refuses it while entries
3754
3760
  * hold the value or a node of the subtree. A union
3755
3761
  * update that drops a member deletes that member's content, a union
3756
- * reference's update that drops a model deletes that model's field back, and
3757
- * a rich text update that drops an embedded model deletes the embeds of its
3758
- * entries.
3762
+ * reference's update that drops a model deletes that model's field back, a
3763
+ * rich text update that drops an embedded model deletes the embeds of its
3764
+ * entries, and turning a field's variants off deletes its variant values.
3759
3765
  */
3760
3766
  function isDestructive(change) {
3761
- return change.action === "delete" || dropsUnionMember(change) || dropsEmbed(change);
3767
+ return change.action === "delete" || dropsUnionMember(change) || dropsEmbed(change) || dropsVariants(change);
3768
+ }
3769
+ /** A field update that turns variants off: Hygraph deletes its variant values. */
3770
+ function dropsVariants(change) {
3771
+ return change.resource === "field" && change.action === "update" && change.kind !== "unsupported" && change.changes.variantEnabled?.to === false;
3762
3772
  }
3763
3773
  /**
3764
3774
  * An asset field update that makes it required. It is not destructive, but
@@ -5774,6 +5784,7 @@ function createSimpleField({ parent, migrationValue }, field) {
5774
5784
  isTitle: field.title,
5775
5785
  visibility: field.visibility,
5776
5786
  visibilityCondition: field.visibilityCondition,
5787
+ isVariantEnabled: field.variantEnabled,
5777
5788
  initialValue: jsonValue(field.initialValue),
5778
5789
  position: field.position
5779
5790
  };
@@ -5793,7 +5804,7 @@ function createSimpleField({ parent, migrationValue }, field) {
5793
5804
  }
5794
5805
  /** Only the attributes that change are sent. A rename is `newApiId`. */
5795
5806
  function updateSimpleField(change) {
5796
- const { apiId, formRenderer, displayName, description, required, unique, localized, title, visibility, visibilityCondition, initialValue, position, validations, slug, embeds, actions } = change.changes;
5807
+ const { apiId, formRenderer, displayName, description, required, unique, localized, title, visibility, visibilityCondition, variantEnabled, initialValue, position, validations, slug, embeds, actions } = change.changes;
5797
5808
  const input = {
5798
5809
  apiId: change.apiId,
5799
5810
  parentApiId: change.parent
@@ -5811,6 +5822,7 @@ function updateSimpleField(change) {
5811
5822
  if (title) input.isTitle = title.to;
5812
5823
  if (visibility) input.visibility = visibility.to;
5813
5824
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
5825
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5814
5826
  if (initialValue) input.initialValue = jsonValue(initialValue.to);
5815
5827
  if (position) input.position = position.to;
5816
5828
  if (validations) input.validations = validations.to === null ? null : validationsInput(change.kind, validations.to);
@@ -5840,6 +5852,7 @@ function createEnumerableField({ parent, migrationValue }, field) {
5840
5852
  isTitle: field.title,
5841
5853
  visibility: field.visibility,
5842
5854
  visibilityCondition: field.visibilityCondition,
5855
+ isVariantEnabled: field.variantEnabled,
5843
5856
  initialValue: jsonValue(field.initialValue),
5844
5857
  position: field.position
5845
5858
  };
@@ -5852,7 +5865,7 @@ function createEnumerableField({ parent, migrationValue }, field) {
5852
5865
  * creates the field instead.
5853
5866
  */
5854
5867
  function updateEnumerableField(change) {
5855
- const { apiId, displayName, description, required, unique, title, visibility, visibilityCondition, initialValue, position } = change.changes;
5868
+ const { apiId, displayName, description, required, unique, title, visibility, visibilityCondition, variantEnabled, initialValue, position } = change.changes;
5856
5869
  const input = {
5857
5870
  apiId: change.apiId,
5858
5871
  parentApiId: change.parent
@@ -5865,6 +5878,7 @@ function updateEnumerableField(change) {
5865
5878
  if (title) input.isTitle = title.to;
5866
5879
  if (visibility) input.visibility = visibility.to;
5867
5880
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
5881
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5868
5882
  if (initialValue) input.initialValue = jsonValue(initialValue.to);
5869
5883
  if (position) input.position = position.to;
5870
5884
  if (change.migrationValue !== void 0) input.migrationValue = enumerationMigrationValue(change.migrationValue);
@@ -5890,6 +5904,7 @@ function createTaxonomyField({ parent, migrationValue }, field) {
5890
5904
  isUnique: field.unique,
5891
5905
  visibility: field.visibility,
5892
5906
  visibilityCondition: field.visibilityCondition,
5907
+ isVariantEnabled: field.variantEnabled,
5893
5908
  initialValue: jsonValue(field.initialValue),
5894
5909
  position: field.position
5895
5910
  };
@@ -5902,7 +5917,7 @@ function createTaxonomyField({ parent, migrationValue }, field) {
5902
5917
  * instead.
5903
5918
  */
5904
5919
  function updateTaxonomyField(change) {
5905
- const { apiId, displayName, description, required, unique, visibility, visibilityCondition, initialValue, position } = change.changes;
5920
+ const { apiId, displayName, description, required, unique, visibility, visibilityCondition, variantEnabled, initialValue, position } = change.changes;
5906
5921
  const input = {
5907
5922
  apiId: change.apiId,
5908
5923
  parentApiId: change.parent
@@ -5914,6 +5929,7 @@ function updateTaxonomyField(change) {
5914
5929
  if (unique) input.isUnique = unique.to;
5915
5930
  if (visibility) input.visibility = visibility.to;
5916
5931
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
5932
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5917
5933
  if (initialValue) input.initialValue = jsonValue(initialValue.to);
5918
5934
  if (position) input.position = position.to;
5919
5935
  if (change.migrationValue !== void 0) input.migrationValue = taxonomyMigrationValue(change.migrationValue);
@@ -5938,6 +5954,7 @@ function createComponentField({ parent }, field) {
5938
5954
  isRequired: field.required,
5939
5955
  visibility: field.visibility,
5940
5956
  visibilityCondition: field.visibilityCondition,
5957
+ isVariantEnabled: field.variantEnabled,
5941
5958
  position: field.position
5942
5959
  };
5943
5960
  }
@@ -5947,7 +5964,7 @@ function createComponentField({ parent }, field) {
5947
5964
  * field instead.
5948
5965
  */
5949
5966
  function updateComponentField(change) {
5950
- const { apiId, displayName, description, required, visibility, visibilityCondition, position } = change.changes;
5967
+ const { apiId, displayName, description, required, visibility, visibilityCondition, variantEnabled, position } = change.changes;
5951
5968
  const input = {
5952
5969
  apiId: change.apiId,
5953
5970
  parentApiId: change.parent
@@ -5958,6 +5975,7 @@ function updateComponentField(change) {
5958
5975
  if (required) input.isRequired = required.to;
5959
5976
  if (visibility) input.visibility = visibility.to;
5960
5977
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
5978
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5961
5979
  if (position) input.position = position.to;
5962
5980
  return input;
5963
5981
  }
@@ -5972,6 +5990,7 @@ function createComponentUnionField({ parent }, field) {
5972
5990
  isList: field.list,
5973
5991
  visibility: field.visibility,
5974
5992
  visibilityCondition: field.visibilityCondition,
5993
+ isVariantEnabled: field.variantEnabled,
5975
5994
  position: field.position
5976
5995
  };
5977
5996
  }
@@ -5982,7 +6001,7 @@ function createComponentUnionField({ parent }, field) {
5982
6001
  * instead.
5983
6002
  */
5984
6003
  function updateComponentUnionField(change) {
5985
- const { apiId, displayName, description, components, visibilityCondition, position } = change.changes;
6004
+ const { apiId, displayName, description, components, visibilityCondition, variantEnabled, position } = change.changes;
5986
6005
  const input = {
5987
6006
  apiId: change.apiId,
5988
6007
  parentApiId: change.parent
@@ -5992,6 +6011,7 @@ function updateComponentUnionField(change) {
5992
6011
  if (description) input.description = description.to;
5993
6012
  if (components) input.componentApiIds = components.to;
5994
6013
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
6014
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5995
6015
  if (position) input.position = position.to;
5996
6016
  return input;
5997
6017
  }
@@ -6024,6 +6044,7 @@ function createReferenceOneWayField({ parent }, field) {
6024
6044
  isList: field.list,
6025
6045
  visibility: field.visibility,
6026
6046
  visibilityCondition: field.visibilityCondition,
6047
+ isVariantEnabled: field.variantEnabled,
6027
6048
  relationalFieldRules: field.rules,
6028
6049
  position: field.position,
6029
6050
  reverseField: {
@@ -6053,6 +6074,7 @@ function createReferenceTwoWayField({ parent, partner }, field) {
6053
6074
  isList: field.list,
6054
6075
  visibility: field.visibility,
6055
6076
  visibilityCondition: field.visibilityCondition,
6077
+ isVariantEnabled: field.variantEnabled,
6056
6078
  relationalFieldRules: field.rules,
6057
6079
  position: field.position,
6058
6080
  reverseField: {
@@ -6087,6 +6109,7 @@ function createAssetField({ parent, partner }, field) {
6087
6109
  isRequired: field.required,
6088
6110
  visibility: field.visibility,
6089
6111
  visibilityCondition: field.visibilityCondition,
6112
+ isVariantEnabled: field.variantEnabled,
6090
6113
  position: field.position,
6091
6114
  reverseField: partner === void 0 ? {
6092
6115
  apiId: hidden,
@@ -6114,7 +6137,7 @@ function createAssetField({ parent, partner }, field) {
6114
6137
  * diff deletes and creates the field instead.
6115
6138
  */
6116
6139
  function updateRelationalField(change) {
6117
- const { apiId, displayName, description, required, visibility, visibilityCondition, position, rules } = change.changes;
6140
+ const { apiId, displayName, description, required, visibility, visibilityCondition, variantEnabled, position, rules } = change.changes;
6118
6141
  const input = {
6119
6142
  apiId: change.apiId,
6120
6143
  parentApiId: change.parent
@@ -6125,6 +6148,7 @@ function updateRelationalField(change) {
6125
6148
  if (required) input.isRequired = required.to;
6126
6149
  if (visibility) input.visibility = visibility.to;
6127
6150
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
6151
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
6128
6152
  if (position) input.position = position.to;
6129
6153
  if (rules) input.relationalFieldRules = rules.to;
6130
6154
  return input;
@@ -6156,6 +6180,7 @@ function createUnionField({ parent, members = [], memberName }, field) {
6156
6180
  isList: field.list,
6157
6181
  visibility: field.visibility,
6158
6182
  visibilityCondition: field.visibilityCondition,
6183
+ isVariantEnabled: field.variantEnabled,
6159
6184
  relationalFieldRules: field.rules,
6160
6185
  position: field.position,
6161
6186
  reverseField: first === void 0 ? { modelApiIds: field.to } : {
@@ -6179,7 +6204,7 @@ function createUnionField({ parent, members = [], memberName }, field) {
6179
6204
  * member's field only, a rename included.
6180
6205
  */
6181
6206
  function updateUnionField(change) {
6182
- const { apiId, displayName, description, visibility, visibilityCondition, position, rules, to } = change.changes;
6207
+ const { apiId, displayName, description, visibility, visibilityCondition, variantEnabled, position, rules, to } = change.changes;
6183
6208
  const input = {
6184
6209
  apiId: change.apiId,
6185
6210
  parentApiId: change.parent
@@ -6189,6 +6214,7 @@ function updateUnionField(change) {
6189
6214
  if (description) input.description = description.to;
6190
6215
  if (visibility) input.visibility = visibility.to;
6191
6216
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
6217
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
6192
6218
  if (position) input.position = position.to;
6193
6219
  if (rules) input.relationalFieldRules = rules.to;
6194
6220
  if (to) input.reverseField = {
@@ -6813,7 +6839,12 @@ function renderFieldChange(change, width, colors) {
6813
6839
  case "update": {
6814
6840
  if (unsupportedFieldMove(change)) return [` ${colors.yellow(`~ ${op}`)} ${subject} ${colors.dim(change.type)}`, ...renderAttributes(change.changes, colors)];
6815
6841
  const { apiId, headers, args, ...attributes } = change.changes;
6816
- const warning = dropsUnionMember(change) ? ` ${colors.yellow(`⚠ deletes the content of the members it drops`)}` : dropsEmbed(change) ? ` ${colors.yellow(`⚠ deletes the embeds of the models it drops`)}` : makesAssetRequired(change) ? ` ${colors.yellow(`⚠ API creates must set it; entries without an asset may fail to read`)}` : "";
6842
+ const warning = [
6843
+ dropsUnionMember(change) && "deletes the content of the members it drops",
6844
+ dropsEmbed(change) && "deletes the embeds of the models it drops",
6845
+ dropsVariants(change) && "deletes the field's variant values",
6846
+ makesAssetRequired(change) && "API creates must set it; entries without an asset may fail to read"
6847
+ ].filter((text) => text !== false).map((text) => ` ${colors.yellow(`⚠ ${text}`)}`).join("");
6817
6848
  const rows = Object.entries(attributes).flatMap(([attribute, each]) => each === void 0 ? [] : [changeRow(attribute, each)]);
6818
6849
  if (headers) rows.push(keyedChanges("headers", headerEntries(headers.from), headerEntries(headers.to)));
6819
6850
  if (args) rows.push(keyedChanges("args", args.from.map((arg) => [arg.apiId, JSON.stringify(arg)]), args.to.map((arg) => [arg.apiId, JSON.stringify(arg)])));
@@ -12854,6 +12885,7 @@ const colorFieldSchema = strictObject({
12854
12885
  title: literal(false),
12855
12886
  visibility: fieldVisibilitySchema,
12856
12887
  visibilityCondition: visibilityConditionSchema.nullable(),
12888
+ variantEnabled: boolean(),
12857
12889
  initialValue: colorValueSchema,
12858
12890
  migrationValue: colorValueSchema,
12859
12891
  renamedFrom: string$1().nullable()
@@ -12878,6 +12910,7 @@ const locationFieldSchema = strictObject({
12878
12910
  title: literal(false),
12879
12911
  visibility: fieldVisibilitySchema,
12880
12912
  visibilityCondition: visibilityConditionSchema.nullable(),
12913
+ variantEnabled: boolean(),
12881
12914
  initialValue: locationValueSchema,
12882
12915
  migrationValue: locationValueSchema,
12883
12916
  renamedFrom: string$1().nullable()
@@ -12899,6 +12932,7 @@ const richTextFieldSchema = strictObject({
12899
12932
  title: literal(false),
12900
12933
  visibility: fieldVisibilitySchema,
12901
12934
  visibilityCondition: visibilityConditionSchema.nullable(),
12935
+ variantEnabled: boolean(),
12902
12936
  initialValue: richTextValuesSchema,
12903
12937
  migrationValue: richTextValuesSchema,
12904
12938
  embeds: array(custom((value) => typeof value === "function")).nullable(),
@@ -13279,7 +13313,8 @@ const fieldAttributes = {
13279
13313
  list: boolean(),
13280
13314
  required: boolean(),
13281
13315
  visibility: fieldVisibilitySchema,
13282
- visibilityCondition: visibilityConditionSchema.nullable()
13316
+ visibilityCondition: visibilityConditionSchema.nullable(),
13317
+ variantEnabled: boolean()
13283
13318
  };
13284
13319
  const stringFormRendererSchema = _enum([
13285
13320
  "GCMS_SINGLE_LINE",
@@ -13306,7 +13341,8 @@ const referenceUnionMemberFieldSchema$1 = strictObject({
13306
13341
  kind: literal("referenceUnionMember"),
13307
13342
  to: string$1(),
13308
13343
  reverse: string$1(),
13309
- required: literal(false)
13344
+ required: literal(false),
13345
+ variantEnabled: literal(false)
13310
13346
  });
13311
13347
  const remoteFieldArgSchema = strictObject({
13312
13348
  apiId: string$1(),
@@ -13315,6 +13351,21 @@ const remoteFieldArgSchema = strictObject({
13315
13351
  list: boolean()
13316
13352
  });
13317
13353
  const remoteFieldMethodSchema = _enum(["GET", "POST"]);
13354
+ const dateAttributes = {
13355
+ ...fieldAttributes,
13356
+ unique: boolean(),
13357
+ localized: boolean(),
13358
+ title: boolean(),
13359
+ initialValue: union([string$1(), array(string$1())]).nullable()
13360
+ };
13361
+ const numberAttributes = {
13362
+ ...fieldAttributes,
13363
+ unique: boolean(),
13364
+ localized: boolean(),
13365
+ title: boolean(),
13366
+ initialValue: union([number(), array(number())]).nullable(),
13367
+ validations: numberValidationRulesSchema.nullable()
13368
+ };
13318
13369
  const fieldSchema$1 = discriminatedUnion("kind", [
13319
13370
  strictObject({
13320
13371
  ...fieldAttributes,
@@ -13336,12 +13387,12 @@ const fieldSchema$1 = discriminatedUnion("kind", [
13336
13387
  slug: slugSettingsSchema.nullable()
13337
13388
  }),
13338
13389
  strictObject({
13339
- ...fieldAttributes,
13340
- kind: _enum(["date", "dateTime"]),
13341
- unique: boolean(),
13342
- localized: boolean(),
13343
- title: boolean(),
13344
- initialValue: union([string$1(), array(string$1())]).nullable()
13390
+ ...dateAttributes,
13391
+ kind: literal("date")
13392
+ }),
13393
+ strictObject({
13394
+ ...dateAttributes,
13395
+ kind: literal("dateTime")
13345
13396
  }),
13346
13397
  strictObject({
13347
13398
  ...fieldAttributes,
@@ -13360,13 +13411,12 @@ const fieldSchema$1 = discriminatedUnion("kind", [
13360
13411
  initialValue: union([string$1(), array(string$1())]).nullable()
13361
13412
  }),
13362
13413
  strictObject({
13363
- ...fieldAttributes,
13364
- kind: _enum(["int", "float"]),
13365
- unique: boolean(),
13366
- localized: boolean(),
13367
- title: boolean(),
13368
- initialValue: union([number(), array(number())]).nullable(),
13369
- validations: numberValidationRulesSchema.nullable()
13414
+ ...numberAttributes,
13415
+ kind: literal("int")
13416
+ }),
13417
+ strictObject({
13418
+ ...numberAttributes,
13419
+ kind: literal("float")
13370
13420
  }),
13371
13421
  strictObject({
13372
13422
  ...fieldAttributes,
@@ -13448,7 +13498,8 @@ const fieldSchema$1 = discriminatedUnion("kind", [
13448
13498
  forwardClientHeaders: boolean(),
13449
13499
  cacheTTLSeconds: number(),
13450
13500
  args: array(remoteFieldArgSchema),
13451
- visibilityCondition: _null()
13501
+ visibilityCondition: _null(),
13502
+ variantEnabled: literal(false)
13452
13503
  })
13453
13504
  ]);
13454
13505
  const fieldRefSchema = strictObject({
@@ -13517,6 +13568,7 @@ const changeSchema = discriminatedUnion("resource", [
13517
13568
  title: attributeChangeSchema(boolean()),
13518
13569
  visibility: attributeChangeSchema(fieldVisibilitySchema),
13519
13570
  visibilityCondition: attributeChangeSchema(visibilityConditionSchema.nullable()),
13571
+ variantEnabled: attributeChangeSchema(boolean()),
13520
13572
  initialValue: attributeChangeSchema(initialValueSchema),
13521
13573
  position: attributeChangeSchema(number()),
13522
13574
  validations: attributeChangeSchema(union([stringValidationRulesSchema$1, numberValidationRulesSchema]).nullable()),
@@ -13728,6 +13780,7 @@ const simpleFieldShape = {
13728
13780
  isUnique: boolean().nullish(),
13729
13781
  isLocalized: boolean().nullish(),
13730
13782
  isTitle: boolean().nullish(),
13783
+ isVariantEnabled: boolean().nullish(),
13731
13784
  visibility: fieldVisibilitySchema.nullish(),
13732
13785
  initialValue: string$1().nullish(),
13733
13786
  position: number(),
@@ -13743,6 +13796,7 @@ const createReferenceFieldSchema = object$1({
13743
13796
  description: string$1().nullish(),
13744
13797
  isList: boolean().nullish(),
13745
13798
  isRequired: boolean().nullish(),
13799
+ isVariantEnabled: boolean().nullish(),
13746
13800
  visibility: fieldVisibilitySchema.nullish(),
13747
13801
  position: number(),
13748
13802
  visibilityCondition: liveVisibilityConditionSchema.nullish(),
@@ -13761,6 +13815,7 @@ const createReferenceTwoWayFieldSchema = object$1({
13761
13815
  description: string$1().nullish(),
13762
13816
  isList: boolean().nullish(),
13763
13817
  isRequired: boolean().nullish(),
13818
+ isVariantEnabled: boolean().nullish(),
13764
13819
  visibility: fieldVisibilitySchema.nullish(),
13765
13820
  position: number(),
13766
13821
  visibilityCondition: liveVisibilityConditionSchema.nullish(),
@@ -13880,6 +13935,7 @@ function convertCreateAssetFieldToIR(input, components) {
13880
13935
  required: field.isRequired ?? false,
13881
13936
  visibility: field.visibility ?? "READ_WRITE",
13882
13937
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
13938
+ variantEnabled: field.isVariantEnabled ?? false,
13883
13939
  ...!oneWay && { reverse: field.reverseField.apiId }
13884
13940
  }
13885
13941
  };
@@ -13899,7 +13955,8 @@ function convertCreateAssetFieldToIR(input, components) {
13899
13955
  list: back.isList ?? true,
13900
13956
  required: false,
13901
13957
  visibility: back.visibility ?? "READ_WRITE",
13902
- visibilityCondition: null
13958
+ visibilityCondition: null,
13959
+ variantEnabled: false
13903
13960
  }
13904
13961
  }];
13905
13962
  }
@@ -13936,6 +13993,7 @@ function convertCreateBooleanFieldToIR(input) {
13936
13993
  title: field.isTitle ?? false,
13937
13994
  visibility: field.visibility ?? "READ_WRITE",
13938
13995
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
13996
+ variantEnabled: field.isVariantEnabled ?? false,
13939
13997
  initialValue: parseValue({
13940
13998
  apiId: field.apiId,
13941
13999
  list
@@ -13980,6 +14038,7 @@ function convertCreateColorFieldToIR(input) {
13980
14038
  title: false,
13981
14039
  visibility: field.visibility ?? "READ_WRITE",
13982
14040
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14041
+ variantEnabled: field.isVariantEnabled ?? false,
13983
14042
  initialValue: parseValue({
13984
14043
  apiId: field.apiId,
13985
14044
  list
@@ -14022,6 +14081,7 @@ const baseShape = {
14022
14081
  displayName: string$1(),
14023
14082
  description: string$1().nullish(),
14024
14083
  isList: boolean().nullish(),
14084
+ isVariantEnabled: boolean().nullish(),
14025
14085
  visibility: fieldVisibilitySchema.nullish(),
14026
14086
  position: number(),
14027
14087
  visibilityCondition: liveVisibilityConditionSchema.nullish()
@@ -14075,7 +14135,8 @@ function attributes$3(field) {
14075
14135
  position: field.position,
14076
14136
  list: field.isList ?? false,
14077
14137
  visibility: field.visibility ?? "READ_WRITE",
14078
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
14138
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14139
+ variantEnabled: field.isVariantEnabled ?? false
14079
14140
  };
14080
14141
  }
14081
14142
  //#endregion
@@ -14111,6 +14172,7 @@ function convertCreateDateFieldToIR(input) {
14111
14172
  title: field.isTitle ?? false,
14112
14173
  visibility: field.visibility ?? "READ_WRITE",
14113
14174
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14175
+ variantEnabled: field.isVariantEnabled ?? false,
14114
14176
  initialValue: parseValue({
14115
14177
  apiId: field.apiId,
14116
14178
  list
@@ -14187,6 +14249,7 @@ function convertCreateEnumerableFieldToIR(input) {
14187
14249
  title: field.isTitle ?? false,
14188
14250
  visibility: field.visibility ?? "READ_WRITE",
14189
14251
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14252
+ variantEnabled: field.isVariantEnabled ?? false,
14190
14253
  initialValue: parseValue({
14191
14254
  apiId: field.apiId,
14192
14255
  list
@@ -14231,6 +14294,7 @@ function convertCreateJsonFieldToIR(input) {
14231
14294
  title: false,
14232
14295
  visibility: field.visibility ?? "READ_WRITE",
14233
14296
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14297
+ variantEnabled: field.isVariantEnabled ?? false,
14234
14298
  initialValue: parseValue({
14235
14299
  apiId: field.apiId,
14236
14300
  list
@@ -14275,6 +14339,7 @@ function convertCreateLocationFieldToIR(input) {
14275
14339
  title: false,
14276
14340
  visibility: field.visibility ?? "READ_WRITE",
14277
14341
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14342
+ variantEnabled: field.isVariantEnabled ?? false,
14278
14343
  initialValue: parseValue({
14279
14344
  apiId: field.apiId,
14280
14345
  list
@@ -14351,6 +14416,7 @@ function convertCreateNumberFieldToIR(input) {
14351
14416
  title: field.isTitle ?? false,
14352
14417
  visibility: field.visibility ?? "READ_WRITE",
14353
14418
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14419
+ variantEnabled: field.isVariantEnabled ?? false,
14354
14420
  initialValue: parseValue({
14355
14421
  apiId: field.apiId,
14356
14422
  list
@@ -14400,7 +14466,8 @@ function convertCreateReferenceOneWayFieldToIR(input, models) {
14400
14466
  list: field.isList ?? false,
14401
14467
  required: false,
14402
14468
  visibility: field.visibility ?? "READ_WRITE",
14403
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
14469
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14470
+ variantEnabled: field.isVariantEnabled ?? false
14404
14471
  }
14405
14472
  };
14406
14473
  }
@@ -14436,7 +14503,8 @@ function convertCreateReferenceTwoWayFieldToIR(input, models, partners) {
14436
14503
  list: field.isList ?? false,
14437
14504
  required: false,
14438
14505
  visibility: field.visibility ?? "READ_WRITE",
14439
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
14506
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14507
+ variantEnabled: field.isVariantEnabled ?? false
14440
14508
  }
14441
14509
  }, {
14442
14510
  parentApiId: reverse.modelApiId,
@@ -14452,7 +14520,8 @@ function convertCreateReferenceTwoWayFieldToIR(input, models, partners) {
14452
14520
  list: reverse.isList ?? false,
14453
14521
  required: false,
14454
14522
  visibility: reverse.visibility ?? "READ_WRITE",
14455
- visibilityCondition: convertVisibilityCondition(partner?.visibilityCondition)
14523
+ visibilityCondition: convertVisibilityCondition(partner?.visibilityCondition),
14524
+ variantEnabled: partner?.isVariantEnabled ?? false
14456
14525
  }
14457
14526
  }];
14458
14527
  }
@@ -14515,6 +14584,7 @@ function convertCreateRemoteFieldToIR(input) {
14515
14584
  required: field.isRequired ?? false,
14516
14585
  visibility: field.visibility ?? "READ_WRITE",
14517
14586
  visibilityCondition: null,
14587
+ variantEnabled: false,
14518
14588
  source: config.remoteSourcePrefix,
14519
14589
  type: field.type,
14520
14590
  returnType: config.returnTypeApiId,
@@ -14678,6 +14748,7 @@ function convertCreateRichTextFieldToIR(input, models) {
14678
14748
  title: false,
14679
14749
  visibility: field.visibility ?? "READ_WRITE",
14680
14750
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14751
+ variantEnabled: field.isVariantEnabled ?? false,
14681
14752
  initialValue: isEmptyRichText(initialValue) ? null : initialValue,
14682
14753
  embeds: field.embedsEnabled === true ? (field.embeddableModels ?? []).toSorted() : null,
14683
14754
  actions: richTextActions(field.formConfig?.actions ?? null)
@@ -14780,6 +14851,7 @@ function convertCreateStringFieldToIR(input) {
14780
14851
  title: field.isTitle ?? false,
14781
14852
  visibility: field.visibility ?? "READ_WRITE",
14782
14853
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14854
+ variantEnabled: field.isVariantEnabled ?? false,
14783
14855
  initialValue: parseValue({
14784
14856
  apiId: field.apiId,
14785
14857
  list
@@ -14895,6 +14967,7 @@ function convertCreateTaxonomyFieldToIR(input) {
14895
14967
  unique: field.isUnique ?? false,
14896
14968
  visibility: field.visibility ?? "READ_WRITE",
14897
14969
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14970
+ variantEnabled: field.isVariantEnabled ?? false,
14898
14971
  initialValue: parseValue({
14899
14972
  apiId: field.apiId,
14900
14973
  list
@@ -14914,6 +14987,7 @@ const createReferenceUnionFieldSchema = object$1({
14914
14987
  displayName: string$1(),
14915
14988
  description: string$1().nullish(),
14916
14989
  isList: boolean().nullish(),
14990
+ isVariantEnabled: boolean().nullish(),
14917
14991
  visibility: fieldVisibilitySchema.nullish(),
14918
14992
  position: number(),
14919
14993
  visibilityCondition: liveVisibilityConditionSchema.nullish(),
@@ -14983,7 +15057,8 @@ function convertCreateReferenceUnionFieldToIR(input, models, components, lookup)
14983
15057
  list: field.isList ?? false,
14984
15058
  required: false,
14985
15059
  visibility: field.visibility ?? "READ_WRITE",
14986
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
15060
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
15061
+ variantEnabled: field.isVariantEnabled ?? false
14987
15062
  }
14988
15063
  };
14989
15064
  if (!onModel) return [owner];
@@ -15006,7 +15081,8 @@ function convertCreateReferenceUnionFieldToIR(input, models, components, lookup)
15006
15081
  list: member.isList,
15007
15082
  required: false,
15008
15083
  visibility: member.visibility,
15009
- visibilityCondition: convertVisibilityCondition(member.visibilityCondition)
15084
+ visibilityCondition: convertVisibilityCondition(member.visibilityCondition),
15085
+ variantEnabled: false
15010
15086
  }
15011
15087
  });
15012
15088
  }
@@ -15199,9 +15275,11 @@ function parse$2(operation, schema, input) {
15199
15275
  * reference there; the other side of any other relation on Asset is an
15200
15276
  * unsupported field. Fields on QueryModel, remote fields only, go on
15201
15277
  * `query` the same way, which is there and exported with no fields too.
15202
- * Every other op, `createLocale` and `createStage`
15203
- * included, and fields on anything but a model, a component, Asset or
15204
- * QueryModel, are skipped until the IR has a place for them. A two-way
15278
+ * Fields on Segment go on `segment`, there only with fields: whether live
15279
+ * has Segment without them is `readLiveEnvironment`'s to say. Every other op,
15280
+ * `createLocale` and `createStage` included, and fields on anything but a
15281
+ * model, a component, Asset, QueryModel or Segment, are skipped until the
15282
+ * IR has a place for them. A two-way
15205
15283
  * relation's other side takes its rules and condition from `partners`,
15206
15284
  * which `schemaDefinition` leaves out, and a union's members
15207
15285
  * their apiIds and settings from `unions`: `schemaDefinition` gives the
@@ -15229,7 +15307,12 @@ function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map(),
15229
15307
  apiId: "QueryModel",
15230
15308
  fields: {}
15231
15309
  };
15310
+ const segment = {
15311
+ apiId: "Segment",
15312
+ fields: {}
15313
+ };
15232
15314
  const parents = new Map([
15315
+ [segment.apiId, segment],
15233
15316
  ...[...models, ...components].map((parent) => [parent.apiId, parent]),
15234
15317
  [asset.apiId, asset],
15235
15318
  [query.apiId, query]
@@ -15289,12 +15372,13 @@ function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map(),
15289
15372
  components: components.toSorted(byApiId$1),
15290
15373
  models: models.toSorted(byApiId$1),
15291
15374
  asset,
15292
- query
15375
+ query,
15376
+ ...Object.keys(segment.fields).length > 0 && { segment }
15293
15377
  };
15294
15378
  }
15295
15379
  /**
15296
- * Puts the field on its model, component, Asset or QueryModel. A field on
15297
- * anything else is skipped.
15380
+ * Puts the field on its model, component, Asset, QueryModel or Segment. A
15381
+ * field on anything else is skipped.
15298
15382
  */
15299
15383
  function addField(parents, live) {
15300
15384
  const parent = parents.get(live.parentApiId);
@@ -15388,7 +15472,7 @@ var LiveSchemaFailure = class extends Failure {};
15388
15472
  * locales and stages come from the same request's `contentModel`, and a
15389
15473
  * two-way relation's other side without its rules and condition, and a
15390
15474
  * union's members with the first one's settings, so they come from its
15391
- * `models`.
15475
+ * `models`. Whether Segment exists comes from its system models.
15392
15476
  */
15393
15477
  async function readLiveEnvironment(target, fetch) {
15394
15478
  if (isEmpty(target.token)) throw new LiveSchemaFailure(`target "${target.name}" has no token`);
@@ -15405,7 +15489,8 @@ async function readLiveEnvironment(target, fetch) {
15405
15489
  }
15406
15490
  const { environment } = extractProject(result.viewer, target);
15407
15491
  const unions = unionLookup(environment.contentModel.models);
15408
- const live = convertSchemaDefinitionToIR(environment.schemaDefinition, partnerLookup(environment.contentModel.models), unions);
15492
+ const { segment, ...live } = convertSchemaDefinitionToIR(environment.schemaDefinition, partnerLookup(environment.contentModel.models), unions);
15493
+ const hasSegment = environment.contentModel.systemModels.some((model) => model.__typename === "SegmentModel");
15409
15494
  const components = new Set(environment.contentModel.components.map(({ apiId }) => apiId));
15410
15495
  return {
15411
15496
  environmentId: environment.id,
@@ -15415,6 +15500,10 @@ async function readLiveEnvironment(target, fetch) {
15415
15500
  locales: convertLocalesToIR(environment.contentModel.locales),
15416
15501
  stages: convertStagesToIR(environment.contentModel.stages),
15417
15502
  ...live,
15503
+ ...hasSegment && { segment: segment ?? {
15504
+ apiId: "Segment",
15505
+ fields: {}
15506
+ } },
15418
15507
  components: live.components.filter(({ apiId }) => components.has(apiId))
15419
15508
  }
15420
15509
  };
@@ -15423,7 +15512,8 @@ async function readLiveEnvironment(target, fetch) {
15423
15512
  function partnerLookup(models) {
15424
15513
  return new Map(models.flatMap((model) => model.fields.flatMap((field) => field.__typename === "RelationalField" ? [[`${model.apiId}.${field.apiId}`, {
15425
15514
  relationalFieldRules: field.relationalFieldRules,
15426
- visibilityCondition: liveCondition(field.visibilityCondition)
15515
+ visibilityCondition: liveCondition(field.visibilityCondition),
15516
+ isVariantEnabled: field.isVariantEnabled
15427
15517
  }]] : [])));
15428
15518
  }
15429
15519
  /** Every union's id, and every union member's settings, by `Model.field`. */
@@ -15738,6 +15828,12 @@ const messages = {
15738
15828
  ["model.apiIdReserved"]: (apiId) => `"${apiId}" is the apiId of a model Hygraph provides.`,
15739
15829
  ["systemModel.duplicate"]: (call) => `${call} is listed more than once in models.`,
15740
15830
  ["systemModel.fieldRequired"]: (apiId, field) => `Field "${field}" on ${apiId} is required. Hygraph refuses a required field on a model it provides.`,
15831
+ ["systemModel.fieldVariantEnabled"]: (apiId, field) => `Field "${field}" on ${apiId} has variants. Only fields of your models can have them.`,
15832
+ ["systemModel.fieldApiIdTaken"]: (apiId, field) => `Field "${field}" on ${apiId} has the apiId of one of Hygraph's own fields on ${apiId}.`,
15833
+ ["systemModel.fieldType"]: (apiId, field) => `Field "${field}" on ${apiId} is of a type ${apiId} does not take. It takes text, rich text, number, date, boolean, JSON, color, location, enumeration and taxonomy fields.`,
15834
+ ["systemModel.segmentMissing"]: "Segment has fields, but Hygraph has no Segment yet and no field of your models has variants. Hygraph adds Segment with the first field that has variants.",
15835
+ ["systemModel.segmentNotYet"]: "Segment is in models, but Hygraph has no Segment yet and no field of your models has variants. The plan leaves Segment alone until Hygraph adds it with the first field that has variants.",
15836
+ ["systemModel.fieldLocalized"]: (apiId, field) => `Field "${field}" on ${apiId} is localized. Fields on ${apiId} have one value for every locale.`,
15741
15837
  ["systemModel.fieldUnion"]: (apiId, field) => `Field "${field}" on ${apiId} is a component union. Hygraph refuses one on a model it provides.`,
15742
15838
  ["systemModel.fieldReferenceTwoWay"]: (apiId, field) => `Field "${field}" on ${apiId} is a two-way reference. A two-way reference on ${apiId} is the field back of an asset field, which assetReverseField declares.`,
15743
15839
  ["systemModel.fieldNotRemote"]: (field) => `Field "${field}" on Query is not a remote field. Hygraph takes only remote fields on Query.`,
@@ -15874,6 +15970,11 @@ const messages = {
15874
15970
  ["field.referenceUnionMemberOnComponent"]: (field) => `Field "${field}" is a union member on a component. Only models have them.`,
15875
15971
  ["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.`,
15876
15972
  ["field.requiredNotVisible"]: (field, visibility) => `Field "${field}" is required and ${visibility}, so editors cannot fill it in.`,
15973
+ ["field.variantEnabledUnique"]: (field) => `Field "${field}" is unique and has variants. Hygraph refuses variants on a unique field.`,
15974
+ ["field.variantEnabledOnComponent"]: (field, component) => `Field "${field}" on component "${component}" has variants. Only fields of a model can have them.`,
15975
+ ["field.variantEnabledBaseField"]: (field, base) => `Field "${field}" has variants and a condition on "${base}", which has none. Hygraph needs the field a condition is on to have variants too.`,
15976
+ ["field.variantComponentRequired"]: (model, field) => `Component field "${field}" on ${model} will be required and have variants. Hygraph does not copy the component into the variants existing entries have, so they start without it.`,
15977
+ ["field.variantEnabledBothSides"]: (field, partner) => `Field "${field}" and its partner "${partner}" both have variants. Only one side of a two-way reference can have them.`,
15877
15978
  ["field.assetReverseInvalid"]: (field, reverse) => `Field "${field}" gets the field "${reverse}" on Asset, which is not a valid apiId.`,
15878
15979
  ["field.richTextEmbedsEmpty"]: (field) => `Field "${field}" has embeds, but names no model to embed.`,
15879
15980
  ["field.richTextEmbedDuplicate"]: (field, model) => `Field "${field}" lists model "${model}" more than once in embeds.`,
@@ -15883,8 +15984,8 @@ const messages = {
15883
15984
  ["field.richTextRequiredList"]: (field) => `Field "${field}" is a required list, which Hygraph refuses on rich text.`,
15884
15985
  ["field.assetReverseFieldMissing"]: (parent, field) => `Asset field "${field}" on ${parent} does not name its field back on Asset.`,
15885
15986
  ["field.assetReverseFieldOnComponent"]: (parent, field) => `Asset field "${field}" on component ${parent} names a field back. A component's field back is hidden, and the CLI names it.`,
15886
- ["field.assetSystemAssetMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} has its field back "${back}" on Asset, and models does not list system.asset.`,
15887
- ["field.assetFieldBackMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} names its field back "${back}", which system.asset does not list.`,
15987
+ ["field.assetSystemAssetMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} has its field back "${back}" on Asset, and models does not list system.model.asset.`,
15988
+ ["field.assetFieldBackMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} names its field back "${back}", which system.model.asset does not list.`,
15888
15989
  ["field.assetFieldBackPartner"]: (back, partner, problem) => `Field back "${back}" on Asset names ${partner}, which ${problem}.`,
15889
15990
  ["field.assetReverseFieldNotOnAsset"]: (parent, field) => `Field "${field}" on ${parent} is an assetReverseField. A field back is on Asset only.`,
15890
15991
  ["field.assetReverseFieldChanged"]: (parent, field, from, to) => `Asset field "${field}" on ${parent} has the field back "${from}" on Asset, and the config names "${to}".`,
@@ -15937,9 +16038,15 @@ const fixes = {
15937
16038
  ["model.invalidRenamedFrom"]: "Use the apiId the model has in Hygraph right now: an uppercase letter, then letters, digits and underscores only, up to 64 characters.",
15938
16039
  ["model.renamedFromMatchesApiId"]: "Set renamedFrom to the apiId the model has in Hygraph right now, or remove it.",
15939
16040
  ["model.noTitleField"]: "Set title: true on the field Studio should show entries by, such as a name or a heading.",
15940
- ["model.apiIdReserved"]: "Use another apiId. To add fields to Asset or Query, put system.asset({ fields }) or system.query({ fields }) in models.",
16041
+ ["model.apiIdReserved"]: "Use another apiId. To add fields to Asset, Query or Segment, put system.model.asset({ fields }), system.model.query({ fields }) or system.model.segment({ fields }) in models.",
15941
16042
  ["systemModel.duplicate"]: "List it once, with all your fields on it.",
15942
16043
  ["systemModel.fieldRequired"]: "Set required: false.",
16044
+ ["systemModel.fieldVariantEnabled"]: "Set variantEnabled: false.",
16045
+ ["systemModel.fieldType"]: "Use one of the types it takes, or put the field on a model of yours.",
16046
+ ["systemModel.fieldApiIdTaken"]: "Use another apiId. Hygraph's own fields are never listed in fields.",
16047
+ ["systemModel.fieldLocalized"]: "Set localized: false.",
16048
+ ["systemModel.segmentNotYet"]: "Set variantEnabled: true on a field of one of your models, or remove system.model.segment() from models until one has variants.",
16049
+ ["systemModel.segmentMissing"]: "Set variantEnabled: true on a field of one of your models, or leave Segment's fields out until one has variants.",
15943
16050
  ["systemModel.fieldUnion"]: "Use a component field, or put the union on a model of yours.",
15944
16051
  ["systemModel.fieldReferenceTwoWay"]: "Use define.field.assetReverseField with the same apiId, displayName, to and reverse, and no list or rules.",
15945
16052
  ["systemModel.fieldNotRemote"]: "Use define.field.remote, or put the field on a model of yours.",
@@ -16076,6 +16183,11 @@ const fixes = {
16076
16183
  ["field.referenceUnionMemberOnComponent"]: "Move the union reference and its field back to models, or remove the field back.",
16077
16184
  ["field.unionOwnerMissing"]: "Add this model to the union's to and set its reverse to this field's apiId, or remove this field.",
16078
16185
  ["field.requiredNotVisible"]: "Set required: false, or make the field READ_WRITE or READ_ONLY.",
16186
+ ["field.variantEnabledUnique"]: "Set unique: false or variantEnabled: false.",
16187
+ ["field.variantEnabledOnComponent"]: "Set variantEnabled: false, or move the field to a model.",
16188
+ ["field.variantEnabledBaseField"]: "Set variantEnabled: true on the field the condition is on, or variantEnabled: false on this one.",
16189
+ ["field.variantEnabledBothSides"]: "Set variantEnabled: false on one of the two.",
16190
+ ["field.variantComponentRequired"]: "Fill in the component in each existing variant after the apply.",
16079
16191
  ["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.",
16080
16192
  ["field.richTextEmbedsEmpty"]: "List at least one model in embeds, or remove embeds to turn them off.",
16081
16193
  ["field.richTextEmbedDuplicate"]: "List each model once in embeds.",
@@ -16083,13 +16195,13 @@ const fixes = {
16083
16195
  ["field.richTextEmbedComponent"]: "List only models in embeds. To hold a component, use define.field.component.",
16084
16196
  ["field.richTextUniqueEmbeds"]: "Remove unique, or remove embeds.",
16085
16197
  ["field.richTextRequiredList"]: "Remove required, or set list: false.",
16086
- ["field.assetReverseFieldMissing"]: (parent, field, back) => `Set reverse: "${back}" on the field, and add its field back to system.asset's fields: ${fieldBack(parent, field, back)}.`,
16198
+ ["field.assetReverseFieldMissing"]: (parent, field, back) => `Set reverse: "${back}" on the field, and add its field back to system.model.asset's fields: ${fieldBack(parent, field, back)}.`,
16087
16199
  ["field.assetReverseFieldOnComponent"]: "Remove reverse.",
16088
- ["field.assetSystemAssetMissing"]: (parent, field, back) => `Add const Asset = system.asset({ fields: [${fieldBack(parent, field, back)}] }) to models.`,
16089
- ["field.assetFieldBackMissing"]: (parent, field, back) => `Add ${fieldBack(parent, field, back)} to system.asset's fields, at the end for a new field.`,
16200
+ ["field.assetSystemAssetMissing"]: (parent, field, back) => `Add const Asset = system.model.asset({ fields: [${fieldBack(parent, field, back)}] }) to models.`,
16201
+ ["field.assetFieldBackMissing"]: (parent, field, back) => `Add ${fieldBack(parent, field, back)} to system.model.asset's fields, at the end for a new field.`,
16090
16202
  ["field.assetFieldBackPartner"]: "Point it at the asset field that names it in reverse: to is that field's model, and reverse is its apiId.",
16091
- ["field.assetReverseFieldNotOnAsset"]: "Move it to system.asset's fields, or use define.field.referenceTwoWay on a model.",
16092
- ["field.assetReverseFieldChanged"]: (_parent, _field, from) => `To rename the field back, set renamedFrom: "${from}" on it in system.asset. Otherwise set reverse back to "${from}".`,
16203
+ ["field.assetReverseFieldNotOnAsset"]: "Move it to system.model.asset's fields, or use define.field.referenceTwoWay on a model.",
16204
+ ["field.assetReverseFieldChanged"]: (_parent, _field, from) => `To rename the field back, set renamedFrom: "${from}" on it in system.model.asset. Otherwise set reverse back to "${from}".`,
16093
16205
  ["change.modelMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a model from one place only.",
16094
16206
  ["change.embedsReplaced"]: "Create the new models in one apply. Then change embeds and delete the old models in the next.",
16095
16207
  ["change.componentMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a component from one place only.",
@@ -16106,7 +16218,7 @@ const fixes = {
16106
16218
  ["change.fieldRenameBothInUse"]: "Delete one of the two fields first, in a plan of its own, or remove renamedFrom.",
16107
16219
  ["change.fieldRenameFromUnsupported"]: "Rename the field in Studio, then run export again.",
16108
16220
  ["change.unsupportedFieldMissing"]: "Remove it from the config, or run export again.",
16109
- ["change.unsupportedFieldType"]: "Run export again to write the field as the environment has it.",
16221
+ ["change.unsupportedFieldType"]: "Run pull to see the field as the environment has it, and write it into the config.",
16110
16222
  ["change.unsupportedPartnerDeleted"]: "Keep both sides in the config, or remove both.",
16111
16223
  ["change.unsupportedUnionDeleted"]: "Keep the union and its members in the config, or remove all of them.",
16112
16224
  ["change.unsupportedUnionEmptied"]: "Keep at least one member in the config, or remove the union with them.",
@@ -16552,6 +16664,7 @@ function validateReferenceModelReferences(parent, fields, models) {
16552
16664
  * is this field. Hygraph makes both in one create, so a pair the config
16553
16665
  * gives only half of, or two halves that disagree, has nothing to create.
16554
16666
  * A `to` the environment does not have is `field.referenceModelMissing`.
16667
+ * Only one side of a pair can have variants.
16555
16668
  */
16556
16669
  function validateReferenceTwoWayPartners(parent, fields, models) {
16557
16670
  const validations = [];
@@ -16591,6 +16704,9 @@ function validateReferenceTwoWayPartners(parent, fields, models) {
16591
16704
  if (partnerTarget !== `${parent.apiId}.${field.apiId}`) {
16592
16705
  const code = "field.referencePartnerMismatch";
16593
16706
  report(code, field.apiId, "reverse", messages[code](field.apiId, partnerName, partnerTarget));
16707
+ } else if (field.variantEnabled && partner.variantEnabled && `${parent.apiId}.${field.apiId}` < partnerName) {
16708
+ const code = "field.variantEnabledBothSides";
16709
+ report(code, field.apiId, "variantEnabled", messages[code](field.apiId, partnerName));
16594
16710
  }
16595
16711
  }
16596
16712
  return validations;
@@ -17450,7 +17566,8 @@ function validateTypeOptions(parent, field) {
17450
17566
  /**
17451
17567
  * A condition's base must be another field of the same model that holds one
17452
17568
  * value, and Studio does not let a required, a hidden or an API-only field
17453
- * have one. The server checks none of this; Studio's form does.
17569
+ * have one. The server checks none of this; Studio's form does. A field
17570
+ * with variants needs a base with variants, which the server checks.
17454
17571
  */
17455
17572
  function validateConditions(parent, fields) {
17456
17573
  const byApiId = new Map(fields.map((field) => [field.apiId, field]));
@@ -17490,6 +17607,13 @@ function validateConditions(parent, fields) {
17490
17607
  fix: fixes["field.conditionBaseList"]
17491
17608
  });
17492
17609
  else validations.push(...validateConditionValue(parent, field, base));
17610
+ if (field.variantEnabled && isConditionBase(base) && !base.variantEnabled) validations.push({
17611
+ code: "field.variantEnabledBaseField",
17612
+ severity: "error",
17613
+ path: fieldPath(parent, field.apiId, "variantEnabled"),
17614
+ message: messages["field.variantEnabledBaseField"](field.apiId, condition.baseField),
17615
+ fix: fixes["field.variantEnabledBaseField"]
17616
+ });
17493
17617
  if (field.visibility === "HIDDEN" || field.visibility === "API_ONLY") validations.push({
17494
17618
  code: "field.conditionNotVisible",
17495
17619
  severity: "error",
@@ -17547,6 +17671,8 @@ function validateOptions(parent, field) {
17547
17671
  });
17548
17672
  };
17549
17673
  if (field.required && (field.visibility === "HIDDEN" || field.visibility === "API_ONLY")) report("field.requiredNotVisible", "required", messages["field.requiredNotVisible"](field.apiId, field.visibility));
17674
+ if (field.variantEnabled && "unique" in field && field.unique) report("field.variantEnabledUnique", "variantEnabled", messages["field.variantEnabledUnique"](field.apiId));
17675
+ if (field.variantEnabled && parent.kind === "component") report("field.variantEnabledOnComponent", "variantEnabled", messages["field.variantEnabledOnComponent"](field.apiId, parent.apiId));
17550
17676
  const title = "title" in field && field.title;
17551
17677
  if (title && field.list) report("field.titleOnList", "title", messages["field.titleOnList"](field.apiId));
17552
17678
  if (title && (field.visibility === "HIDDEN" || field.visibility === "API_ONLY")) report("field.titleNotVisible", "title", messages["field.titleNotVisible"](field.apiId, field.visibility));
@@ -17566,9 +17692,10 @@ function validateOptions(parent, field) {
17566
17692
  /**
17567
17693
  * What Asset can tell about itself: its fields, as a model's are checked,
17568
17694
  * and what Hygraph refuses on a model it provides. A required field and a
17569
- * component union fail the whole migration. A two-way reference on Asset
17570
- * is a field back, which `assetReverseField` declares. There is no title
17571
- * check: Studio shows assets by their file.
17695
+ * component union fail the whole migration. Studio does not let a field
17696
+ * on Asset have variants. A two-way reference on Asset is a field back,
17697
+ * which `assetReverseField` declares. There is no title check: Studio
17698
+ * shows assets by their file.
17572
17699
  */
17573
17700
  function validateSystemAsset(asset) {
17574
17701
  const parent = {
@@ -17576,33 +17703,45 @@ function validateSystemAsset(asset) {
17576
17703
  apiId: asset.apiId
17577
17704
  };
17578
17705
  const validations = validateFields(parent, asset.fields);
17579
- for (const field of asset.fields) if (field.__typename === "ComponentUnionField") {
17580
- const code = "systemModel.fieldUnion";
17581
- validations.push({
17582
- code,
17583
- severity: "error",
17584
- path: fieldPath(parent, field.apiId, "components"),
17585
- message: messages[code](asset.apiId, field.apiId),
17586
- fix: fixes[code]
17587
- });
17588
- } else if (field.__typename === "ReferenceTwoWayField") {
17589
- const code = "systemModel.fieldReferenceTwoWay";
17590
- validations.push({
17591
- code,
17592
- severity: "error",
17593
- path: fieldPath(parent, field.apiId, "to"),
17594
- message: messages[code](asset.apiId, field.apiId),
17595
- fix: fixes[code]
17596
- });
17597
- } else if (field.__typename !== "UnsupportedField" && field.required) {
17598
- const code = "systemModel.fieldRequired";
17599
- validations.push({
17600
- code,
17601
- severity: "error",
17602
- path: fieldPath(parent, field.apiId, "required"),
17603
- message: messages[code](asset.apiId, field.apiId),
17604
- fix: fixes[code]
17605
- });
17706
+ for (const field of asset.fields) {
17707
+ if (field.__typename === "ComponentUnionField") {
17708
+ const code = "systemModel.fieldUnion";
17709
+ validations.push({
17710
+ code,
17711
+ severity: "error",
17712
+ path: fieldPath(parent, field.apiId, "components"),
17713
+ message: messages[code](asset.apiId, field.apiId),
17714
+ fix: fixes[code]
17715
+ });
17716
+ } else if (field.__typename === "ReferenceTwoWayField") {
17717
+ const code = "systemModel.fieldReferenceTwoWay";
17718
+ validations.push({
17719
+ code,
17720
+ severity: "error",
17721
+ path: fieldPath(parent, field.apiId, "to"),
17722
+ message: messages[code](asset.apiId, field.apiId),
17723
+ fix: fixes[code]
17724
+ });
17725
+ } else if (field.__typename !== "UnsupportedField" && field.required) {
17726
+ const code = "systemModel.fieldRequired";
17727
+ validations.push({
17728
+ code,
17729
+ severity: "error",
17730
+ path: fieldPath(parent, field.apiId, "required"),
17731
+ message: messages[code](asset.apiId, field.apiId),
17732
+ fix: fixes[code]
17733
+ });
17734
+ }
17735
+ if (field.__typename !== "UnsupportedField" && field.variantEnabled) {
17736
+ const code = "systemModel.fieldVariantEnabled";
17737
+ validations.push({
17738
+ code,
17739
+ severity: "error",
17740
+ path: fieldPath(parent, field.apiId, "variantEnabled"),
17741
+ message: messages[code](asset.apiId, field.apiId),
17742
+ fix: fixes[code]
17743
+ });
17744
+ }
17606
17745
  }
17607
17746
  return validations;
17608
17747
  }
@@ -17636,6 +17775,66 @@ function validateSystemQuery(query) {
17636
17775
  return validations;
17637
17776
  }
17638
17777
  //#endregion
17778
+ //#region src/define/system/segment.validation.ts
17779
+ /**
17780
+ * The field types Segment takes. Keyed by `SegmentModelField`'s, so the
17781
+ * compiler refuses a type missing here or one it does not take.
17782
+ */
17783
+ const SEGMENT_FIELD_TYPES = {
17784
+ BooleanField: true,
17785
+ SingleLineField: true,
17786
+ MultilineField: true,
17787
+ MarkdownField: true,
17788
+ SlugField: true,
17789
+ RichTextField: true,
17790
+ IntField: true,
17791
+ FloatField: true,
17792
+ DateField: true,
17793
+ DateTimeField: true,
17794
+ JsonField: true,
17795
+ ColorField: true,
17796
+ LocationField: true,
17797
+ EnumerationField: true,
17798
+ TaxonomyField: true,
17799
+ UnsupportedField: true
17800
+ };
17801
+ /** Hygraph's own fields on Segment, which yours cannot take the apiIds of. */
17802
+ const SEGMENT_OWN_FIELDS = /* @__PURE__ */ new Set(["name", "description"]);
17803
+ /**
17804
+ * What Segment can tell about itself: its fields, as a model's are
17805
+ * checked, and what Hygraph refuses on it. The server refuses a union and
17806
+ * a required field but for a taxonomy field, which this refuses too;
17807
+ * Studio offers no other type, a localized field or variants. There is no title check: Hygraph's name field is the title.
17808
+ */
17809
+ function validateSystemSegment(segment) {
17810
+ const parent = {
17811
+ kind: "model",
17812
+ apiId: segment.apiId
17813
+ };
17814
+ const validations = validateFields(parent, segment.fields);
17815
+ const report = (code, field, attribute) => {
17816
+ validations.push({
17817
+ code,
17818
+ severity: "error",
17819
+ path: fieldPath(parent, field.apiId, attribute),
17820
+ message: messages[code](segment.apiId, field.apiId),
17821
+ fix: fixes[code]
17822
+ });
17823
+ };
17824
+ for (const field of segment.fields) {
17825
+ if (SEGMENT_OWN_FIELDS.has(field.apiId)) report("systemModel.fieldApiIdTaken", field, "apiId");
17826
+ if (!Object.hasOwn(SEGMENT_FIELD_TYPES, field.__typename)) {
17827
+ report("systemModel.fieldType", field, "apiId");
17828
+ continue;
17829
+ }
17830
+ if (field.__typename === "UnsupportedField") continue;
17831
+ if (field.required) report("systemModel.fieldRequired", field, "required");
17832
+ if ("localized" in field && field.localized) report("systemModel.fieldLocalized", field, "localized");
17833
+ if (field.variantEnabled) report("systemModel.fieldVariantEnabled", field, "variantEnabled");
17834
+ }
17835
+ return validations;
17836
+ }
17837
+ //#endregion
17639
17838
  //#region src/define/resources/component.validation.ts
17640
17839
  /**
17641
17840
  * What a component can tell about itself, its fields included. Whether its
@@ -18187,8 +18386,9 @@ function nodePath(taxonomy, node) {
18187
18386
  //#region src/define/resources/environment.validation.ts
18188
18387
  /** The call that lists each model Hygraph provides, as the config writes it. */
18189
18388
  const SYSTEM_MODEL_CALLS = {
18190
- SystemAsset: "system.asset()",
18191
- SystemQuery: "system.query()"
18389
+ SystemAsset: "system.model.asset()",
18390
+ SystemQuery: "system.model.query()",
18391
+ SystemSegment: "system.model.segment()"
18192
18392
  };
18193
18393
  /**
18194
18394
  * What only the whole environment can tell: whether two resources collide,
@@ -18198,10 +18398,11 @@ const SYSTEM_MODEL_CALLS = {
18198
18398
  * by prefix. Models, components, enumerations and
18199
18399
  * taxonomies share one apiId namespace; locales and stages each have their
18200
18400
  * own. Display names are unique per kind. `Asset`, `QueryModel` and
18201
- * `Query` are Hygraph's: a model of yours cannot take any of them, and
18202
- * `system.asset` and `system.query` are listed once each. An asset field
18401
+ * `Query` are Hygraph's: a model of yours cannot take any of them. Nor
18402
+ * can it take `Segment` once Hygraph needs its own: when `system.model.segment`
18403
+ * is listed or a field has variants. Each `system.*` model is listed once. An asset field
18203
18404
  * on a model or on Asset names its field back on Asset, which
18204
- * `system.asset` lists as an `assetReverseField`.
18405
+ * `system.model.asset` lists as an `assetReverseField`.
18205
18406
  *
18206
18407
  * Runs over the models as declared, before conversion, so every report
18207
18408
  * points at the config the user wrote.
@@ -18214,7 +18415,7 @@ function validateEnvironment(environment) {
18214
18415
  validations.push(...validateStages(environment.stages));
18215
18416
  const systemApiIds = /* @__PURE__ */ new Set();
18216
18417
  for (const model of environment.systemModels) {
18217
- validations.push(...model.__typename === "SystemAsset" ? validateSystemAsset(model) : validateSystemQuery(model));
18418
+ validations.push(...validateSystemModel(model));
18218
18419
  if (systemApiIds.has(model.apiId)) {
18219
18420
  const code = "systemModel.duplicate";
18220
18421
  validations.push({
@@ -18227,13 +18428,14 @@ function validateEnvironment(environment) {
18227
18428
  }
18228
18429
  systemApiIds.add(model.apiId);
18229
18430
  }
18431
+ const needsSegment = environment.systemModels.some((model) => model.__typename === "SystemSegment") || environment.models.some((model) => model.fields.some((field) => field.__typename !== "UnsupportedField" && field.variantEnabled));
18230
18432
  for (const model of environment.models) {
18231
18433
  validations.push(...validateModel(model));
18232
18434
  if ([
18233
18435
  "Asset",
18234
18436
  "QueryModel",
18235
18437
  "Query"
18236
- ].includes(model.apiId)) {
18438
+ ].includes(model.apiId) || model.apiId === "Segment" && needsSegment) {
18237
18439
  const code = "model.apiIdReserved";
18238
18440
  validations.push({
18239
18441
  code,
@@ -18396,6 +18598,13 @@ function validateEnvironment(environment) {
18396
18598
  }
18397
18599
  return validations;
18398
18600
  }
18601
+ function validateSystemModel(model) {
18602
+ switch (model.__typename) {
18603
+ case "SystemAsset": return validateSystemAsset(model);
18604
+ case "SystemQuery": return validateSystemQuery(model);
18605
+ case "SystemSegment": return validateSystemSegment(model);
18606
+ }
18607
+ }
18399
18608
  //#endregion
18400
18609
  //#region src/diff/resources/component.ts
18401
18610
  /**
@@ -18880,13 +19089,49 @@ function diffFields(from, to, migrationValues = /* @__PURE__ */ new Map(), pairs
18880
19089
  const move = moveUnsupportedField(parent, fromField, field, afterDeletes);
18881
19090
  if (move) changes.updates.push(move);
18882
19091
  }
18883
- changes.updates = changes.updates.toSorted(byApiId$1);
19092
+ changes.updates = variantsInOrder(changes.updates.toSorted(byApiId$1), fromFields, to.fields);
18884
19093
  return changes;
18885
19094
  }
18886
19095
  /**
18887
- * The rules and condition of a two-way side its partner's create makes, as
18888
- * an update after the creates: the create takes neither for the partner.
18889
- * `null` when it has neither.
19096
+ * The updates with a condition's base field turning variants on before
19097
+ * the fields whose condition names it, and turning them off after: the
19098
+ * server refuses a field with variants whose base has none. Otherwise in
19099
+ * the order given.
19100
+ */
19101
+ function variantsInOrder(updates, from, to) {
19102
+ const turning = (on) => new Set(updates.flatMap((update) => update.kind !== "unsupported" && update.changes.variantEnabled?.to === on ? [update.apiId] : []));
19103
+ const on = turning(true);
19104
+ const off = turning(false);
19105
+ const before = /* @__PURE__ */ new Map();
19106
+ const runsFirst = (apiId, first) => before.set(apiId, [...before.get(apiId) ?? [], first]);
19107
+ for (const update of updates) {
19108
+ const fromBase = conditionBase(from[update.apiId]);
19109
+ const toBase = conditionBase(to[update.apiId]);
19110
+ if (fromBase !== void 0 && off.has(fromBase)) runsFirst(fromBase, update.apiId);
19111
+ if (toBase !== void 0 && on.has(toBase)) runsFirst(update.apiId, toBase);
19112
+ }
19113
+ const byApiId = new Map(updates.map((update) => [update.apiId, update]));
19114
+ const ordered = [];
19115
+ const visiting = /* @__PURE__ */ new Set();
19116
+ const visit = (update) => {
19117
+ if (ordered.includes(update) || visiting.has(update.apiId)) return;
19118
+ visiting.add(update.apiId);
19119
+ for (const apiId of before.get(update.apiId) ?? []) {
19120
+ const first = byApiId.get(apiId);
19121
+ if (first) visit(first);
19122
+ }
19123
+ ordered.push(update);
19124
+ };
19125
+ updates.forEach(visit);
19126
+ return ordered;
19127
+ }
19128
+ function conditionBase(field) {
19129
+ return field === void 0 || field.kind === "unsupported" ? void 0 : field.visibilityCondition?.baseField;
19130
+ }
19131
+ /**
19132
+ * The rules, condition and variants of a two-way side its partner's create
19133
+ * makes, as an update after the creates: the create takes none of them for
19134
+ * the partner. `null` when it has none.
18890
19135
  */
18891
19136
  function partnerSettings(parent, field) {
18892
19137
  if (field.kind !== "referenceTwoWay") return null;
@@ -18899,6 +19144,10 @@ function partnerSettings(parent, field) {
18899
19144
  from: null,
18900
19145
  to: field.visibilityCondition
18901
19146
  };
19147
+ if (field.variantEnabled) changes.variantEnabled = {
19148
+ from: false,
19149
+ to: true
19150
+ };
18902
19151
  return Object.keys(changes).length === 0 ? null : {
18903
19152
  action: "update",
18904
19153
  resource: "field",
@@ -19061,6 +19310,10 @@ function diffField(from, to) {
19061
19310
  from: from.visibilityCondition,
19062
19311
  to: to.visibilityCondition
19063
19312
  };
19313
+ if (from.variantEnabled !== to.variantEnabled) changes.variantEnabled = {
19314
+ from: from.variantEnabled,
19315
+ to: to.variantEnabled
19316
+ };
19064
19317
  if (from.kind === "componentUnion" && to.kind === "componentUnion" && hashJSON(from.components) !== hashJSON(to.components)) changes.components = {
19065
19318
  from: from.components,
19066
19319
  to: to.components
@@ -19637,6 +19890,15 @@ function diffEnvironment({ from, to, intents = {
19637
19890
  });
19638
19891
  }
19639
19892
  if (to.query) pushFields(renamed.query ?? null, to.query);
19893
+ const segmentCreates = [];
19894
+ const segmentConditions = [];
19895
+ if (to.segment) {
19896
+ const creates = fieldCreates.length;
19897
+ const conditions = fieldConditions.length;
19898
+ pushFields(renamed.segment ?? null, to.segment);
19899
+ segmentCreates.push(...fieldCreates.splice(creates));
19900
+ segmentConditions.push(...fieldConditions.splice(conditions));
19901
+ }
19640
19902
  const fromComponents = new Map(renamed.components.map((component) => [component.apiId, component]));
19641
19903
  const toComponentApiIds = new Set(to.components.map((component) => component.apiId));
19642
19904
  const deletedComponents = renamed.components.filter((component) => !toComponentApiIds.has(component.apiId));
@@ -19714,6 +19976,8 @@ function diffEnvironment({ from, to, intents = {
19714
19976
  ...fieldCreates.map((change) => withFieldBack(change, to)),
19715
19977
  ...memberAdds,
19716
19978
  ...fieldConditions,
19979
+ ...segmentCreates,
19980
+ ...segmentConditions,
19717
19981
  ...embeds.afterModelCreates
19718
19982
  ];
19719
19983
  }
@@ -19731,7 +19995,9 @@ function diffEnvironment({ from, to, intents = {
19731
19995
  * Both places keep a move right: positions count after the field deletes,
19732
19996
  * and the model deletes renumber no other model's fields. A field whose
19733
19997
  * embeds were all deleted and that embeds a created model goes after the
19734
- * creates, which `validateChangeSet` refuses.
19998
+ * creates, which `validateChangeSet` refuses. A moved update's variants
19999
+ * stay in an update of their own among the field updates, in the order
20000
+ * `variantsInOrder` gave them.
19735
20001
  */
19736
20002
  function orderEmbeds(changes, deleted, created) {
19737
20003
  const order = {
@@ -19740,10 +20006,31 @@ function orderEmbeds(changes, deleted, created) {
19740
20006
  afterModelCreates: []
19741
20007
  };
19742
20008
  for (const change of changes) {
19743
- const embeds = change.resource === "field" && change.action === "update" && change.kind === "richText" ? change.changes.embeds : void 0;
19744
- if ((embeds?.to ?? []).some((apiId) => created.has(apiId))) order.afterModelCreates.push(change);
19745
- else if ((embeds?.from ?? []).some((apiId) => deleted.has(apiId))) order.beforeModelDeletes.push(change);
19746
- else order.updates.push(change);
20009
+ if (change.resource !== "field" || change.action !== "update" || change.kind !== "richText") {
20010
+ order.updates.push(change);
20011
+ continue;
20012
+ }
20013
+ const { embeds, variantEnabled, ...rest } = change.changes;
20014
+ const moveTo = (embeds?.to ?? []).some((apiId) => created.has(apiId)) ? order.afterModelCreates : (embeds?.from ?? []).some((apiId) => deleted.has(apiId)) ? order.beforeModelDeletes : void 0;
20015
+ if (moveTo === void 0) order.updates.push(change);
20016
+ else if (variantEnabled === void 0) moveTo.push(change);
20017
+ else {
20018
+ moveTo.push({
20019
+ ...change,
20020
+ changes: {
20021
+ ...rest,
20022
+ embeds
20023
+ }
20024
+ });
20025
+ order.updates.push({
20026
+ action: "update",
20027
+ resource: "field",
20028
+ parent: change.parent,
20029
+ apiId: change.apiId,
20030
+ kind: change.kind,
20031
+ changes: { variantEnabled }
20032
+ });
20033
+ }
19747
20034
  }
19748
20035
  return order;
19749
20036
  }
@@ -20056,7 +20343,7 @@ function applyEnumerationValueRenames(from, intents) {
20056
20343
  renames
20057
20344
  };
20058
20345
  }
20059
- /** Every model, component and Asset with `map` applied to each of its fields. */
20346
+ /** Every model, component, Asset and Segment with `map` applied to each of its fields. */
20060
20347
  function mapFields(from, map) {
20061
20348
  const mapParent = (parent) => ({
20062
20349
  ...parent,
@@ -20065,7 +20352,8 @@ function mapFields(from, map) {
20065
20352
  return {
20066
20353
  models: from.models.map(mapParent),
20067
20354
  components: from.components.map(mapParent),
20068
- ...from.asset && { asset: mapParent(from.asset) }
20355
+ ...from.asset && { asset: mapParent(from.asset) },
20356
+ ...from.segment && { segment: mapParent(from.segment) }
20069
20357
  };
20070
20358
  }
20071
20359
  /**
@@ -20226,7 +20514,8 @@ function applyFieldRenames(from, intents) {
20226
20514
  ...from,
20227
20515
  models: from.models.map(renameFields),
20228
20516
  components: from.components.map(renameFields),
20229
- ...from.asset && { asset: renameFields(from.asset) }
20517
+ ...from.asset && { asset: renameFields(from.asset) },
20518
+ ...from.segment && { segment: renameFields(from.segment) }
20230
20519
  };
20231
20520
  const parents = mapFields(renamed, (field) => {
20232
20521
  switch (field.kind) {
@@ -20709,6 +20998,10 @@ function validateUnsupportedFields({ from, to, intents, unsupportedPairs = [], u
20709
20998
  kind: "model",
20710
20999
  parent: to.query
20711
21000
  }] : [],
21001
+ ...to.segment ? [{
21002
+ kind: "model",
21003
+ parent: to.segment
21004
+ }] : [],
20712
21005
  ...to.components.map((parent) => ({
20713
21006
  kind: "component",
20714
21007
  parent
@@ -20886,6 +21179,10 @@ function liveParent(from, intents, parent) {
20886
21179
  ["QueryModel", from.query ?? {
20887
21180
  apiId: "QueryModel",
20888
21181
  fields: {}
21182
+ }],
21183
+ ["Segment", from.segment ?? {
21184
+ apiId: "Segment",
21185
+ fields: {}
20889
21186
  }]
20890
21187
  ]);
20891
21188
  const rename = intents.renames.find((each) => (each.resource === "model" || each.resource === "component") && each.apiId === parent);
@@ -20893,6 +21190,52 @@ function liveParent(from, intents, parent) {
20893
21190
  return parents.get(parent);
20894
21191
  }
20895
21192
  /**
21193
+ * Hygraph adds Segment with the first field that has variants, and keeps
21194
+ * it. Live without Segment has no such field yet, so one of your models
21195
+ * needs one in this plan. Without it, your fields on Segment are an error,
21196
+ * and Segment listed without fields, which plans nothing, a warning.
21197
+ */
21198
+ function validateSegment({ from, to }) {
21199
+ if (from.segment !== void 0 || to.segment === void 0 || to.models.some((model) => Object.values(model.fields).some((field) => field.kind !== "unsupported" && field.variantEnabled))) return [];
21200
+ const empty = Object.keys(to.segment.fields).length === 0;
21201
+ const code = empty ? "systemModel.segmentNotYet" : "systemModel.segmentMissing";
21202
+ return [{
21203
+ code,
21204
+ severity: empty ? "warning" : "error",
21205
+ path: ["models", "Segment"],
21206
+ message: messages[code],
21207
+ fix: fixes[code]
21208
+ }];
21209
+ }
21210
+ /**
21211
+ * A component field that becomes required with variants, by either change.
21212
+ * Hygraph copies a required field's values into the variants of existing
21213
+ * entries, but not a component's, so those variants start without it.
21214
+ * The field and its model are looked up live under the apiIds they have
21215
+ * before the plan's renames.
21216
+ */
21217
+ function validateVariantComponents({ from, to, intents }) {
21218
+ return to.models.flatMap((model) => Object.values(model.fields).flatMap((field) => {
21219
+ const rename = intents.fieldRenames.find((each) => each.parent === model.apiId && each.apiId === field.apiId);
21220
+ const fields = liveParent(from, intents, model.apiId)?.fields ?? {};
21221
+ const before = fields[field.apiId] ?? (rename === void 0 ? void 0 : fields[rename.renamedFrom]);
21222
+ if (field.kind !== "component" || !field.required || !field.variantEnabled || before?.kind !== "component" || before.required && before.variantEnabled) return [];
21223
+ const code = "field.variantComponentRequired";
21224
+ return [{
21225
+ code,
21226
+ severity: "warning",
21227
+ path: [
21228
+ "models",
21229
+ model.apiId,
21230
+ "fields",
21231
+ field.apiId
21232
+ ],
21233
+ message: messages[code](model.apiId, field.apiId),
21234
+ fix: fixes[code]
21235
+ }];
21236
+ }));
21237
+ }
21238
+ /**
20896
21239
  * Whether every change can be applied at its point of the migration. Plays
20897
21240
  * the change set through in order against `from`: a delete or update needs
20898
21241
  * its locale, model, component or enumeration to still exist, a create or
@@ -20909,6 +21252,7 @@ function validateChangeSet({ from, changes }) {
20909
21252
  const models = new Map(from.models.map((model) => [model.apiId, model]));
20910
21253
  const components = new Map(from.components.map((component) => [component.apiId, component]));
20911
21254
  const componentApiIds = new Set(components.keys());
21255
+ let segment = from.segment !== void 0;
20912
21256
  const enumerations = new Map(from.enumerations.map((enumeration) => [enumeration.apiId, enumeration]));
20913
21257
  const taxonomies = new Map(from.taxonomies.map((taxonomy) => [taxonomy.apiId, {
20914
21258
  apiId: taxonomy.apiId,
@@ -21004,7 +21348,8 @@ function validateChangeSet({ from, changes }) {
21004
21348
  validateComponentsUsed(change);
21005
21349
  validateModelReferenced(change);
21006
21350
  validateModelsEmbedded(change);
21007
- if (change.parent === "Asset" || change.parent === "QueryModel" || models.has(change.parent) || components.has(change.parent)) break;
21351
+ if (turnsVariantsOn(change) && models.has(change.parent)) segment = true;
21352
+ if (change.parent === "Asset" || change.parent === "QueryModel" || change.parent === "Segment" && segment || models.has(change.parent) || components.has(change.parent)) break;
21008
21353
  const onComponent = componentApiIds.has(change.parent);
21009
21354
  report(onComponent ? "change.componentMissing" : "change.modelMissing", [
21010
21355
  onComponent ? "components" : "models",
@@ -21281,6 +21626,10 @@ function applyUpdate(model, change) {
21281
21626
  function text(entry, params) {
21282
21627
  return typeof entry === "string" ? entry : entry(...params);
21283
21628
  }
21629
+ /** A field create or update that gives the field variants. */
21630
+ function turnsVariantsOn(change) {
21631
+ return change.action === "create" ? change.field.variantEnabled : change.action === "update" && change.kind !== "unsupported" && change.changes.variantEnabled?.to === true;
21632
+ }
21284
21633
  //#endregion
21285
21634
  //#region src/validations/render.ts
21286
21635
  /**
@@ -21306,6 +21655,7 @@ const assetFieldSchema = strictObject({
21306
21655
  required: boolean(),
21307
21656
  visibility: fieldVisibilitySchema,
21308
21657
  visibilityCondition: visibilityConditionSchema.nullable(),
21658
+ variantEnabled: boolean(),
21309
21659
  reverse: string$1().nullable(),
21310
21660
  renamedFrom: string$1().nullable()
21311
21661
  });
@@ -21322,6 +21672,7 @@ const assetReverseFieldSchema = strictObject({
21322
21672
  required: literal(false),
21323
21673
  visibility: fieldVisibilitySchema,
21324
21674
  visibilityCondition: _null(),
21675
+ variantEnabled: literal(false),
21325
21676
  renamedFrom: string$1().nullable()
21326
21677
  });
21327
21678
  //#endregion
@@ -21338,6 +21689,7 @@ const booleanFieldSchema = strictObject({
21338
21689
  title: boolean(),
21339
21690
  visibility: fieldVisibilitySchema,
21340
21691
  visibilityCondition: visibilityConditionSchema.nullable(),
21692
+ variantEnabled: boolean(),
21341
21693
  initialValue: union([boolean(), array(boolean())]).nullable(),
21342
21694
  migrationValue: union([boolean(), array(boolean())]).nullable(),
21343
21695
  renamedFrom: string$1().nullable()
@@ -21356,6 +21708,7 @@ const componentFieldSchema = strictObject({
21356
21708
  required: boolean(),
21357
21709
  visibility: fieldVisibilitySchema,
21358
21710
  visibilityCondition: visibilityConditionSchema.nullable(),
21711
+ variantEnabled: boolean(),
21359
21712
  renamedFrom: string$1().nullable()
21360
21713
  });
21361
21714
  const componentUnionFieldSchema = strictObject({
@@ -21368,6 +21721,7 @@ const componentUnionFieldSchema = strictObject({
21368
21721
  required: literal(false),
21369
21722
  visibility: fieldVisibilitySchema,
21370
21723
  visibilityCondition: visibilityConditionSchema.nullable(),
21724
+ variantEnabled: boolean(),
21371
21725
  renamedFrom: string$1().nullable()
21372
21726
  });
21373
21727
  //#endregion
@@ -21385,6 +21739,7 @@ const dateFieldShape = {
21385
21739
  title: boolean(),
21386
21740
  visibility: fieldVisibilitySchema,
21387
21741
  visibilityCondition: visibilityConditionSchema.nullable(),
21742
+ variantEnabled: boolean(),
21388
21743
  initialValue: dateValueSchema,
21389
21744
  migrationValue: dateValueSchema,
21390
21745
  renamedFrom: string$1().nullable()
@@ -21427,6 +21782,7 @@ const enumerationFieldSchema = strictObject({
21427
21782
  title: boolean(),
21428
21783
  visibility: fieldVisibilitySchema,
21429
21784
  visibilityCondition: visibilityConditionSchema.nullable(),
21785
+ variantEnabled: boolean(),
21430
21786
  initialValue: enumerationValueSchema,
21431
21787
  migrationValue: enumerationValueSchema,
21432
21788
  renamedFrom: string$1().nullable()
@@ -21446,6 +21802,7 @@ const jsonFieldSchema = strictObject({
21446
21802
  title: literal(false),
21447
21803
  visibility: fieldVisibilitySchema,
21448
21804
  visibilityCondition: visibilityConditionSchema.nullable(),
21805
+ variantEnabled: boolean(),
21449
21806
  initialValue: jsonValueSchema,
21450
21807
  migrationValue: jsonValueSchema,
21451
21808
  renamedFrom: string$1().nullable()
@@ -21473,6 +21830,7 @@ const numberFieldShape = {
21473
21830
  title: boolean(),
21474
21831
  visibility: fieldVisibilitySchema,
21475
21832
  visibilityCondition: visibilityConditionSchema.nullable(),
21833
+ variantEnabled: boolean(),
21476
21834
  initialValue: numberValueSchema,
21477
21835
  migrationValue: numberValueSchema,
21478
21836
  validations: strictObject({
@@ -21506,6 +21864,7 @@ const referenceOneWayFieldSchema = strictObject({
21506
21864
  }) }).nullable(),
21507
21865
  visibility: fieldVisibilitySchema,
21508
21866
  visibilityCondition: visibilityConditionSchema.nullable(),
21867
+ variantEnabled: boolean(),
21509
21868
  renamedFrom: string$1().nullable()
21510
21869
  });
21511
21870
  //#endregion
@@ -21526,6 +21885,7 @@ const referenceTwoWayFieldSchema = strictObject({
21526
21885
  }) }).nullable(),
21527
21886
  visibility: fieldVisibilitySchema,
21528
21887
  visibilityCondition: visibilityConditionSchema.nullable(),
21888
+ variantEnabled: boolean(),
21529
21889
  renamedFrom: string$1().nullable()
21530
21890
  });
21531
21891
  //#endregion
@@ -21546,6 +21906,7 @@ const referenceUnionFieldSchema = strictObject({
21546
21906
  }) }).nullable(),
21547
21907
  visibility: fieldVisibilitySchema,
21548
21908
  visibilityCondition: visibilityConditionSchema.nullable(),
21909
+ variantEnabled: boolean(),
21549
21910
  renamedFrom: string$1().nullable()
21550
21911
  });
21551
21912
  //#endregion
@@ -21561,6 +21922,7 @@ const referenceUnionMemberFieldSchema = strictObject({
21561
21922
  required: literal(false),
21562
21923
  visibility: fieldVisibilitySchema,
21563
21924
  visibilityCondition: visibilityConditionSchema.nullable(),
21925
+ variantEnabled: literal(false),
21564
21926
  renamedFrom: string$1().nullable()
21565
21927
  });
21566
21928
  //#endregion
@@ -21630,6 +21992,7 @@ const remoteFieldSchema = strictObject({
21630
21992
  required: boolean(),
21631
21993
  visibility: fieldVisibilitySchema,
21632
21994
  visibilityCondition: _null(),
21995
+ variantEnabled: literal(false),
21633
21996
  renamedFrom: string$1().nullable()
21634
21997
  });
21635
21998
  //#endregion
@@ -21662,6 +22025,7 @@ const stringFieldShape = {
21662
22025
  title: boolean(),
21663
22026
  visibility: fieldVisibilitySchema,
21664
22027
  visibilityCondition: visibilityConditionSchema.nullable(),
22028
+ variantEnabled: boolean(),
21665
22029
  initialValue: textValueSchema,
21666
22030
  migrationValue: textValueSchema,
21667
22031
  validations: stringValidationRulesSchema.nullable(),
@@ -21731,6 +22095,7 @@ const fieldSchema = discriminatedUnion("__typename", [
21731
22095
  unique: boolean(),
21732
22096
  visibility: fieldVisibilitySchema,
21733
22097
  visibilityCondition: visibilityConditionSchema.nullable(),
22098
+ variantEnabled: boolean(),
21734
22099
  initialValue: taxonomyValueSchema,
21735
22100
  migrationValue: taxonomyValueSchema,
21736
22101
  renamedFrom: string$1().nullable()
@@ -21769,6 +22134,13 @@ const systemQuerySchema = strictObject({
21769
22134
  fields: array(fieldSchema)
21770
22135
  });
21771
22136
  //#endregion
22137
+ //#region src/define/system/segment.zod.ts
22138
+ const systemSegmentSchema = strictObject({
22139
+ __typename: literal("SystemSegment"),
22140
+ apiId: literal("Segment"),
22141
+ fields: array(fieldSchema)
22142
+ });
22143
+ //#endregion
21772
22144
  //#region src/define/resources/component.zod.ts
21773
22145
  const componentSchema = strictObject({
21774
22146
  __typename: literal("Component"),
@@ -21811,7 +22183,11 @@ const environmentSchema = strictObject({
21811
22183
  remoteSources: array(remoteSourceSchema),
21812
22184
  components: array(componentSchema),
21813
22185
  models: array(modelSchema),
21814
- systemModels: array(union([systemAssetSchema, systemQuerySchema]))
22186
+ systemModels: array(union([
22187
+ systemAssetSchema,
22188
+ systemQuerySchema,
22189
+ systemSegmentSchema
22190
+ ]))
21815
22191
  });
21816
22192
  //#endregion
21817
22193
  //#region src/define/resources/target.zod.ts
@@ -22063,6 +22439,11 @@ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
22063
22439
  to: desired,
22064
22440
  intents
22065
22441
  }), `the fields back on Asset do not match the asset fields,`);
22442
+ const segmentValidations = validateSegment({
22443
+ from: live,
22444
+ to: desired
22445
+ });
22446
+ maybeRefuse(segmentValidations, `Segment's fields cannot be planned against ${target.environment},`);
22066
22447
  const diffed = diffEnvironment({
22067
22448
  from: live,
22068
22449
  to: desired,
@@ -22089,7 +22470,15 @@ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
22089
22470
  }),
22090
22471
  environmentId,
22091
22472
  secretValues: secretValues(desired, secrets),
22092
- warnings: [...configValidations.filter((validation) => validation.severity === "warning"), ...warnings]
22473
+ warnings: [
22474
+ ...[...configValidations, ...segmentValidations].filter((validation) => validation.severity === "warning"),
22475
+ ...validateVariantComponents({
22476
+ from: live,
22477
+ to: desired,
22478
+ intents
22479
+ }),
22480
+ ...warnings
22481
+ ]
22093
22482
  };
22094
22483
  }
22095
22484
  /** Below the plan: what is worth a look but does not stop it. */
@@ -22234,7 +22623,7 @@ async function prepare(target, { config, options, colors, planFiles, write }) {
22234
22623
  const file = planFiles?.get(target.name);
22235
22624
  const artifact = file === void 0 ? void 0 : readPlanFile(file);
22236
22625
  if (artifact !== void 0) refuseUnsendableOAuthSecrets(unmaskSecrets(artifact.changes, oAuthSecretValues(oAuthSecrets(target.apply))));
22237
- const { plan: fresh, environmentId, secretValues } = await computePlan(target, void 0, { rotateSecrets: artifact ? sentOAuthSecrets(artifact.changes) : options.rotateSecret });
22626
+ const { plan: fresh, environmentId, secretValues, warnings } = await computePlan(target, void 0, { rotateSecrets: artifact ? sentOAuthSecrets(artifact.changes) : options.rotateSecret });
22238
22627
  let plan = fresh;
22239
22628
  if (file !== void 0 && artifact !== void 0) {
22240
22629
  const refusals = verifyPlan(artifact, fresh);
@@ -22250,6 +22639,7 @@ async function prepare(target, { config, options, colors, planFiles, write }) {
22250
22639
  config,
22251
22640
  colors
22252
22641
  }));
22642
+ if (warnings.length > 0) write(renderWarnings(warnings, colors));
22253
22643
  if (plan.changes.length === 0) return;
22254
22644
  if (plan.summary.destructive > 0 && options.prune !== true) throw new ApplyRefusal(renderDestructiveRefusal(plan.summary, colors));
22255
22645
  refuseUnsendableOAuthSecrets(unmaskSecrets(plan.changes, secretValues));
@@ -22627,6 +23017,7 @@ function fieldOptions(field, defaults) {
22627
23017
  ["title", !("title" in field) || field.title === defaults.title ? void 0 : String(field.title)],
22628
23018
  ["visibility", field.visibility === defaults.visibility ? void 0 : string(field.visibility)],
22629
23019
  ["visibilityCondition", field.visibilityCondition === null ? void 0 : printCondition(field.visibilityCondition)],
23020
+ ["variantEnabled", field.variantEnabled === defaults.variantEnabled ? void 0 : String(field.variantEnabled)],
22630
23021
  ["initialValue", field.initialValue === null ? void 0 : JSON.stringify(field.initialValue)]
22631
23022
  ];
22632
23023
  }
@@ -22645,7 +23036,8 @@ function referenceOptions(field, referenced) {
22645
23036
  ["list", field.list === FIELD_DEFAULTS.list ? void 0 : String(field.list)],
22646
23037
  ["required", field.required === FIELD_DEFAULTS.required ? void 0 : String(field.required)],
22647
23038
  ["visibility", field.visibility === FIELD_DEFAULTS.visibility ? void 0 : string(field.visibility)],
22648
- ["visibilityCondition", field.visibilityCondition === null ? void 0 : printCondition(field.visibilityCondition)]
23039
+ ["visibilityCondition", field.visibilityCondition === null ? void 0 : printCondition(field.visibilityCondition)],
23040
+ ["variantEnabled", field.variantEnabled === FIELD_DEFAULTS.variantEnabled ? void 0 : String(field.variantEnabled)]
22649
23041
  ];
22650
23042
  }
22651
23043
  /** A condition with the value its base field's type takes. */
@@ -22799,17 +23191,33 @@ function printStage(stage) {
22799
23191
  }
22800
23192
  //#endregion
22801
23193
  //#region src/export/resources/system.ts
22802
- /** `const Asset = system.asset({ fields: [...] });`, your fields only. */
23194
+ /** `const Asset = system.model.asset({ fields: [...] });`, your fields only. */
22803
23195
  function printSystemAsset(asset) {
22804
- return `const Asset = system.asset(${object([["fields", printFields(asset.apiId, asset.fields, printAssetModelField)]])});`;
23196
+ return `const Asset = system.model.asset(${object([["fields", printFields(asset.apiId, asset.fields, printAssetModelField)]])});`;
22805
23197
  }
22806
23198
  /**
22807
- * `const Query = system.query({ fields: [...] });`. Its remote fields read
23199
+ * `const Query = system.model.query({ fields: [...] });`. Its remote fields read
22808
23200
  * their headers as `QUERY_<FIELD>_<HEADER>`, after the name Studio shows.
22809
23201
  */
22810
23202
  function printSystemQuery(query) {
22811
- return `const Query = system.query(${object([["fields", printFields("Query", query.fields)]])});`;
23203
+ return `const Query = system.model.query(${object([["fields", printFields("Query", query.fields)]])});`;
23204
+ }
23205
+ /** `const Segment = system.model.segment({ fields: [...] });`, your fields only. */
23206
+ function printSystemSegment(segment) {
23207
+ return `const Segment = system.model.segment(${object([["fields", printFields(segment.apiId, segment.fields)]])});`;
22812
23208
  }
23209
+ /**
23210
+ * Segment as a comment, for an environment Hygraph has not added it to
23211
+ * yet, so the config shows where it goes once a field has variants.
23212
+ */
23213
+ const SEGMENT_NOT_YET = [
23214
+ "// Segment (the audiences for variants) does not exist in this project yet.",
23215
+ "// To add fields to it:",
23216
+ "// 1. Give a field of one of your models variantEnabled: true.",
23217
+ "// 2. Uncomment the line below and add Segment to models.",
23218
+ "// Both can go in the same plan.",
23219
+ "// const Segment = system.model.segment({ fields: [] });"
23220
+ ].join("\n");
22813
23221
  //#endregion
22814
23222
  //#region src/export/resources/taxonomy.ts
22815
23223
  /**
@@ -22855,10 +23263,11 @@ const NO_QUERY_FIELDS = {
22855
23263
  * The config a user commits: one const per enumeration, then per
22856
23264
  * taxonomy, per remote source, per component and per model, in IR
22857
23265
  * order, then Asset and Query, also with no fields of yours, so the first
22858
- * asset field only adds its field back there. Then the environment that
22859
- * lists them with every locale and stage written inline, and the target as
22860
- * the default export. The token is read from HYGRAPH_TOKEN when the config
22861
- * loads, never written.
23266
+ * asset field only adds its field back there. Then Segment, as a comment
23267
+ * while live has none. Then the environment that lists them with every
23268
+ * locale and stage written inline, and the target as the default export.
23269
+ * The token is read from HYGRAPH_TOKEN when the config loads, never
23270
+ * written.
22862
23271
  */
22863
23272
  async function printConfig(target, environment) {
22864
23273
  return formatSource([
@@ -22870,6 +23279,7 @@ async function printConfig(target, environment) {
22870
23279
  ...environment.models.map(printModel),
22871
23280
  printSystemAsset(environment.asset ?? NO_ASSET_FIELDS),
22872
23281
  printSystemQuery(environment.query ?? NO_QUERY_FIELDS),
23282
+ environment.segment ? printSystemSegment(environment.segment) : SEGMENT_NOT_YET,
22873
23283
  printEnvironment(environment),
22874
23284
  printTarget(target)
22875
23285
  ].join("\n\n"));
@@ -22879,9 +23289,10 @@ async function printConfig(target, environment) {
22879
23289
  * every stage in its live order, also when Draft and Published are the only
22880
23290
  * ones, so the config shows where a new stage goes. `enumerations`,
22881
23291
  * `taxonomies`, `remoteSources` and `components` are left out when there
22882
- * are none, their default. `models` ends with Asset and Query.
23292
+ * are none, their default. `models` ends with Asset, Query and Segment,
23293
+ * when live has it.
22883
23294
  */
22884
- function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSources, components, models, asset }) {
23295
+ function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSources, components, models, asset, segment }) {
22885
23296
  const list = (resources) => `[${resources.map((resource) => resource.apiId).join(", ")}]`;
22886
23297
  return `const environment = define.environment({ ${[
22887
23298
  `locales: [${locales.map(printLocale).join(", ")}]`,
@@ -22893,7 +23304,8 @@ function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSou
22893
23304
  `models: ${list([
22894
23305
  ...models,
22895
23306
  asset ?? NO_ASSET_FIELDS,
22896
- { apiId: "Query" }
23307
+ { apiId: "Query" },
23308
+ ...segment ? [segment] : []
22897
23309
  ])}`
22898
23310
  ].join(", ")} });`;
22899
23311
  }
@@ -22993,17 +23405,188 @@ function count(environment) {
22993
23405
  return models === 1 ? "1 model" : `${models} models`;
22994
23406
  }
22995
23407
  //#endregion
23408
+ //#region src/pull/diff.ts
23409
+ /**
23410
+ * The unified diff that takes the config to live, both printed the way
23411
+ * export writes them, or `undefined` when they print the same. Printing
23412
+ * both sides keeps the diff to what differs in the schema, whatever the
23413
+ * config's own layout.
23414
+ *
23415
+ * It describes the change, it is not a patch for the config file: the
23416
+ * config may keep its consts in other files, or hold code of its own, so
23417
+ * the sides are named `config` and `live`, with the target's name, rather
23418
+ * than by a path. By
23419
+ * default it holds the changed lines only, each run under the resource it
23420
+ * is in, such as `@@ component PullQuote`, which is how to find it in any
23421
+ * file. `full` prints the whole config instead, with the changes marked,
23422
+ * so a change shows where it sits among the lines around it.
23423
+ */
23424
+ async function diffConfig(target, config, live, { full = false } = {}) {
23425
+ const [from, to] = await Promise.all([printConfig(target, config), printConfig(target, live)]);
23426
+ if (from === to) return;
23427
+ const lines = Math.max(from.split("\n").length, to.split("\n").length);
23428
+ const patch = structuredPatch("config", "live", from, to, void 0, void 0, { context: full ? lines : 0 });
23429
+ if (full) return [
23430
+ `--- config (${target.name})`,
23431
+ `+++ live (${target.name})`,
23432
+ ...patch.hunks.flatMap((hunk) => hunk.lines)
23433
+ ].join("\n");
23434
+ const configLabels = resourceLabels(from);
23435
+ const liveLabels = resourceLabels(to);
23436
+ return [
23437
+ `--- config (${target.name})`,
23438
+ `+++ live (${target.name})`,
23439
+ ...patch.hunks.flatMap((hunk) => {
23440
+ const label = hunk.lines.some((line) => line.startsWith("+")) ? liveLabels[hunk.newStart] : configLabels[hunk.oldStart];
23441
+ return [label ? `@@ ${label}` : "@@", ...hunk.lines];
23442
+ })
23443
+ ].join("\n");
23444
+ }
23445
+ /** How export starts each resource, and what the diff calls it. */
23446
+ const RESOURCE_STARTS = [
23447
+ [/^const (\w+) = define\.model\(/, (name) => `model ${name}`],
23448
+ [/^const (\w+) = define\.component\(/, (name) => `component ${name}`],
23449
+ [/^const (\w+) = define\.enumeration\(/, (name) => `enumeration ${name}`],
23450
+ [/^const (\w+) = define\.taxonomy\(/, (name) => `taxonomy ${name}`],
23451
+ [/^const (\w+)RemoteSource = define\.(?:graphql|rest)RemoteSource\(/, (prefix) => `remote source ${prefix}`],
23452
+ [/^const \w+ = system\.model\.asset\(/, () => "system.model.asset"],
23453
+ [/^const \w+ = system\.model\.query\(/, () => "system.model.query"],
23454
+ [/^const \w+ = system\.model\.segment\(/, () => "system.model.segment"],
23455
+ [/^const environment = define\.environment\(/, () => "environment"],
23456
+ [/^export default define\.target\(/, () => "target"]
23457
+ ];
23458
+ /** Each line's resource, by 1-based line number: the last one that starts at or above it. */
23459
+ function resourceLabels(text) {
23460
+ let current = null;
23461
+ return [null, ...text.split("\n").map((line) => {
23462
+ for (const [start, label] of RESOURCE_STARTS) {
23463
+ const match = start.exec(line);
23464
+ if (match) current = label(match[1] ?? "");
23465
+ }
23466
+ return current;
23467
+ })];
23468
+ }
23469
+ //#endregion
23470
+ //#region src/pull/render.ts
23471
+ /**
23472
+ * What pull prints for one target: a header naming it and the config, for
23473
+ * a reader, and the diff. Pull writes the header to stderr and the diff to
23474
+ * stdout, so `hygraph pull > drift.diff` saves the diff alone. Without a
23475
+ * difference there is a header only.
23476
+ */
23477
+ function renderPull(diff, { target, config, colors, full }) {
23478
+ if (diff === void 0) return {
23479
+ header: `Pull for ${target.name}: no changes. The config matches the live schema.\n`,
23480
+ diff: ""
23481
+ };
23482
+ return {
23483
+ header: `${[
23484
+ colors.bold(`Pull for ${target.name} (project ${target.project.slice(0, 8)}… / ${target.environment})`),
23485
+ `config: ${config}`,
23486
+ "",
23487
+ "Live differs from the config.",
23488
+ "Both are printed the way export writes a config: find each change by its const.",
23489
+ ...full ? [] : ["Run with --full to see the whole config with the changes marked."],
23490
+ ""
23491
+ ].join("\n")}\n`,
23492
+ diff: `${diff.trimEnd().split("\n").map((line) => colorLine(line, colors)).join("\n")}\n`
23493
+ };
23494
+ }
23495
+ function colorLine(line, colors) {
23496
+ if (line.startsWith("---") || line.startsWith("+++")) return colors.bold(line);
23497
+ if (line.startsWith("@@")) return colors.cyan(line);
23498
+ if (line.startsWith("+")) return colors.green(line);
23499
+ if (line.startsWith("-")) return colors.red(line);
23500
+ return line;
23501
+ }
23502
+ //#endregion
22996
23503
  //#region src/commands/pull.ts
23504
+ /** What only pull can find out is wrong. The command prints it and exits 1. */
23505
+ var PullFailure = class extends Failure {};
22997
23506
  function registerPull(program) {
22998
- program.command("pull").description("report what changed live relative to the config").argument("[config]", "path to the config", "hygraph.config.ts").action(function() {
22999
- pull(this);
23000
- }).addHelpText("after", examples([["hygraph pull", "report drift against the default config"], ["hygraph pull brands/kaffa.ts", "report drift against another config"]]));
23507
+ program.command("pull").description("report what changed live relative to the config").argument("[config]", "path to the config", "hygraph.config.ts").option("-t, --target <name>", "pull only this target (repeatable, default: every target)", collect, []).option("--full", "print the whole config with the changes marked, not only the changes").option("--no-color", "print without colours").action(async function(config, options) {
23508
+ const output = this.configureOutput();
23509
+ const write = (text) => output.writeOut?.(text);
23510
+ const writeErr = (text) => output.writeErr?.(text);
23511
+ try {
23512
+ await pull(config, options, write, writeErr);
23513
+ } catch (error) {
23514
+ if (error instanceof Failure) this.error(`error: ${error.message}`, {
23515
+ exitCode: 1,
23516
+ code: "hygraph.pull"
23517
+ });
23518
+ throw error;
23519
+ }
23520
+ }).addHelpText("after", examples([
23521
+ ["hygraph pull", "report drift against the default config"],
23522
+ ["hygraph pull --target uk", "pull one target of several"],
23523
+ ["hygraph pull --full", "see each change among the lines around it"],
23524
+ ["hygraph pull brands/kaffa.ts", "report drift against another config"]
23525
+ ]));
23001
23526
  }
23002
- function pull(command) {
23003
- command.error("error: pull is not implemented yet", {
23004
- exitCode: 1,
23005
- code: "hygraph.notImplemented"
23527
+ /**
23528
+ * Pulls every selected target on its own, the way plan plans them: with
23529
+ * several, a failed target is reported and the rest are still pulled, and
23530
+ * the command fails at the end.
23531
+ */
23532
+ async function pull(config, options, write, writeErr) {
23533
+ const colors = import_picocolors.default.createColors(options.color && import_picocolors.default.isColorSupported && process.stdout.isTTY === true);
23534
+ const targets = await loadTargets(config, options.target, PullFailure);
23535
+ const full = options.full === true;
23536
+ if (targets.length === 1) {
23537
+ await pullTarget(targets[0], {
23538
+ config,
23539
+ colors,
23540
+ full,
23541
+ write,
23542
+ writeErr
23543
+ });
23544
+ return;
23545
+ }
23546
+ const outcomes = [];
23547
+ for (const target of targets) {
23548
+ writeErr(renderTargetHeading(target, colors));
23549
+ try {
23550
+ const diff = await pullTarget(target, {
23551
+ config,
23552
+ colors,
23553
+ full,
23554
+ write,
23555
+ writeErr
23556
+ });
23557
+ outcomes.push({
23558
+ name: target.name,
23559
+ ok: true,
23560
+ detail: diff === void 0 ? "no changes" : "differs from live"
23561
+ });
23562
+ } catch (error) {
23563
+ if (!(error instanceof Failure)) throw error;
23564
+ writeErr(`error: ${target.name}: ${error.message}\n`);
23565
+ outcomes.push({
23566
+ name: target.name,
23567
+ ok: false,
23568
+ detail: firstLine(error)
23569
+ });
23570
+ }
23571
+ }
23572
+ writeErr(renderTargetOutcomes(outcomes, colors));
23573
+ const failed = outcomes.filter(({ ok }) => !ok).length;
23574
+ if (failed > 0) throw new PullFailure(`${failed} of ${targets.length} targets could not be pulled`);
23575
+ }
23576
+ async function pullTarget(target, { config, colors, full, write, writeErr }) {
23577
+ const errors = validateEnvironment(target.apply).filter((validation) => validation.severity === "error");
23578
+ if (errors.length > 0) throw new PullFailure(`the config has ${errors.length === 1 ? "1 error" : `${errors.length} errors`}:\n\n${renderValidations(errors)}`);
23579
+ const { environment: live } = await readLiveEnvironment(target);
23580
+ const diff = await diffConfig(target, convertEnvironmentToIR(target.apply), live, { full });
23581
+ const rendered = renderPull(diff, {
23582
+ target,
23583
+ config,
23584
+ colors,
23585
+ full
23006
23586
  });
23587
+ writeErr(rendered.header);
23588
+ write(rendered.diff);
23589
+ return diff;
23007
23590
  }
23008
23591
  //#endregion
23009
23592
  //#region src/commands/validate.ts