@hygraph/cli 0.0.11 → 0.0.13

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 { Writable } from "node:stream";
13
14
  import { structuredPatch } from "diff";
14
15
  //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
15
16
  /**
@@ -3223,11 +3224,16 @@ const SchemaDefinitionDocument = new TypedDocumentString(`
3223
3224
  apiId
3224
3225
  __typename
3225
3226
  }
3227
+ systemModels: models(includeSystemModels: true) {
3228
+ apiId
3229
+ __typename
3230
+ }
3226
3231
  models(includeSystemModels: false) {
3227
3232
  apiId
3228
3233
  fields(includeHiddenFields: true, includeApiOnlyFields: true) {
3229
3234
  apiId
3230
3235
  ... on RelationalField {
3236
+ isVariantEnabled
3231
3237
  relationalFieldRules {
3232
3238
  connections {
3233
3239
  min
@@ -3754,12 +3760,16 @@ function isRename(change) {
3754
3760
  * value or a node is counted too, although Hygraph refuses it while entries
3755
3761
  * hold the value or a node of the subtree. A union
3756
3762
  * update that drops a member deletes that member's content, a union
3757
- * reference's update that drops a model deletes that model's field back, and
3758
- * a rich text update that drops an embedded model deletes the embeds of its
3759
- * entries.
3763
+ * reference's update that drops a model deletes that model's field back, a
3764
+ * rich text update that drops an embedded model deletes the embeds of its
3765
+ * entries, and turning a field's variants off deletes its variant values.
3760
3766
  */
3761
3767
  function isDestructive(change) {
3762
- return change.action === "delete" || dropsUnionMember(change) || dropsEmbed(change);
3768
+ return change.action === "delete" || dropsUnionMember(change) || dropsEmbed(change) || dropsVariants(change);
3769
+ }
3770
+ /** A field update that turns variants off: Hygraph deletes its variant values. */
3771
+ function dropsVariants(change) {
3772
+ return change.resource === "field" && change.action === "update" && change.kind !== "unsupported" && change.changes.variantEnabled?.to === false;
3763
3773
  }
3764
3774
  /**
3765
3775
  * An asset field update that makes it required. It is not destructive, but
@@ -5775,6 +5785,7 @@ function createSimpleField({ parent, migrationValue }, field) {
5775
5785
  isTitle: field.title,
5776
5786
  visibility: field.visibility,
5777
5787
  visibilityCondition: field.visibilityCondition,
5788
+ isVariantEnabled: field.variantEnabled,
5778
5789
  initialValue: jsonValue(field.initialValue),
5779
5790
  position: field.position
5780
5791
  };
@@ -5794,7 +5805,7 @@ function createSimpleField({ parent, migrationValue }, field) {
5794
5805
  }
5795
5806
  /** Only the attributes that change are sent. A rename is `newApiId`. */
5796
5807
  function updateSimpleField(change) {
5797
- const { apiId, formRenderer, displayName, description, required, unique, localized, title, visibility, visibilityCondition, initialValue, position, validations, slug, embeds, actions } = change.changes;
5808
+ const { apiId, formRenderer, displayName, description, required, unique, localized, title, visibility, visibilityCondition, variantEnabled, initialValue, position, validations, slug, embeds, actions } = change.changes;
5798
5809
  const input = {
5799
5810
  apiId: change.apiId,
5800
5811
  parentApiId: change.parent
@@ -5812,6 +5823,7 @@ function updateSimpleField(change) {
5812
5823
  if (title) input.isTitle = title.to;
5813
5824
  if (visibility) input.visibility = visibility.to;
5814
5825
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
5826
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5815
5827
  if (initialValue) input.initialValue = jsonValue(initialValue.to);
5816
5828
  if (position) input.position = position.to;
5817
5829
  if (validations) input.validations = validations.to === null ? null : validationsInput(change.kind, validations.to);
@@ -5841,6 +5853,7 @@ function createEnumerableField({ parent, migrationValue }, field) {
5841
5853
  isTitle: field.title,
5842
5854
  visibility: field.visibility,
5843
5855
  visibilityCondition: field.visibilityCondition,
5856
+ isVariantEnabled: field.variantEnabled,
5844
5857
  initialValue: jsonValue(field.initialValue),
5845
5858
  position: field.position
5846
5859
  };
@@ -5853,7 +5866,7 @@ function createEnumerableField({ parent, migrationValue }, field) {
5853
5866
  * creates the field instead.
5854
5867
  */
5855
5868
  function updateEnumerableField(change) {
5856
- const { apiId, displayName, description, required, unique, title, visibility, visibilityCondition, initialValue, position } = change.changes;
5869
+ const { apiId, displayName, description, required, unique, title, visibility, visibilityCondition, variantEnabled, initialValue, position } = change.changes;
5857
5870
  const input = {
5858
5871
  apiId: change.apiId,
5859
5872
  parentApiId: change.parent
@@ -5866,6 +5879,7 @@ function updateEnumerableField(change) {
5866
5879
  if (title) input.isTitle = title.to;
5867
5880
  if (visibility) input.visibility = visibility.to;
5868
5881
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
5882
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5869
5883
  if (initialValue) input.initialValue = jsonValue(initialValue.to);
5870
5884
  if (position) input.position = position.to;
5871
5885
  if (change.migrationValue !== void 0) input.migrationValue = enumerationMigrationValue(change.migrationValue);
@@ -5891,6 +5905,7 @@ function createTaxonomyField({ parent, migrationValue }, field) {
5891
5905
  isUnique: field.unique,
5892
5906
  visibility: field.visibility,
5893
5907
  visibilityCondition: field.visibilityCondition,
5908
+ isVariantEnabled: field.variantEnabled,
5894
5909
  initialValue: jsonValue(field.initialValue),
5895
5910
  position: field.position
5896
5911
  };
@@ -5903,7 +5918,7 @@ function createTaxonomyField({ parent, migrationValue }, field) {
5903
5918
  * instead.
5904
5919
  */
5905
5920
  function updateTaxonomyField(change) {
5906
- const { apiId, displayName, description, required, unique, visibility, visibilityCondition, initialValue, position } = change.changes;
5921
+ const { apiId, displayName, description, required, unique, visibility, visibilityCondition, variantEnabled, initialValue, position } = change.changes;
5907
5922
  const input = {
5908
5923
  apiId: change.apiId,
5909
5924
  parentApiId: change.parent
@@ -5915,6 +5930,7 @@ function updateTaxonomyField(change) {
5915
5930
  if (unique) input.isUnique = unique.to;
5916
5931
  if (visibility) input.visibility = visibility.to;
5917
5932
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
5933
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5918
5934
  if (initialValue) input.initialValue = jsonValue(initialValue.to);
5919
5935
  if (position) input.position = position.to;
5920
5936
  if (change.migrationValue !== void 0) input.migrationValue = taxonomyMigrationValue(change.migrationValue);
@@ -5939,6 +5955,7 @@ function createComponentField({ parent }, field) {
5939
5955
  isRequired: field.required,
5940
5956
  visibility: field.visibility,
5941
5957
  visibilityCondition: field.visibilityCondition,
5958
+ isVariantEnabled: field.variantEnabled,
5942
5959
  position: field.position
5943
5960
  };
5944
5961
  }
@@ -5948,7 +5965,7 @@ function createComponentField({ parent }, field) {
5948
5965
  * field instead.
5949
5966
  */
5950
5967
  function updateComponentField(change) {
5951
- const { apiId, displayName, description, required, visibility, visibilityCondition, position } = change.changes;
5968
+ const { apiId, displayName, description, required, visibility, visibilityCondition, variantEnabled, position } = change.changes;
5952
5969
  const input = {
5953
5970
  apiId: change.apiId,
5954
5971
  parentApiId: change.parent
@@ -5959,6 +5976,7 @@ function updateComponentField(change) {
5959
5976
  if (required) input.isRequired = required.to;
5960
5977
  if (visibility) input.visibility = visibility.to;
5961
5978
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
5979
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5962
5980
  if (position) input.position = position.to;
5963
5981
  return input;
5964
5982
  }
@@ -5973,6 +5991,7 @@ function createComponentUnionField({ parent }, field) {
5973
5991
  isList: field.list,
5974
5992
  visibility: field.visibility,
5975
5993
  visibilityCondition: field.visibilityCondition,
5994
+ isVariantEnabled: field.variantEnabled,
5976
5995
  position: field.position
5977
5996
  };
5978
5997
  }
@@ -5983,7 +6002,7 @@ function createComponentUnionField({ parent }, field) {
5983
6002
  * instead.
5984
6003
  */
5985
6004
  function updateComponentUnionField(change) {
5986
- const { apiId, displayName, description, components, visibilityCondition, position } = change.changes;
6005
+ const { apiId, displayName, description, components, visibilityCondition, variantEnabled, position } = change.changes;
5987
6006
  const input = {
5988
6007
  apiId: change.apiId,
5989
6008
  parentApiId: change.parent
@@ -5993,6 +6012,7 @@ function updateComponentUnionField(change) {
5993
6012
  if (description) input.description = description.to;
5994
6013
  if (components) input.componentApiIds = components.to;
5995
6014
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
6015
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
5996
6016
  if (position) input.position = position.to;
5997
6017
  return input;
5998
6018
  }
@@ -6025,6 +6045,7 @@ function createReferenceOneWayField({ parent }, field) {
6025
6045
  isList: field.list,
6026
6046
  visibility: field.visibility,
6027
6047
  visibilityCondition: field.visibilityCondition,
6048
+ isVariantEnabled: field.variantEnabled,
6028
6049
  relationalFieldRules: field.rules,
6029
6050
  position: field.position,
6030
6051
  reverseField: {
@@ -6054,6 +6075,7 @@ function createReferenceTwoWayField({ parent, partner }, field) {
6054
6075
  isList: field.list,
6055
6076
  visibility: field.visibility,
6056
6077
  visibilityCondition: field.visibilityCondition,
6078
+ isVariantEnabled: field.variantEnabled,
6057
6079
  relationalFieldRules: field.rules,
6058
6080
  position: field.position,
6059
6081
  reverseField: {
@@ -6088,6 +6110,7 @@ function createAssetField({ parent, partner }, field) {
6088
6110
  isRequired: field.required,
6089
6111
  visibility: field.visibility,
6090
6112
  visibilityCondition: field.visibilityCondition,
6113
+ isVariantEnabled: field.variantEnabled,
6091
6114
  position: field.position,
6092
6115
  reverseField: partner === void 0 ? {
6093
6116
  apiId: hidden,
@@ -6115,7 +6138,7 @@ function createAssetField({ parent, partner }, field) {
6115
6138
  * diff deletes and creates the field instead.
6116
6139
  */
6117
6140
  function updateRelationalField(change) {
6118
- const { apiId, displayName, description, required, visibility, visibilityCondition, position, rules } = change.changes;
6141
+ const { apiId, displayName, description, required, visibility, visibilityCondition, variantEnabled, position, rules } = change.changes;
6119
6142
  const input = {
6120
6143
  apiId: change.apiId,
6121
6144
  parentApiId: change.parent
@@ -6126,6 +6149,7 @@ function updateRelationalField(change) {
6126
6149
  if (required) input.isRequired = required.to;
6127
6150
  if (visibility) input.visibility = visibility.to;
6128
6151
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
6152
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
6129
6153
  if (position) input.position = position.to;
6130
6154
  if (rules) input.relationalFieldRules = rules.to;
6131
6155
  return input;
@@ -6157,6 +6181,7 @@ function createUnionField({ parent, members = [], memberName }, field) {
6157
6181
  isList: field.list,
6158
6182
  visibility: field.visibility,
6159
6183
  visibilityCondition: field.visibilityCondition,
6184
+ isVariantEnabled: field.variantEnabled,
6160
6185
  relationalFieldRules: field.rules,
6161
6186
  position: field.position,
6162
6187
  reverseField: first === void 0 ? { modelApiIds: field.to } : {
@@ -6180,7 +6205,7 @@ function createUnionField({ parent, members = [], memberName }, field) {
6180
6205
  * member's field only, a rename included.
6181
6206
  */
6182
6207
  function updateUnionField(change) {
6183
- const { apiId, displayName, description, visibility, visibilityCondition, position, rules, to } = change.changes;
6208
+ const { apiId, displayName, description, visibility, visibilityCondition, variantEnabled, position, rules, to } = change.changes;
6184
6209
  const input = {
6185
6210
  apiId: change.apiId,
6186
6211
  parentApiId: change.parent
@@ -6190,6 +6215,7 @@ function updateUnionField(change) {
6190
6215
  if (description) input.description = description.to;
6191
6216
  if (visibility) input.visibility = visibility.to;
6192
6217
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
6218
+ if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
6193
6219
  if (position) input.position = position.to;
6194
6220
  if (rules) input.relationalFieldRules = rules.to;
6195
6221
  if (to) input.reverseField = {
@@ -6814,7 +6840,12 @@ function renderFieldChange(change, width, colors) {
6814
6840
  case "update": {
6815
6841
  if (unsupportedFieldMove(change)) return [` ${colors.yellow(`~ ${op}`)} ${subject} ${colors.dim(change.type)}`, ...renderAttributes(change.changes, colors)];
6816
6842
  const { apiId, headers, args, ...attributes } = change.changes;
6817
- 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`)}` : "";
6843
+ const warning = [
6844
+ dropsUnionMember(change) && "deletes the content of the members it drops",
6845
+ dropsEmbed(change) && "deletes the embeds of the models it drops",
6846
+ dropsVariants(change) && "deletes the field's variant values",
6847
+ makesAssetRequired(change) && "API creates must set it; entries without an asset may fail to read"
6848
+ ].filter((text) => text !== false).map((text) => ` ${colors.yellow(`⚠ ${text}`)}`).join("");
6818
6849
  const rows = Object.entries(attributes).flatMap(([attribute, each]) => each === void 0 ? [] : [changeRow(attribute, each)]);
6819
6850
  if (headers) rows.push(keyedChanges("headers", headerEntries(headers.from), headerEntries(headers.to)));
6820
6851
  if (args) rows.push(keyedChanges("args", args.from.map((arg) => [arg.apiId, JSON.stringify(arg)]), args.to.map((arg) => [arg.apiId, JSON.stringify(arg)])));
@@ -12855,6 +12886,7 @@ const colorFieldSchema = strictObject({
12855
12886
  title: literal(false),
12856
12887
  visibility: fieldVisibilitySchema,
12857
12888
  visibilityCondition: visibilityConditionSchema.nullable(),
12889
+ variantEnabled: boolean(),
12858
12890
  initialValue: colorValueSchema,
12859
12891
  migrationValue: colorValueSchema,
12860
12892
  renamedFrom: string$1().nullable()
@@ -12879,6 +12911,7 @@ const locationFieldSchema = strictObject({
12879
12911
  title: literal(false),
12880
12912
  visibility: fieldVisibilitySchema,
12881
12913
  visibilityCondition: visibilityConditionSchema.nullable(),
12914
+ variantEnabled: boolean(),
12882
12915
  initialValue: locationValueSchema,
12883
12916
  migrationValue: locationValueSchema,
12884
12917
  renamedFrom: string$1().nullable()
@@ -12900,6 +12933,7 @@ const richTextFieldSchema = strictObject({
12900
12933
  title: literal(false),
12901
12934
  visibility: fieldVisibilitySchema,
12902
12935
  visibilityCondition: visibilityConditionSchema.nullable(),
12936
+ variantEnabled: boolean(),
12903
12937
  initialValue: richTextValuesSchema,
12904
12938
  migrationValue: richTextValuesSchema,
12905
12939
  embeds: array(custom((value) => typeof value === "function")).nullable(),
@@ -13280,7 +13314,8 @@ const fieldAttributes = {
13280
13314
  list: boolean(),
13281
13315
  required: boolean(),
13282
13316
  visibility: fieldVisibilitySchema,
13283
- visibilityCondition: visibilityConditionSchema.nullable()
13317
+ visibilityCondition: visibilityConditionSchema.nullable(),
13318
+ variantEnabled: boolean()
13284
13319
  };
13285
13320
  const stringFormRendererSchema = _enum([
13286
13321
  "GCMS_SINGLE_LINE",
@@ -13307,7 +13342,8 @@ const referenceUnionMemberFieldSchema$1 = strictObject({
13307
13342
  kind: literal("referenceUnionMember"),
13308
13343
  to: string$1(),
13309
13344
  reverse: string$1(),
13310
- required: literal(false)
13345
+ required: literal(false),
13346
+ variantEnabled: literal(false)
13311
13347
  });
13312
13348
  const remoteFieldArgSchema = strictObject({
13313
13349
  apiId: string$1(),
@@ -13316,6 +13352,21 @@ const remoteFieldArgSchema = strictObject({
13316
13352
  list: boolean()
13317
13353
  });
13318
13354
  const remoteFieldMethodSchema = _enum(["GET", "POST"]);
13355
+ const dateAttributes = {
13356
+ ...fieldAttributes,
13357
+ unique: boolean(),
13358
+ localized: boolean(),
13359
+ title: boolean(),
13360
+ initialValue: union([string$1(), array(string$1())]).nullable()
13361
+ };
13362
+ const numberAttributes = {
13363
+ ...fieldAttributes,
13364
+ unique: boolean(),
13365
+ localized: boolean(),
13366
+ title: boolean(),
13367
+ initialValue: union([number(), array(number())]).nullable(),
13368
+ validations: numberValidationRulesSchema.nullable()
13369
+ };
13319
13370
  const fieldSchema$1 = discriminatedUnion("kind", [
13320
13371
  strictObject({
13321
13372
  ...fieldAttributes,
@@ -13337,12 +13388,12 @@ const fieldSchema$1 = discriminatedUnion("kind", [
13337
13388
  slug: slugSettingsSchema.nullable()
13338
13389
  }),
13339
13390
  strictObject({
13340
- ...fieldAttributes,
13341
- kind: _enum(["date", "dateTime"]),
13342
- unique: boolean(),
13343
- localized: boolean(),
13344
- title: boolean(),
13345
- initialValue: union([string$1(), array(string$1())]).nullable()
13391
+ ...dateAttributes,
13392
+ kind: literal("date")
13393
+ }),
13394
+ strictObject({
13395
+ ...dateAttributes,
13396
+ kind: literal("dateTime")
13346
13397
  }),
13347
13398
  strictObject({
13348
13399
  ...fieldAttributes,
@@ -13361,13 +13412,12 @@ const fieldSchema$1 = discriminatedUnion("kind", [
13361
13412
  initialValue: union([string$1(), array(string$1())]).nullable()
13362
13413
  }),
13363
13414
  strictObject({
13364
- ...fieldAttributes,
13365
- kind: _enum(["int", "float"]),
13366
- unique: boolean(),
13367
- localized: boolean(),
13368
- title: boolean(),
13369
- initialValue: union([number(), array(number())]).nullable(),
13370
- validations: numberValidationRulesSchema.nullable()
13415
+ ...numberAttributes,
13416
+ kind: literal("int")
13417
+ }),
13418
+ strictObject({
13419
+ ...numberAttributes,
13420
+ kind: literal("float")
13371
13421
  }),
13372
13422
  strictObject({
13373
13423
  ...fieldAttributes,
@@ -13449,7 +13499,8 @@ const fieldSchema$1 = discriminatedUnion("kind", [
13449
13499
  forwardClientHeaders: boolean(),
13450
13500
  cacheTTLSeconds: number(),
13451
13501
  args: array(remoteFieldArgSchema),
13452
- visibilityCondition: _null()
13502
+ visibilityCondition: _null(),
13503
+ variantEnabled: literal(false)
13453
13504
  })
13454
13505
  ]);
13455
13506
  const fieldRefSchema = strictObject({
@@ -13518,6 +13569,7 @@ const changeSchema = discriminatedUnion("resource", [
13518
13569
  title: attributeChangeSchema(boolean()),
13519
13570
  visibility: attributeChangeSchema(fieldVisibilitySchema),
13520
13571
  visibilityCondition: attributeChangeSchema(visibilityConditionSchema.nullable()),
13572
+ variantEnabled: attributeChangeSchema(boolean()),
13521
13573
  initialValue: attributeChangeSchema(initialValueSchema),
13522
13574
  position: attributeChangeSchema(number()),
13523
13575
  validations: attributeChangeSchema(union([stringValidationRulesSchema$1, numberValidationRulesSchema]).nullable()),
@@ -13729,6 +13781,7 @@ const simpleFieldShape = {
13729
13781
  isUnique: boolean().nullish(),
13730
13782
  isLocalized: boolean().nullish(),
13731
13783
  isTitle: boolean().nullish(),
13784
+ isVariantEnabled: boolean().nullish(),
13732
13785
  visibility: fieldVisibilitySchema.nullish(),
13733
13786
  initialValue: string$1().nullish(),
13734
13787
  position: number(),
@@ -13744,6 +13797,7 @@ const createReferenceFieldSchema = object$1({
13744
13797
  description: string$1().nullish(),
13745
13798
  isList: boolean().nullish(),
13746
13799
  isRequired: boolean().nullish(),
13800
+ isVariantEnabled: boolean().nullish(),
13747
13801
  visibility: fieldVisibilitySchema.nullish(),
13748
13802
  position: number(),
13749
13803
  visibilityCondition: liveVisibilityConditionSchema.nullish(),
@@ -13762,6 +13816,7 @@ const createReferenceTwoWayFieldSchema = object$1({
13762
13816
  description: string$1().nullish(),
13763
13817
  isList: boolean().nullish(),
13764
13818
  isRequired: boolean().nullish(),
13819
+ isVariantEnabled: boolean().nullish(),
13765
13820
  visibility: fieldVisibilitySchema.nullish(),
13766
13821
  position: number(),
13767
13822
  visibilityCondition: liveVisibilityConditionSchema.nullish(),
@@ -13881,6 +13936,7 @@ function convertCreateAssetFieldToIR(input, components) {
13881
13936
  required: field.isRequired ?? false,
13882
13937
  visibility: field.visibility ?? "READ_WRITE",
13883
13938
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
13939
+ variantEnabled: field.isVariantEnabled ?? false,
13884
13940
  ...!oneWay && { reverse: field.reverseField.apiId }
13885
13941
  }
13886
13942
  };
@@ -13900,7 +13956,8 @@ function convertCreateAssetFieldToIR(input, components) {
13900
13956
  list: back.isList ?? true,
13901
13957
  required: false,
13902
13958
  visibility: back.visibility ?? "READ_WRITE",
13903
- visibilityCondition: null
13959
+ visibilityCondition: null,
13960
+ variantEnabled: false
13904
13961
  }
13905
13962
  }];
13906
13963
  }
@@ -13937,6 +13994,7 @@ function convertCreateBooleanFieldToIR(input) {
13937
13994
  title: field.isTitle ?? false,
13938
13995
  visibility: field.visibility ?? "READ_WRITE",
13939
13996
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
13997
+ variantEnabled: field.isVariantEnabled ?? false,
13940
13998
  initialValue: parseValue({
13941
13999
  apiId: field.apiId,
13942
14000
  list
@@ -13981,6 +14039,7 @@ function convertCreateColorFieldToIR(input) {
13981
14039
  title: false,
13982
14040
  visibility: field.visibility ?? "READ_WRITE",
13983
14041
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14042
+ variantEnabled: field.isVariantEnabled ?? false,
13984
14043
  initialValue: parseValue({
13985
14044
  apiId: field.apiId,
13986
14045
  list
@@ -14023,6 +14082,7 @@ const baseShape = {
14023
14082
  displayName: string$1(),
14024
14083
  description: string$1().nullish(),
14025
14084
  isList: boolean().nullish(),
14085
+ isVariantEnabled: boolean().nullish(),
14026
14086
  visibility: fieldVisibilitySchema.nullish(),
14027
14087
  position: number(),
14028
14088
  visibilityCondition: liveVisibilityConditionSchema.nullish()
@@ -14076,7 +14136,8 @@ function attributes$3(field) {
14076
14136
  position: field.position,
14077
14137
  list: field.isList ?? false,
14078
14138
  visibility: field.visibility ?? "READ_WRITE",
14079
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
14139
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14140
+ variantEnabled: field.isVariantEnabled ?? false
14080
14141
  };
14081
14142
  }
14082
14143
  //#endregion
@@ -14112,6 +14173,7 @@ function convertCreateDateFieldToIR(input) {
14112
14173
  title: field.isTitle ?? false,
14113
14174
  visibility: field.visibility ?? "READ_WRITE",
14114
14175
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14176
+ variantEnabled: field.isVariantEnabled ?? false,
14115
14177
  initialValue: parseValue({
14116
14178
  apiId: field.apiId,
14117
14179
  list
@@ -14188,6 +14250,7 @@ function convertCreateEnumerableFieldToIR(input) {
14188
14250
  title: field.isTitle ?? false,
14189
14251
  visibility: field.visibility ?? "READ_WRITE",
14190
14252
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14253
+ variantEnabled: field.isVariantEnabled ?? false,
14191
14254
  initialValue: parseValue({
14192
14255
  apiId: field.apiId,
14193
14256
  list
@@ -14232,6 +14295,7 @@ function convertCreateJsonFieldToIR(input) {
14232
14295
  title: false,
14233
14296
  visibility: field.visibility ?? "READ_WRITE",
14234
14297
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14298
+ variantEnabled: field.isVariantEnabled ?? false,
14235
14299
  initialValue: parseValue({
14236
14300
  apiId: field.apiId,
14237
14301
  list
@@ -14276,6 +14340,7 @@ function convertCreateLocationFieldToIR(input) {
14276
14340
  title: false,
14277
14341
  visibility: field.visibility ?? "READ_WRITE",
14278
14342
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14343
+ variantEnabled: field.isVariantEnabled ?? false,
14279
14344
  initialValue: parseValue({
14280
14345
  apiId: field.apiId,
14281
14346
  list
@@ -14352,6 +14417,7 @@ function convertCreateNumberFieldToIR(input) {
14352
14417
  title: field.isTitle ?? false,
14353
14418
  visibility: field.visibility ?? "READ_WRITE",
14354
14419
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14420
+ variantEnabled: field.isVariantEnabled ?? false,
14355
14421
  initialValue: parseValue({
14356
14422
  apiId: field.apiId,
14357
14423
  list
@@ -14401,7 +14467,8 @@ function convertCreateReferenceOneWayFieldToIR(input, models) {
14401
14467
  list: field.isList ?? false,
14402
14468
  required: false,
14403
14469
  visibility: field.visibility ?? "READ_WRITE",
14404
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
14470
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14471
+ variantEnabled: field.isVariantEnabled ?? false
14405
14472
  }
14406
14473
  };
14407
14474
  }
@@ -14437,7 +14504,8 @@ function convertCreateReferenceTwoWayFieldToIR(input, models, partners) {
14437
14504
  list: field.isList ?? false,
14438
14505
  required: false,
14439
14506
  visibility: field.visibility ?? "READ_WRITE",
14440
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
14507
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14508
+ variantEnabled: field.isVariantEnabled ?? false
14441
14509
  }
14442
14510
  }, {
14443
14511
  parentApiId: reverse.modelApiId,
@@ -14453,7 +14521,8 @@ function convertCreateReferenceTwoWayFieldToIR(input, models, partners) {
14453
14521
  list: reverse.isList ?? false,
14454
14522
  required: false,
14455
14523
  visibility: reverse.visibility ?? "READ_WRITE",
14456
- visibilityCondition: convertVisibilityCondition(partner?.visibilityCondition)
14524
+ visibilityCondition: convertVisibilityCondition(partner?.visibilityCondition),
14525
+ variantEnabled: partner?.isVariantEnabled ?? false
14457
14526
  }
14458
14527
  }];
14459
14528
  }
@@ -14516,6 +14585,7 @@ function convertCreateRemoteFieldToIR(input) {
14516
14585
  required: field.isRequired ?? false,
14517
14586
  visibility: field.visibility ?? "READ_WRITE",
14518
14587
  visibilityCondition: null,
14588
+ variantEnabled: false,
14519
14589
  source: config.remoteSourcePrefix,
14520
14590
  type: field.type,
14521
14591
  returnType: config.returnTypeApiId,
@@ -14679,6 +14749,7 @@ function convertCreateRichTextFieldToIR(input, models) {
14679
14749
  title: false,
14680
14750
  visibility: field.visibility ?? "READ_WRITE",
14681
14751
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14752
+ variantEnabled: field.isVariantEnabled ?? false,
14682
14753
  initialValue: isEmptyRichText(initialValue) ? null : initialValue,
14683
14754
  embeds: field.embedsEnabled === true ? (field.embeddableModels ?? []).toSorted() : null,
14684
14755
  actions: richTextActions(field.formConfig?.actions ?? null)
@@ -14781,6 +14852,7 @@ function convertCreateStringFieldToIR(input) {
14781
14852
  title: field.isTitle ?? false,
14782
14853
  visibility: field.visibility ?? "READ_WRITE",
14783
14854
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14855
+ variantEnabled: field.isVariantEnabled ?? false,
14784
14856
  initialValue: parseValue({
14785
14857
  apiId: field.apiId,
14786
14858
  list
@@ -14896,6 +14968,7 @@ function convertCreateTaxonomyFieldToIR(input) {
14896
14968
  unique: field.isUnique ?? false,
14897
14969
  visibility: field.visibility ?? "READ_WRITE",
14898
14970
  visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
14971
+ variantEnabled: field.isVariantEnabled ?? false,
14899
14972
  initialValue: parseValue({
14900
14973
  apiId: field.apiId,
14901
14974
  list
@@ -14915,6 +14988,7 @@ const createReferenceUnionFieldSchema = object$1({
14915
14988
  displayName: string$1(),
14916
14989
  description: string$1().nullish(),
14917
14990
  isList: boolean().nullish(),
14991
+ isVariantEnabled: boolean().nullish(),
14918
14992
  visibility: fieldVisibilitySchema.nullish(),
14919
14993
  position: number(),
14920
14994
  visibilityCondition: liveVisibilityConditionSchema.nullish(),
@@ -14984,7 +15058,8 @@ function convertCreateReferenceUnionFieldToIR(input, models, components, lookup)
14984
15058
  list: field.isList ?? false,
14985
15059
  required: false,
14986
15060
  visibility: field.visibility ?? "READ_WRITE",
14987
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
15061
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
15062
+ variantEnabled: field.isVariantEnabled ?? false
14988
15063
  }
14989
15064
  };
14990
15065
  if (!onModel) return [owner];
@@ -15007,7 +15082,8 @@ function convertCreateReferenceUnionFieldToIR(input, models, components, lookup)
15007
15082
  list: member.isList,
15008
15083
  required: false,
15009
15084
  visibility: member.visibility,
15010
- visibilityCondition: convertVisibilityCondition(member.visibilityCondition)
15085
+ visibilityCondition: convertVisibilityCondition(member.visibilityCondition),
15086
+ variantEnabled: false
15011
15087
  }
15012
15088
  });
15013
15089
  }
@@ -15200,9 +15276,11 @@ function parse$2(operation, schema, input) {
15200
15276
  * reference there; the other side of any other relation on Asset is an
15201
15277
  * unsupported field. Fields on QueryModel, remote fields only, go on
15202
15278
  * `query` the same way, which is there and exported with no fields too.
15203
- * Every other op, `createLocale` and `createStage`
15204
- * included, and fields on anything but a model, a component, Asset or
15205
- * QueryModel, are skipped until the IR has a place for them. A two-way
15279
+ * Fields on Segment go on `segment`, there only with fields: whether live
15280
+ * has Segment without them is `readLiveEnvironment`'s to say. Every other op,
15281
+ * `createLocale` and `createStage` included, and fields on anything but a
15282
+ * model, a component, Asset, QueryModel or Segment, are skipped until the
15283
+ * IR has a place for them. A two-way
15206
15284
  * relation's other side takes its rules and condition from `partners`,
15207
15285
  * which `schemaDefinition` leaves out, and a union's members
15208
15286
  * their apiIds and settings from `unions`: `schemaDefinition` gives the
@@ -15230,7 +15308,12 @@ function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map(),
15230
15308
  apiId: "QueryModel",
15231
15309
  fields: {}
15232
15310
  };
15311
+ const segment = {
15312
+ apiId: "Segment",
15313
+ fields: {}
15314
+ };
15233
15315
  const parents = new Map([
15316
+ [segment.apiId, segment],
15234
15317
  ...[...models, ...components].map((parent) => [parent.apiId, parent]),
15235
15318
  [asset.apiId, asset],
15236
15319
  [query.apiId, query]
@@ -15290,12 +15373,13 @@ function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map(),
15290
15373
  components: components.toSorted(byApiId$1),
15291
15374
  models: models.toSorted(byApiId$1),
15292
15375
  asset,
15293
- query
15376
+ query,
15377
+ ...Object.keys(segment.fields).length > 0 && { segment }
15294
15378
  };
15295
15379
  }
15296
15380
  /**
15297
- * Puts the field on its model, component, Asset or QueryModel. A field on
15298
- * anything else is skipped.
15381
+ * Puts the field on its model, component, Asset, QueryModel or Segment. A
15382
+ * field on anything else is skipped.
15299
15383
  */
15300
15384
  function addField(parents, live) {
15301
15385
  const parent = parents.get(live.parentApiId);
@@ -15389,10 +15473,10 @@ var LiveSchemaFailure = class extends Failure {};
15389
15473
  * locales and stages come from the same request's `contentModel`, and a
15390
15474
  * two-way relation's other side without its rules and condition, and a
15391
15475
  * union's members with the first one's settings, so they come from its
15392
- * `models`.
15476
+ * `models`. Whether Segment exists comes from its system models.
15393
15477
  */
15394
15478
  async function readLiveEnvironment(target, fetch) {
15395
- if (isEmpty(target.token)) throw new LiveSchemaFailure(`target "${target.name}" has no token`);
15479
+ if (isEmpty(target.token)) throw new LiveSchemaFailure(`target "${target.name}" has no token. An exported config reads it from HYGRAPH_TOKEN.`);
15396
15480
  const client = createManagementClient({
15397
15481
  endpoint: target.endpoint,
15398
15482
  token: target.token,
@@ -15406,7 +15490,8 @@ async function readLiveEnvironment(target, fetch) {
15406
15490
  }
15407
15491
  const { environment } = extractProject(result.viewer, target);
15408
15492
  const unions = unionLookup(environment.contentModel.models);
15409
- const live = convertSchemaDefinitionToIR(environment.schemaDefinition, partnerLookup(environment.contentModel.models), unions);
15493
+ const { segment, ...live } = convertSchemaDefinitionToIR(environment.schemaDefinition, partnerLookup(environment.contentModel.models), unions);
15494
+ const hasSegment = environment.contentModel.systemModels.some((model) => model.__typename === "SegmentModel");
15410
15495
  const components = new Set(environment.contentModel.components.map(({ apiId }) => apiId));
15411
15496
  return {
15412
15497
  environmentId: environment.id,
@@ -15416,6 +15501,10 @@ async function readLiveEnvironment(target, fetch) {
15416
15501
  locales: convertLocalesToIR(environment.contentModel.locales),
15417
15502
  stages: convertStagesToIR(environment.contentModel.stages),
15418
15503
  ...live,
15504
+ ...hasSegment && { segment: segment ?? {
15505
+ apiId: "Segment",
15506
+ fields: {}
15507
+ } },
15419
15508
  components: live.components.filter(({ apiId }) => components.has(apiId))
15420
15509
  }
15421
15510
  };
@@ -15424,7 +15513,8 @@ async function readLiveEnvironment(target, fetch) {
15424
15513
  function partnerLookup(models) {
15425
15514
  return new Map(models.flatMap((model) => model.fields.flatMap((field) => field.__typename === "RelationalField" ? [[`${model.apiId}.${field.apiId}`, {
15426
15515
  relationalFieldRules: field.relationalFieldRules,
15427
- visibilityCondition: liveCondition(field.visibilityCondition)
15516
+ visibilityCondition: liveCondition(field.visibilityCondition),
15517
+ isVariantEnabled: field.isVariantEnabled
15428
15518
  }]] : [])));
15429
15519
  }
15430
15520
  /** Every union's id, and every union member's settings, by `Model.field`. */
@@ -15739,6 +15829,12 @@ const messages = {
15739
15829
  ["model.apiIdReserved"]: (apiId) => `"${apiId}" is the apiId of a model Hygraph provides.`,
15740
15830
  ["systemModel.duplicate"]: (call) => `${call} is listed more than once in models.`,
15741
15831
  ["systemModel.fieldRequired"]: (apiId, field) => `Field "${field}" on ${apiId} is required. Hygraph refuses a required field on a model it provides.`,
15832
+ ["systemModel.fieldVariantEnabled"]: (apiId, field) => `Field "${field}" on ${apiId} has variants. Only fields of your models can have them.`,
15833
+ ["systemModel.fieldApiIdTaken"]: (apiId, field) => `Field "${field}" on ${apiId} has the apiId of one of Hygraph's own fields on ${apiId}.`,
15834
+ ["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.`,
15835
+ ["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.",
15836
+ ["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.",
15837
+ ["systemModel.fieldLocalized"]: (apiId, field) => `Field "${field}" on ${apiId} is localized. Fields on ${apiId} have one value for every locale.`,
15742
15838
  ["systemModel.fieldUnion"]: (apiId, field) => `Field "${field}" on ${apiId} is a component union. Hygraph refuses one on a model it provides.`,
15743
15839
  ["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.`,
15744
15840
  ["systemModel.fieldNotRemote"]: (field) => `Field "${field}" on Query is not a remote field. Hygraph takes only remote fields on Query.`,
@@ -15875,6 +15971,11 @@ const messages = {
15875
15971
  ["field.referenceUnionMemberOnComponent"]: (field) => `Field "${field}" is a union member on a component. Only models have them.`,
15876
15972
  ["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.`,
15877
15973
  ["field.requiredNotVisible"]: (field, visibility) => `Field "${field}" is required and ${visibility}, so editors cannot fill it in.`,
15974
+ ["field.variantEnabledUnique"]: (field) => `Field "${field}" is unique and has variants. Hygraph refuses variants on a unique field.`,
15975
+ ["field.variantEnabledOnComponent"]: (field, component) => `Field "${field}" on component "${component}" has variants. Only fields of a model can have them.`,
15976
+ ["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.`,
15977
+ ["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.`,
15978
+ ["field.variantEnabledBothSides"]: (field, partner) => `Field "${field}" and its partner "${partner}" both have variants. Only one side of a two-way reference can have them.`,
15878
15979
  ["field.assetReverseInvalid"]: (field, reverse) => `Field "${field}" gets the field "${reverse}" on Asset, which is not a valid apiId.`,
15879
15980
  ["field.richTextEmbedsEmpty"]: (field) => `Field "${field}" has embeds, but names no model to embed.`,
15880
15981
  ["field.richTextEmbedDuplicate"]: (field, model) => `Field "${field}" lists model "${model}" more than once in embeds.`,
@@ -15884,8 +15985,8 @@ const messages = {
15884
15985
  ["field.richTextRequiredList"]: (field) => `Field "${field}" is a required list, which Hygraph refuses on rich text.`,
15885
15986
  ["field.assetReverseFieldMissing"]: (parent, field) => `Asset field "${field}" on ${parent} does not name its field back on Asset.`,
15886
15987
  ["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.`,
15887
- ["field.assetSystemAssetMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} has its field back "${back}" on Asset, and models does not list system.asset.`,
15888
- ["field.assetFieldBackMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} names its field back "${back}", which system.asset does not list.`,
15988
+ ["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.`,
15989
+ ["field.assetFieldBackMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} names its field back "${back}", which system.model.asset does not list.`,
15889
15990
  ["field.assetFieldBackPartner"]: (back, partner, problem) => `Field back "${back}" on Asset names ${partner}, which ${problem}.`,
15890
15991
  ["field.assetReverseFieldNotOnAsset"]: (parent, field) => `Field "${field}" on ${parent} is an assetReverseField. A field back is on Asset only.`,
15891
15992
  ["field.assetReverseFieldChanged"]: (parent, field, from, to) => `Asset field "${field}" on ${parent} has the field back "${from}" on Asset, and the config names "${to}".`,
@@ -15938,9 +16039,15 @@ const fixes = {
15938
16039
  ["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.",
15939
16040
  ["model.renamedFromMatchesApiId"]: "Set renamedFrom to the apiId the model has in Hygraph right now, or remove it.",
15940
16041
  ["model.noTitleField"]: "Set title: true on the field Studio should show entries by, such as a name or a heading.",
15941
- ["model.apiIdReserved"]: "Use another apiId. To add fields to Asset or Query, put system.asset({ fields }) or system.query({ fields }) in models.",
16042
+ ["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.",
15942
16043
  ["systemModel.duplicate"]: "List it once, with all your fields on it.",
15943
16044
  ["systemModel.fieldRequired"]: "Set required: false.",
16045
+ ["systemModel.fieldVariantEnabled"]: "Set variantEnabled: false.",
16046
+ ["systemModel.fieldType"]: "Use one of the types it takes, or put the field on a model of yours.",
16047
+ ["systemModel.fieldApiIdTaken"]: "Use another apiId. Hygraph's own fields are never listed in fields.",
16048
+ ["systemModel.fieldLocalized"]: "Set localized: false.",
16049
+ ["systemModel.segmentNotYet"]: "Set variantEnabled: true on a field of one of your models, or remove system.model.segment() from models until one has variants.",
16050
+ ["systemModel.segmentMissing"]: "Set variantEnabled: true on a field of one of your models, or leave Segment's fields out until one has variants.",
15944
16051
  ["systemModel.fieldUnion"]: "Use a component field, or put the union on a model of yours.",
15945
16052
  ["systemModel.fieldReferenceTwoWay"]: "Use define.field.assetReverseField with the same apiId, displayName, to and reverse, and no list or rules.",
15946
16053
  ["systemModel.fieldNotRemote"]: "Use define.field.remote, or put the field on a model of yours.",
@@ -16077,6 +16184,11 @@ const fixes = {
16077
16184
  ["field.referenceUnionMemberOnComponent"]: "Move the union reference and its field back to models, or remove the field back.",
16078
16185
  ["field.unionOwnerMissing"]: "Add this model to the union's to and set its reverse to this field's apiId, or remove this field.",
16079
16186
  ["field.requiredNotVisible"]: "Set required: false, or make the field READ_WRITE or READ_ONLY.",
16187
+ ["field.variantEnabledUnique"]: "Set unique: false or variantEnabled: false.",
16188
+ ["field.variantEnabledOnComponent"]: "Set variantEnabled: false, or move the field to a model.",
16189
+ ["field.variantEnabledBaseField"]: "Set variantEnabled: true on the field the condition is on, or variantEnabled: false on this one.",
16190
+ ["field.variantEnabledBothSides"]: "Set variantEnabled: false on one of the two.",
16191
+ ["field.variantComponentRequired"]: "Fill in the component in each existing variant after the apply.",
16080
16192
  ["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.",
16081
16193
  ["field.richTextEmbedsEmpty"]: "List at least one model in embeds, or remove embeds to turn them off.",
16082
16194
  ["field.richTextEmbedDuplicate"]: "List each model once in embeds.",
@@ -16084,13 +16196,13 @@ const fixes = {
16084
16196
  ["field.richTextEmbedComponent"]: "List only models in embeds. To hold a component, use define.field.component.",
16085
16197
  ["field.richTextUniqueEmbeds"]: "Remove unique, or remove embeds.",
16086
16198
  ["field.richTextRequiredList"]: "Remove required, or set list: false.",
16087
- ["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)}.`,
16199
+ ["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)}.`,
16088
16200
  ["field.assetReverseFieldOnComponent"]: "Remove reverse.",
16089
- ["field.assetSystemAssetMissing"]: (parent, field, back) => `Add const Asset = system.asset({ fields: [${fieldBack(parent, field, back)}] }) to models.`,
16090
- ["field.assetFieldBackMissing"]: (parent, field, back) => `Add ${fieldBack(parent, field, back)} to system.asset's fields, at the end for a new field.`,
16201
+ ["field.assetSystemAssetMissing"]: (parent, field, back) => `Add const Asset = system.model.asset({ fields: [${fieldBack(parent, field, back)}] }) to models.`,
16202
+ ["field.assetFieldBackMissing"]: (parent, field, back) => `Add ${fieldBack(parent, field, back)} to system.model.asset's fields, at the end for a new field.`,
16091
16203
  ["field.assetFieldBackPartner"]: "Point it at the asset field that names it in reverse: to is that field's model, and reverse is its apiId.",
16092
- ["field.assetReverseFieldNotOnAsset"]: "Move it to system.asset's fields, or use define.field.referenceTwoWay on a model.",
16093
- ["field.assetReverseFieldChanged"]: (_parent, _field, from) => `To rename the field back, set renamedFrom: "${from}" on it in system.asset. Otherwise set reverse back to "${from}".`,
16204
+ ["field.assetReverseFieldNotOnAsset"]: "Move it to system.model.asset's fields, or use define.field.referenceTwoWay on a model.",
16205
+ ["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}".`,
16094
16206
  ["change.modelMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a model from one place only.",
16095
16207
  ["change.embedsReplaced"]: "Create the new models in one apply. Then change embeds and delete the old models in the next.",
16096
16208
  ["change.componentMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a component from one place only.",
@@ -16553,6 +16665,7 @@ function validateReferenceModelReferences(parent, fields, models) {
16553
16665
  * is this field. Hygraph makes both in one create, so a pair the config
16554
16666
  * gives only half of, or two halves that disagree, has nothing to create.
16555
16667
  * A `to` the environment does not have is `field.referenceModelMissing`.
16668
+ * Only one side of a pair can have variants.
16556
16669
  */
16557
16670
  function validateReferenceTwoWayPartners(parent, fields, models) {
16558
16671
  const validations = [];
@@ -16592,6 +16705,9 @@ function validateReferenceTwoWayPartners(parent, fields, models) {
16592
16705
  if (partnerTarget !== `${parent.apiId}.${field.apiId}`) {
16593
16706
  const code = "field.referencePartnerMismatch";
16594
16707
  report(code, field.apiId, "reverse", messages[code](field.apiId, partnerName, partnerTarget));
16708
+ } else if (field.variantEnabled && partner.variantEnabled && `${parent.apiId}.${field.apiId}` < partnerName) {
16709
+ const code = "field.variantEnabledBothSides";
16710
+ report(code, field.apiId, "variantEnabled", messages[code](field.apiId, partnerName));
16595
16711
  }
16596
16712
  }
16597
16713
  return validations;
@@ -17451,7 +17567,8 @@ function validateTypeOptions(parent, field) {
17451
17567
  /**
17452
17568
  * A condition's base must be another field of the same model that holds one
17453
17569
  * value, and Studio does not let a required, a hidden or an API-only field
17454
- * have one. The server checks none of this; Studio's form does.
17570
+ * have one. The server checks none of this; Studio's form does. A field
17571
+ * with variants needs a base with variants, which the server checks.
17455
17572
  */
17456
17573
  function validateConditions(parent, fields) {
17457
17574
  const byApiId = new Map(fields.map((field) => [field.apiId, field]));
@@ -17491,6 +17608,13 @@ function validateConditions(parent, fields) {
17491
17608
  fix: fixes["field.conditionBaseList"]
17492
17609
  });
17493
17610
  else validations.push(...validateConditionValue(parent, field, base));
17611
+ if (field.variantEnabled && isConditionBase(base) && !base.variantEnabled) validations.push({
17612
+ code: "field.variantEnabledBaseField",
17613
+ severity: "error",
17614
+ path: fieldPath(parent, field.apiId, "variantEnabled"),
17615
+ message: messages["field.variantEnabledBaseField"](field.apiId, condition.baseField),
17616
+ fix: fixes["field.variantEnabledBaseField"]
17617
+ });
17494
17618
  if (field.visibility === "HIDDEN" || field.visibility === "API_ONLY") validations.push({
17495
17619
  code: "field.conditionNotVisible",
17496
17620
  severity: "error",
@@ -17548,6 +17672,8 @@ function validateOptions(parent, field) {
17548
17672
  });
17549
17673
  };
17550
17674
  if (field.required && (field.visibility === "HIDDEN" || field.visibility === "API_ONLY")) report("field.requiredNotVisible", "required", messages["field.requiredNotVisible"](field.apiId, field.visibility));
17675
+ if (field.variantEnabled && "unique" in field && field.unique) report("field.variantEnabledUnique", "variantEnabled", messages["field.variantEnabledUnique"](field.apiId));
17676
+ if (field.variantEnabled && parent.kind === "component") report("field.variantEnabledOnComponent", "variantEnabled", messages["field.variantEnabledOnComponent"](field.apiId, parent.apiId));
17551
17677
  const title = "title" in field && field.title;
17552
17678
  if (title && field.list) report("field.titleOnList", "title", messages["field.titleOnList"](field.apiId));
17553
17679
  if (title && (field.visibility === "HIDDEN" || field.visibility === "API_ONLY")) report("field.titleNotVisible", "title", messages["field.titleNotVisible"](field.apiId, field.visibility));
@@ -17567,9 +17693,10 @@ function validateOptions(parent, field) {
17567
17693
  /**
17568
17694
  * What Asset can tell about itself: its fields, as a model's are checked,
17569
17695
  * and what Hygraph refuses on a model it provides. A required field and a
17570
- * component union fail the whole migration. A two-way reference on Asset
17571
- * is a field back, which `assetReverseField` declares. There is no title
17572
- * check: Studio shows assets by their file.
17696
+ * component union fail the whole migration. Studio does not let a field
17697
+ * on Asset have variants. A two-way reference on Asset is a field back,
17698
+ * which `assetReverseField` declares. There is no title check: Studio
17699
+ * shows assets by their file.
17573
17700
  */
17574
17701
  function validateSystemAsset(asset) {
17575
17702
  const parent = {
@@ -17577,33 +17704,45 @@ function validateSystemAsset(asset) {
17577
17704
  apiId: asset.apiId
17578
17705
  };
17579
17706
  const validations = validateFields(parent, asset.fields);
17580
- for (const field of asset.fields) if (field.__typename === "ComponentUnionField") {
17581
- const code = "systemModel.fieldUnion";
17582
- validations.push({
17583
- code,
17584
- severity: "error",
17585
- path: fieldPath(parent, field.apiId, "components"),
17586
- message: messages[code](asset.apiId, field.apiId),
17587
- fix: fixes[code]
17588
- });
17589
- } else if (field.__typename === "ReferenceTwoWayField") {
17590
- const code = "systemModel.fieldReferenceTwoWay";
17591
- validations.push({
17592
- code,
17593
- severity: "error",
17594
- path: fieldPath(parent, field.apiId, "to"),
17595
- message: messages[code](asset.apiId, field.apiId),
17596
- fix: fixes[code]
17597
- });
17598
- } else if (field.__typename !== "UnsupportedField" && field.required) {
17599
- const code = "systemModel.fieldRequired";
17600
- validations.push({
17601
- code,
17602
- severity: "error",
17603
- path: fieldPath(parent, field.apiId, "required"),
17604
- message: messages[code](asset.apiId, field.apiId),
17605
- fix: fixes[code]
17606
- });
17707
+ for (const field of asset.fields) {
17708
+ if (field.__typename === "ComponentUnionField") {
17709
+ const code = "systemModel.fieldUnion";
17710
+ validations.push({
17711
+ code,
17712
+ severity: "error",
17713
+ path: fieldPath(parent, field.apiId, "components"),
17714
+ message: messages[code](asset.apiId, field.apiId),
17715
+ fix: fixes[code]
17716
+ });
17717
+ } else if (field.__typename === "ReferenceTwoWayField") {
17718
+ const code = "systemModel.fieldReferenceTwoWay";
17719
+ validations.push({
17720
+ code,
17721
+ severity: "error",
17722
+ path: fieldPath(parent, field.apiId, "to"),
17723
+ message: messages[code](asset.apiId, field.apiId),
17724
+ fix: fixes[code]
17725
+ });
17726
+ } else if (field.__typename !== "UnsupportedField" && field.required) {
17727
+ const code = "systemModel.fieldRequired";
17728
+ validations.push({
17729
+ code,
17730
+ severity: "error",
17731
+ path: fieldPath(parent, field.apiId, "required"),
17732
+ message: messages[code](asset.apiId, field.apiId),
17733
+ fix: fixes[code]
17734
+ });
17735
+ }
17736
+ if (field.__typename !== "UnsupportedField" && field.variantEnabled) {
17737
+ const code = "systemModel.fieldVariantEnabled";
17738
+ validations.push({
17739
+ code,
17740
+ severity: "error",
17741
+ path: fieldPath(parent, field.apiId, "variantEnabled"),
17742
+ message: messages[code](asset.apiId, field.apiId),
17743
+ fix: fixes[code]
17744
+ });
17745
+ }
17607
17746
  }
17608
17747
  return validations;
17609
17748
  }
@@ -17637,6 +17776,66 @@ function validateSystemQuery(query) {
17637
17776
  return validations;
17638
17777
  }
17639
17778
  //#endregion
17779
+ //#region src/define/system/segment.validation.ts
17780
+ /**
17781
+ * The field types Segment takes. Keyed by `SegmentModelField`'s, so the
17782
+ * compiler refuses a type missing here or one it does not take.
17783
+ */
17784
+ const SEGMENT_FIELD_TYPES = {
17785
+ BooleanField: true,
17786
+ SingleLineField: true,
17787
+ MultilineField: true,
17788
+ MarkdownField: true,
17789
+ SlugField: true,
17790
+ RichTextField: true,
17791
+ IntField: true,
17792
+ FloatField: true,
17793
+ DateField: true,
17794
+ DateTimeField: true,
17795
+ JsonField: true,
17796
+ ColorField: true,
17797
+ LocationField: true,
17798
+ EnumerationField: true,
17799
+ TaxonomyField: true,
17800
+ UnsupportedField: true
17801
+ };
17802
+ /** Hygraph's own fields on Segment, which yours cannot take the apiIds of. */
17803
+ const SEGMENT_OWN_FIELDS = /* @__PURE__ */ new Set(["name", "description"]);
17804
+ /**
17805
+ * What Segment can tell about itself: its fields, as a model's are
17806
+ * checked, and what Hygraph refuses on it. The server refuses a union and
17807
+ * a required field but for a taxonomy field, which this refuses too;
17808
+ * Studio offers no other type, a localized field or variants. There is no title check: Hygraph's name field is the title.
17809
+ */
17810
+ function validateSystemSegment(segment) {
17811
+ const parent = {
17812
+ kind: "model",
17813
+ apiId: segment.apiId
17814
+ };
17815
+ const validations = validateFields(parent, segment.fields);
17816
+ const report = (code, field, attribute) => {
17817
+ validations.push({
17818
+ code,
17819
+ severity: "error",
17820
+ path: fieldPath(parent, field.apiId, attribute),
17821
+ message: messages[code](segment.apiId, field.apiId),
17822
+ fix: fixes[code]
17823
+ });
17824
+ };
17825
+ for (const field of segment.fields) {
17826
+ if (SEGMENT_OWN_FIELDS.has(field.apiId)) report("systemModel.fieldApiIdTaken", field, "apiId");
17827
+ if (!Object.hasOwn(SEGMENT_FIELD_TYPES, field.__typename)) {
17828
+ report("systemModel.fieldType", field, "apiId");
17829
+ continue;
17830
+ }
17831
+ if (field.__typename === "UnsupportedField") continue;
17832
+ if (field.required) report("systemModel.fieldRequired", field, "required");
17833
+ if ("localized" in field && field.localized) report("systemModel.fieldLocalized", field, "localized");
17834
+ if (field.variantEnabled) report("systemModel.fieldVariantEnabled", field, "variantEnabled");
17835
+ }
17836
+ return validations;
17837
+ }
17838
+ //#endregion
17640
17839
  //#region src/define/resources/component.validation.ts
17641
17840
  /**
17642
17841
  * What a component can tell about itself, its fields included. Whether its
@@ -18188,8 +18387,9 @@ function nodePath(taxonomy, node) {
18188
18387
  //#region src/define/resources/environment.validation.ts
18189
18388
  /** The call that lists each model Hygraph provides, as the config writes it. */
18190
18389
  const SYSTEM_MODEL_CALLS = {
18191
- SystemAsset: "system.asset()",
18192
- SystemQuery: "system.query()"
18390
+ SystemAsset: "system.model.asset()",
18391
+ SystemQuery: "system.model.query()",
18392
+ SystemSegment: "system.model.segment()"
18193
18393
  };
18194
18394
  /**
18195
18395
  * What only the whole environment can tell: whether two resources collide,
@@ -18199,10 +18399,11 @@ const SYSTEM_MODEL_CALLS = {
18199
18399
  * by prefix. Models, components, enumerations and
18200
18400
  * taxonomies share one apiId namespace; locales and stages each have their
18201
18401
  * own. Display names are unique per kind. `Asset`, `QueryModel` and
18202
- * `Query` are Hygraph's: a model of yours cannot take any of them, and
18203
- * `system.asset` and `system.query` are listed once each. An asset field
18402
+ * `Query` are Hygraph's: a model of yours cannot take any of them. Nor
18403
+ * can it take `Segment` once Hygraph needs its own: when `system.model.segment`
18404
+ * is listed or a field has variants. Each `system.*` model is listed once. An asset field
18204
18405
  * on a model or on Asset names its field back on Asset, which
18205
- * `system.asset` lists as an `assetReverseField`.
18406
+ * `system.model.asset` lists as an `assetReverseField`.
18206
18407
  *
18207
18408
  * Runs over the models as declared, before conversion, so every report
18208
18409
  * points at the config the user wrote.
@@ -18215,7 +18416,7 @@ function validateEnvironment(environment) {
18215
18416
  validations.push(...validateStages(environment.stages));
18216
18417
  const systemApiIds = /* @__PURE__ */ new Set();
18217
18418
  for (const model of environment.systemModels) {
18218
- validations.push(...model.__typename === "SystemAsset" ? validateSystemAsset(model) : validateSystemQuery(model));
18419
+ validations.push(...validateSystemModel(model));
18219
18420
  if (systemApiIds.has(model.apiId)) {
18220
18421
  const code = "systemModel.duplicate";
18221
18422
  validations.push({
@@ -18228,13 +18429,14 @@ function validateEnvironment(environment) {
18228
18429
  }
18229
18430
  systemApiIds.add(model.apiId);
18230
18431
  }
18432
+ const needsSegment = environment.systemModels.some((model) => model.__typename === "SystemSegment") || environment.models.some((model) => model.fields.some((field) => field.__typename !== "UnsupportedField" && field.variantEnabled));
18231
18433
  for (const model of environment.models) {
18232
18434
  validations.push(...validateModel(model));
18233
18435
  if ([
18234
18436
  "Asset",
18235
18437
  "QueryModel",
18236
18438
  "Query"
18237
- ].includes(model.apiId)) {
18439
+ ].includes(model.apiId) || model.apiId === "Segment" && needsSegment) {
18238
18440
  const code = "model.apiIdReserved";
18239
18441
  validations.push({
18240
18442
  code,
@@ -18397,6 +18599,13 @@ function validateEnvironment(environment) {
18397
18599
  }
18398
18600
  return validations;
18399
18601
  }
18602
+ function validateSystemModel(model) {
18603
+ switch (model.__typename) {
18604
+ case "SystemAsset": return validateSystemAsset(model);
18605
+ case "SystemQuery": return validateSystemQuery(model);
18606
+ case "SystemSegment": return validateSystemSegment(model);
18607
+ }
18608
+ }
18400
18609
  //#endregion
18401
18610
  //#region src/diff/resources/component.ts
18402
18611
  /**
@@ -18881,13 +19090,49 @@ function diffFields(from, to, migrationValues = /* @__PURE__ */ new Map(), pairs
18881
19090
  const move = moveUnsupportedField(parent, fromField, field, afterDeletes);
18882
19091
  if (move) changes.updates.push(move);
18883
19092
  }
18884
- changes.updates = changes.updates.toSorted(byApiId$1);
19093
+ changes.updates = variantsInOrder(changes.updates.toSorted(byApiId$1), fromFields, to.fields);
18885
19094
  return changes;
18886
19095
  }
18887
19096
  /**
18888
- * The rules and condition of a two-way side its partner's create makes, as
18889
- * an update after the creates: the create takes neither for the partner.
18890
- * `null` when it has neither.
19097
+ * The updates with a condition's base field turning variants on before
19098
+ * the fields whose condition names it, and turning them off after: the
19099
+ * server refuses a field with variants whose base has none. Otherwise in
19100
+ * the order given.
19101
+ */
19102
+ function variantsInOrder(updates, from, to) {
19103
+ const turning = (on) => new Set(updates.flatMap((update) => update.kind !== "unsupported" && update.changes.variantEnabled?.to === on ? [update.apiId] : []));
19104
+ const on = turning(true);
19105
+ const off = turning(false);
19106
+ const before = /* @__PURE__ */ new Map();
19107
+ const runsFirst = (apiId, first) => before.set(apiId, [...before.get(apiId) ?? [], first]);
19108
+ for (const update of updates) {
19109
+ const fromBase = conditionBase(from[update.apiId]);
19110
+ const toBase = conditionBase(to[update.apiId]);
19111
+ if (fromBase !== void 0 && off.has(fromBase)) runsFirst(fromBase, update.apiId);
19112
+ if (toBase !== void 0 && on.has(toBase)) runsFirst(update.apiId, toBase);
19113
+ }
19114
+ const byApiId = new Map(updates.map((update) => [update.apiId, update]));
19115
+ const ordered = [];
19116
+ const visiting = /* @__PURE__ */ new Set();
19117
+ const visit = (update) => {
19118
+ if (ordered.includes(update) || visiting.has(update.apiId)) return;
19119
+ visiting.add(update.apiId);
19120
+ for (const apiId of before.get(update.apiId) ?? []) {
19121
+ const first = byApiId.get(apiId);
19122
+ if (first) visit(first);
19123
+ }
19124
+ ordered.push(update);
19125
+ };
19126
+ updates.forEach(visit);
19127
+ return ordered;
19128
+ }
19129
+ function conditionBase(field) {
19130
+ return field === void 0 || field.kind === "unsupported" ? void 0 : field.visibilityCondition?.baseField;
19131
+ }
19132
+ /**
19133
+ * The rules, condition and variants of a two-way side its partner's create
19134
+ * makes, as an update after the creates: the create takes none of them for
19135
+ * the partner. `null` when it has none.
18891
19136
  */
18892
19137
  function partnerSettings(parent, field) {
18893
19138
  if (field.kind !== "referenceTwoWay") return null;
@@ -18900,6 +19145,10 @@ function partnerSettings(parent, field) {
18900
19145
  from: null,
18901
19146
  to: field.visibilityCondition
18902
19147
  };
19148
+ if (field.variantEnabled) changes.variantEnabled = {
19149
+ from: false,
19150
+ to: true
19151
+ };
18903
19152
  return Object.keys(changes).length === 0 ? null : {
18904
19153
  action: "update",
18905
19154
  resource: "field",
@@ -19062,6 +19311,10 @@ function diffField(from, to) {
19062
19311
  from: from.visibilityCondition,
19063
19312
  to: to.visibilityCondition
19064
19313
  };
19314
+ if (from.variantEnabled !== to.variantEnabled) changes.variantEnabled = {
19315
+ from: from.variantEnabled,
19316
+ to: to.variantEnabled
19317
+ };
19065
19318
  if (from.kind === "componentUnion" && to.kind === "componentUnion" && hashJSON(from.components) !== hashJSON(to.components)) changes.components = {
19066
19319
  from: from.components,
19067
19320
  to: to.components
@@ -19638,6 +19891,15 @@ function diffEnvironment({ from, to, intents = {
19638
19891
  });
19639
19892
  }
19640
19893
  if (to.query) pushFields(renamed.query ?? null, to.query);
19894
+ const segmentCreates = [];
19895
+ const segmentConditions = [];
19896
+ if (to.segment) {
19897
+ const creates = fieldCreates.length;
19898
+ const conditions = fieldConditions.length;
19899
+ pushFields(renamed.segment ?? null, to.segment);
19900
+ segmentCreates.push(...fieldCreates.splice(creates));
19901
+ segmentConditions.push(...fieldConditions.splice(conditions));
19902
+ }
19641
19903
  const fromComponents = new Map(renamed.components.map((component) => [component.apiId, component]));
19642
19904
  const toComponentApiIds = new Set(to.components.map((component) => component.apiId));
19643
19905
  const deletedComponents = renamed.components.filter((component) => !toComponentApiIds.has(component.apiId));
@@ -19715,6 +19977,8 @@ function diffEnvironment({ from, to, intents = {
19715
19977
  ...fieldCreates.map((change) => withFieldBack(change, to)),
19716
19978
  ...memberAdds,
19717
19979
  ...fieldConditions,
19980
+ ...segmentCreates,
19981
+ ...segmentConditions,
19718
19982
  ...embeds.afterModelCreates
19719
19983
  ];
19720
19984
  }
@@ -19732,7 +19996,9 @@ function diffEnvironment({ from, to, intents = {
19732
19996
  * Both places keep a move right: positions count after the field deletes,
19733
19997
  * and the model deletes renumber no other model's fields. A field whose
19734
19998
  * embeds were all deleted and that embeds a created model goes after the
19735
- * creates, which `validateChangeSet` refuses.
19999
+ * creates, which `validateChangeSet` refuses. A moved update's variants
20000
+ * stay in an update of their own among the field updates, in the order
20001
+ * `variantsInOrder` gave them.
19736
20002
  */
19737
20003
  function orderEmbeds(changes, deleted, created) {
19738
20004
  const order = {
@@ -19741,10 +20007,31 @@ function orderEmbeds(changes, deleted, created) {
19741
20007
  afterModelCreates: []
19742
20008
  };
19743
20009
  for (const change of changes) {
19744
- const embeds = change.resource === "field" && change.action === "update" && change.kind === "richText" ? change.changes.embeds : void 0;
19745
- if ((embeds?.to ?? []).some((apiId) => created.has(apiId))) order.afterModelCreates.push(change);
19746
- else if ((embeds?.from ?? []).some((apiId) => deleted.has(apiId))) order.beforeModelDeletes.push(change);
19747
- else order.updates.push(change);
20010
+ if (change.resource !== "field" || change.action !== "update" || change.kind !== "richText") {
20011
+ order.updates.push(change);
20012
+ continue;
20013
+ }
20014
+ const { embeds, variantEnabled, ...rest } = change.changes;
20015
+ const moveTo = (embeds?.to ?? []).some((apiId) => created.has(apiId)) ? order.afterModelCreates : (embeds?.from ?? []).some((apiId) => deleted.has(apiId)) ? order.beforeModelDeletes : void 0;
20016
+ if (moveTo === void 0) order.updates.push(change);
20017
+ else if (variantEnabled === void 0) moveTo.push(change);
20018
+ else {
20019
+ moveTo.push({
20020
+ ...change,
20021
+ changes: {
20022
+ ...rest,
20023
+ embeds
20024
+ }
20025
+ });
20026
+ order.updates.push({
20027
+ action: "update",
20028
+ resource: "field",
20029
+ parent: change.parent,
20030
+ apiId: change.apiId,
20031
+ kind: change.kind,
20032
+ changes: { variantEnabled }
20033
+ });
20034
+ }
19748
20035
  }
19749
20036
  return order;
19750
20037
  }
@@ -20057,7 +20344,7 @@ function applyEnumerationValueRenames(from, intents) {
20057
20344
  renames
20058
20345
  };
20059
20346
  }
20060
- /** Every model, component and Asset with `map` applied to each of its fields. */
20347
+ /** Every model, component, Asset and Segment with `map` applied to each of its fields. */
20061
20348
  function mapFields(from, map) {
20062
20349
  const mapParent = (parent) => ({
20063
20350
  ...parent,
@@ -20066,7 +20353,8 @@ function mapFields(from, map) {
20066
20353
  return {
20067
20354
  models: from.models.map(mapParent),
20068
20355
  components: from.components.map(mapParent),
20069
- ...from.asset && { asset: mapParent(from.asset) }
20356
+ ...from.asset && { asset: mapParent(from.asset) },
20357
+ ...from.segment && { segment: mapParent(from.segment) }
20070
20358
  };
20071
20359
  }
20072
20360
  /**
@@ -20227,7 +20515,8 @@ function applyFieldRenames(from, intents) {
20227
20515
  ...from,
20228
20516
  models: from.models.map(renameFields),
20229
20517
  components: from.components.map(renameFields),
20230
- ...from.asset && { asset: renameFields(from.asset) }
20518
+ ...from.asset && { asset: renameFields(from.asset) },
20519
+ ...from.segment && { segment: renameFields(from.segment) }
20231
20520
  };
20232
20521
  const parents = mapFields(renamed, (field) => {
20233
20522
  switch (field.kind) {
@@ -20710,6 +20999,10 @@ function validateUnsupportedFields({ from, to, intents, unsupportedPairs = [], u
20710
20999
  kind: "model",
20711
21000
  parent: to.query
20712
21001
  }] : [],
21002
+ ...to.segment ? [{
21003
+ kind: "model",
21004
+ parent: to.segment
21005
+ }] : [],
20713
21006
  ...to.components.map((parent) => ({
20714
21007
  kind: "component",
20715
21008
  parent
@@ -20887,6 +21180,10 @@ function liveParent(from, intents, parent) {
20887
21180
  ["QueryModel", from.query ?? {
20888
21181
  apiId: "QueryModel",
20889
21182
  fields: {}
21183
+ }],
21184
+ ["Segment", from.segment ?? {
21185
+ apiId: "Segment",
21186
+ fields: {}
20890
21187
  }]
20891
21188
  ]);
20892
21189
  const rename = intents.renames.find((each) => (each.resource === "model" || each.resource === "component") && each.apiId === parent);
@@ -20894,6 +21191,52 @@ function liveParent(from, intents, parent) {
20894
21191
  return parents.get(parent);
20895
21192
  }
20896
21193
  /**
21194
+ * Hygraph adds Segment with the first field that has variants, and keeps
21195
+ * it. Live without Segment has no such field yet, so one of your models
21196
+ * needs one in this plan. Without it, your fields on Segment are an error,
21197
+ * and Segment listed without fields, which plans nothing, a warning.
21198
+ */
21199
+ function validateSegment({ from, to }) {
21200
+ 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 [];
21201
+ const empty = Object.keys(to.segment.fields).length === 0;
21202
+ const code = empty ? "systemModel.segmentNotYet" : "systemModel.segmentMissing";
21203
+ return [{
21204
+ code,
21205
+ severity: empty ? "warning" : "error",
21206
+ path: ["models", "Segment"],
21207
+ message: messages[code],
21208
+ fix: fixes[code]
21209
+ }];
21210
+ }
21211
+ /**
21212
+ * A component field that becomes required with variants, by either change.
21213
+ * Hygraph copies a required field's values into the variants of existing
21214
+ * entries, but not a component's, so those variants start without it.
21215
+ * The field and its model are looked up live under the apiIds they have
21216
+ * before the plan's renames.
21217
+ */
21218
+ function validateVariantComponents({ from, to, intents }) {
21219
+ return to.models.flatMap((model) => Object.values(model.fields).flatMap((field) => {
21220
+ const rename = intents.fieldRenames.find((each) => each.parent === model.apiId && each.apiId === field.apiId);
21221
+ const fields = liveParent(from, intents, model.apiId)?.fields ?? {};
21222
+ const before = fields[field.apiId] ?? (rename === void 0 ? void 0 : fields[rename.renamedFrom]);
21223
+ if (field.kind !== "component" || !field.required || !field.variantEnabled || before?.kind !== "component" || before.required && before.variantEnabled) return [];
21224
+ const code = "field.variantComponentRequired";
21225
+ return [{
21226
+ code,
21227
+ severity: "warning",
21228
+ path: [
21229
+ "models",
21230
+ model.apiId,
21231
+ "fields",
21232
+ field.apiId
21233
+ ],
21234
+ message: messages[code](model.apiId, field.apiId),
21235
+ fix: fixes[code]
21236
+ }];
21237
+ }));
21238
+ }
21239
+ /**
20897
21240
  * Whether every change can be applied at its point of the migration. Plays
20898
21241
  * the change set through in order against `from`: a delete or update needs
20899
21242
  * its locale, model, component or enumeration to still exist, a create or
@@ -20910,6 +21253,7 @@ function validateChangeSet({ from, changes }) {
20910
21253
  const models = new Map(from.models.map((model) => [model.apiId, model]));
20911
21254
  const components = new Map(from.components.map((component) => [component.apiId, component]));
20912
21255
  const componentApiIds = new Set(components.keys());
21256
+ let segment = from.segment !== void 0;
20913
21257
  const enumerations = new Map(from.enumerations.map((enumeration) => [enumeration.apiId, enumeration]));
20914
21258
  const taxonomies = new Map(from.taxonomies.map((taxonomy) => [taxonomy.apiId, {
20915
21259
  apiId: taxonomy.apiId,
@@ -21005,7 +21349,8 @@ function validateChangeSet({ from, changes }) {
21005
21349
  validateComponentsUsed(change);
21006
21350
  validateModelReferenced(change);
21007
21351
  validateModelsEmbedded(change);
21008
- if (change.parent === "Asset" || change.parent === "QueryModel" || models.has(change.parent) || components.has(change.parent)) break;
21352
+ if (turnsVariantsOn(change) && models.has(change.parent)) segment = true;
21353
+ if (change.parent === "Asset" || change.parent === "QueryModel" || change.parent === "Segment" && segment || models.has(change.parent) || components.has(change.parent)) break;
21009
21354
  const onComponent = componentApiIds.has(change.parent);
21010
21355
  report(onComponent ? "change.componentMissing" : "change.modelMissing", [
21011
21356
  onComponent ? "components" : "models",
@@ -21282,6 +21627,10 @@ function applyUpdate(model, change) {
21282
21627
  function text(entry, params) {
21283
21628
  return typeof entry === "string" ? entry : entry(...params);
21284
21629
  }
21630
+ /** A field create or update that gives the field variants. */
21631
+ function turnsVariantsOn(change) {
21632
+ return change.action === "create" ? change.field.variantEnabled : change.action === "update" && change.kind !== "unsupported" && change.changes.variantEnabled?.to === true;
21633
+ }
21285
21634
  //#endregion
21286
21635
  //#region src/validations/render.ts
21287
21636
  /**
@@ -21307,6 +21656,7 @@ const assetFieldSchema = strictObject({
21307
21656
  required: boolean(),
21308
21657
  visibility: fieldVisibilitySchema,
21309
21658
  visibilityCondition: visibilityConditionSchema.nullable(),
21659
+ variantEnabled: boolean(),
21310
21660
  reverse: string$1().nullable(),
21311
21661
  renamedFrom: string$1().nullable()
21312
21662
  });
@@ -21323,6 +21673,7 @@ const assetReverseFieldSchema = strictObject({
21323
21673
  required: literal(false),
21324
21674
  visibility: fieldVisibilitySchema,
21325
21675
  visibilityCondition: _null(),
21676
+ variantEnabled: literal(false),
21326
21677
  renamedFrom: string$1().nullable()
21327
21678
  });
21328
21679
  //#endregion
@@ -21339,6 +21690,7 @@ const booleanFieldSchema = strictObject({
21339
21690
  title: boolean(),
21340
21691
  visibility: fieldVisibilitySchema,
21341
21692
  visibilityCondition: visibilityConditionSchema.nullable(),
21693
+ variantEnabled: boolean(),
21342
21694
  initialValue: union([boolean(), array(boolean())]).nullable(),
21343
21695
  migrationValue: union([boolean(), array(boolean())]).nullable(),
21344
21696
  renamedFrom: string$1().nullable()
@@ -21357,6 +21709,7 @@ const componentFieldSchema = strictObject({
21357
21709
  required: boolean(),
21358
21710
  visibility: fieldVisibilitySchema,
21359
21711
  visibilityCondition: visibilityConditionSchema.nullable(),
21712
+ variantEnabled: boolean(),
21360
21713
  renamedFrom: string$1().nullable()
21361
21714
  });
21362
21715
  const componentUnionFieldSchema = strictObject({
@@ -21369,6 +21722,7 @@ const componentUnionFieldSchema = strictObject({
21369
21722
  required: literal(false),
21370
21723
  visibility: fieldVisibilitySchema,
21371
21724
  visibilityCondition: visibilityConditionSchema.nullable(),
21725
+ variantEnabled: boolean(),
21372
21726
  renamedFrom: string$1().nullable()
21373
21727
  });
21374
21728
  //#endregion
@@ -21386,6 +21740,7 @@ const dateFieldShape = {
21386
21740
  title: boolean(),
21387
21741
  visibility: fieldVisibilitySchema,
21388
21742
  visibilityCondition: visibilityConditionSchema.nullable(),
21743
+ variantEnabled: boolean(),
21389
21744
  initialValue: dateValueSchema,
21390
21745
  migrationValue: dateValueSchema,
21391
21746
  renamedFrom: string$1().nullable()
@@ -21428,6 +21783,7 @@ const enumerationFieldSchema = strictObject({
21428
21783
  title: boolean(),
21429
21784
  visibility: fieldVisibilitySchema,
21430
21785
  visibilityCondition: visibilityConditionSchema.nullable(),
21786
+ variantEnabled: boolean(),
21431
21787
  initialValue: enumerationValueSchema,
21432
21788
  migrationValue: enumerationValueSchema,
21433
21789
  renamedFrom: string$1().nullable()
@@ -21447,6 +21803,7 @@ const jsonFieldSchema = strictObject({
21447
21803
  title: literal(false),
21448
21804
  visibility: fieldVisibilitySchema,
21449
21805
  visibilityCondition: visibilityConditionSchema.nullable(),
21806
+ variantEnabled: boolean(),
21450
21807
  initialValue: jsonValueSchema,
21451
21808
  migrationValue: jsonValueSchema,
21452
21809
  renamedFrom: string$1().nullable()
@@ -21474,6 +21831,7 @@ const numberFieldShape = {
21474
21831
  title: boolean(),
21475
21832
  visibility: fieldVisibilitySchema,
21476
21833
  visibilityCondition: visibilityConditionSchema.nullable(),
21834
+ variantEnabled: boolean(),
21477
21835
  initialValue: numberValueSchema,
21478
21836
  migrationValue: numberValueSchema,
21479
21837
  validations: strictObject({
@@ -21507,6 +21865,7 @@ const referenceOneWayFieldSchema = strictObject({
21507
21865
  }) }).nullable(),
21508
21866
  visibility: fieldVisibilitySchema,
21509
21867
  visibilityCondition: visibilityConditionSchema.nullable(),
21868
+ variantEnabled: boolean(),
21510
21869
  renamedFrom: string$1().nullable()
21511
21870
  });
21512
21871
  //#endregion
@@ -21527,6 +21886,7 @@ const referenceTwoWayFieldSchema = strictObject({
21527
21886
  }) }).nullable(),
21528
21887
  visibility: fieldVisibilitySchema,
21529
21888
  visibilityCondition: visibilityConditionSchema.nullable(),
21889
+ variantEnabled: boolean(),
21530
21890
  renamedFrom: string$1().nullable()
21531
21891
  });
21532
21892
  //#endregion
@@ -21547,6 +21907,7 @@ const referenceUnionFieldSchema = strictObject({
21547
21907
  }) }).nullable(),
21548
21908
  visibility: fieldVisibilitySchema,
21549
21909
  visibilityCondition: visibilityConditionSchema.nullable(),
21910
+ variantEnabled: boolean(),
21550
21911
  renamedFrom: string$1().nullable()
21551
21912
  });
21552
21913
  //#endregion
@@ -21562,6 +21923,7 @@ const referenceUnionMemberFieldSchema = strictObject({
21562
21923
  required: literal(false),
21563
21924
  visibility: fieldVisibilitySchema,
21564
21925
  visibilityCondition: visibilityConditionSchema.nullable(),
21926
+ variantEnabled: literal(false),
21565
21927
  renamedFrom: string$1().nullable()
21566
21928
  });
21567
21929
  //#endregion
@@ -21631,6 +21993,7 @@ const remoteFieldSchema = strictObject({
21631
21993
  required: boolean(),
21632
21994
  visibility: fieldVisibilitySchema,
21633
21995
  visibilityCondition: _null(),
21996
+ variantEnabled: literal(false),
21634
21997
  renamedFrom: string$1().nullable()
21635
21998
  });
21636
21999
  //#endregion
@@ -21663,6 +22026,7 @@ const stringFieldShape = {
21663
22026
  title: boolean(),
21664
22027
  visibility: fieldVisibilitySchema,
21665
22028
  visibilityCondition: visibilityConditionSchema.nullable(),
22029
+ variantEnabled: boolean(),
21666
22030
  initialValue: textValueSchema,
21667
22031
  migrationValue: textValueSchema,
21668
22032
  validations: stringValidationRulesSchema.nullable(),
@@ -21732,6 +22096,7 @@ const fieldSchema = discriminatedUnion("__typename", [
21732
22096
  unique: boolean(),
21733
22097
  visibility: fieldVisibilitySchema,
21734
22098
  visibilityCondition: visibilityConditionSchema.nullable(),
22099
+ variantEnabled: boolean(),
21735
22100
  initialValue: taxonomyValueSchema,
21736
22101
  migrationValue: taxonomyValueSchema,
21737
22102
  renamedFrom: string$1().nullable()
@@ -21770,6 +22135,13 @@ const systemQuerySchema = strictObject({
21770
22135
  fields: array(fieldSchema)
21771
22136
  });
21772
22137
  //#endregion
22138
+ //#region src/define/system/segment.zod.ts
22139
+ const systemSegmentSchema = strictObject({
22140
+ __typename: literal("SystemSegment"),
22141
+ apiId: literal("Segment"),
22142
+ fields: array(fieldSchema)
22143
+ });
22144
+ //#endregion
21773
22145
  //#region src/define/resources/component.zod.ts
21774
22146
  const componentSchema = strictObject({
21775
22147
  __typename: literal("Component"),
@@ -21812,7 +22184,11 @@ const environmentSchema = strictObject({
21812
22184
  remoteSources: array(remoteSourceSchema),
21813
22185
  components: array(componentSchema),
21814
22186
  models: array(modelSchema),
21815
- systemModels: array(union([systemAssetSchema, systemQuerySchema]))
22187
+ systemModels: array(union([
22188
+ systemAssetSchema,
22189
+ systemQuerySchema,
22190
+ systemSegmentSchema
22191
+ ]))
21816
22192
  });
21817
22193
  //#endregion
21818
22194
  //#region src/define/resources/target.zod.ts
@@ -22064,6 +22440,11 @@ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
22064
22440
  to: desired,
22065
22441
  intents
22066
22442
  }), `the fields back on Asset do not match the asset fields,`);
22443
+ const segmentValidations = validateSegment({
22444
+ from: live,
22445
+ to: desired
22446
+ });
22447
+ maybeRefuse(segmentValidations, `Segment's fields cannot be planned against ${target.environment},`);
22067
22448
  const diffed = diffEnvironment({
22068
22449
  from: live,
22069
22450
  to: desired,
@@ -22090,7 +22471,15 @@ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
22090
22471
  }),
22091
22472
  environmentId,
22092
22473
  secretValues: secretValues(desired, secrets),
22093
- warnings: [...configValidations.filter((validation) => validation.severity === "warning"), ...warnings]
22474
+ warnings: [
22475
+ ...[...configValidations, ...segmentValidations].filter((validation) => validation.severity === "warning"),
22476
+ ...validateVariantComponents({
22477
+ from: live,
22478
+ to: desired,
22479
+ intents
22480
+ }),
22481
+ ...warnings
22482
+ ]
22094
22483
  };
22095
22484
  }
22096
22485
  /** Below the plan: what is worth a look but does not stop it. */
@@ -22235,7 +22624,7 @@ async function prepare(target, { config, options, colors, planFiles, write }) {
22235
22624
  const file = planFiles?.get(target.name);
22236
22625
  const artifact = file === void 0 ? void 0 : readPlanFile(file);
22237
22626
  if (artifact !== void 0) refuseUnsendableOAuthSecrets(unmaskSecrets(artifact.changes, oAuthSecretValues(oAuthSecrets(target.apply))));
22238
- const { plan: fresh, environmentId, secretValues } = await computePlan(target, void 0, { rotateSecrets: artifact ? sentOAuthSecrets(artifact.changes) : options.rotateSecret });
22627
+ const { plan: fresh, environmentId, secretValues, warnings } = await computePlan(target, void 0, { rotateSecrets: artifact ? sentOAuthSecrets(artifact.changes) : options.rotateSecret });
22239
22628
  let plan = fresh;
22240
22629
  if (file !== void 0 && artifact !== void 0) {
22241
22630
  const refusals = verifyPlan(artifact, fresh);
@@ -22251,6 +22640,7 @@ async function prepare(target, { config, options, colors, planFiles, write }) {
22251
22640
  config,
22252
22641
  colors
22253
22642
  }));
22643
+ if (warnings.length > 0) write(renderWarnings(warnings, colors));
22254
22644
  if (plan.changes.length === 0) return;
22255
22645
  if (plan.summary.destructive > 0 && options.prune !== true) throw new ApplyRefusal(renderDestructiveRefusal(plan.summary, colors));
22256
22646
  refuseUnsendableOAuthSecrets(unmaskSecrets(plan.changes, secretValues));
@@ -22628,6 +23018,7 @@ function fieldOptions(field, defaults) {
22628
23018
  ["title", !("title" in field) || field.title === defaults.title ? void 0 : String(field.title)],
22629
23019
  ["visibility", field.visibility === defaults.visibility ? void 0 : string(field.visibility)],
22630
23020
  ["visibilityCondition", field.visibilityCondition === null ? void 0 : printCondition(field.visibilityCondition)],
23021
+ ["variantEnabled", field.variantEnabled === defaults.variantEnabled ? void 0 : String(field.variantEnabled)],
22631
23022
  ["initialValue", field.initialValue === null ? void 0 : JSON.stringify(field.initialValue)]
22632
23023
  ];
22633
23024
  }
@@ -22646,7 +23037,8 @@ function referenceOptions(field, referenced) {
22646
23037
  ["list", field.list === FIELD_DEFAULTS.list ? void 0 : String(field.list)],
22647
23038
  ["required", field.required === FIELD_DEFAULTS.required ? void 0 : String(field.required)],
22648
23039
  ["visibility", field.visibility === FIELD_DEFAULTS.visibility ? void 0 : string(field.visibility)],
22649
- ["visibilityCondition", field.visibilityCondition === null ? void 0 : printCondition(field.visibilityCondition)]
23040
+ ["visibilityCondition", field.visibilityCondition === null ? void 0 : printCondition(field.visibilityCondition)],
23041
+ ["variantEnabled", field.variantEnabled === FIELD_DEFAULTS.variantEnabled ? void 0 : String(field.variantEnabled)]
22650
23042
  ];
22651
23043
  }
22652
23044
  /** A condition with the value its base field's type takes. */
@@ -22800,17 +23192,33 @@ function printStage(stage) {
22800
23192
  }
22801
23193
  //#endregion
22802
23194
  //#region src/export/resources/system.ts
22803
- /** `const Asset = system.asset({ fields: [...] });`, your fields only. */
23195
+ /** `const Asset = system.model.asset({ fields: [...] });`, your fields only. */
22804
23196
  function printSystemAsset(asset) {
22805
- return `const Asset = system.asset(${object([["fields", printFields(asset.apiId, asset.fields, printAssetModelField)]])});`;
23197
+ return `const Asset = system.model.asset(${object([["fields", printFields(asset.apiId, asset.fields, printAssetModelField)]])});`;
22806
23198
  }
22807
23199
  /**
22808
- * `const Query = system.query({ fields: [...] });`. Its remote fields read
23200
+ * `const Query = system.model.query({ fields: [...] });`. Its remote fields read
22809
23201
  * their headers as `QUERY_<FIELD>_<HEADER>`, after the name Studio shows.
22810
23202
  */
22811
23203
  function printSystemQuery(query) {
22812
- return `const Query = system.query(${object([["fields", printFields("Query", query.fields)]])});`;
23204
+ return `const Query = system.model.query(${object([["fields", printFields("Query", query.fields)]])});`;
23205
+ }
23206
+ /** `const Segment = system.model.segment({ fields: [...] });`, your fields only. */
23207
+ function printSystemSegment(segment) {
23208
+ return `const Segment = system.model.segment(${object([["fields", printFields(segment.apiId, segment.fields)]])});`;
22813
23209
  }
23210
+ /**
23211
+ * Segment as a comment, for an environment Hygraph has not added it to
23212
+ * yet, so the config shows where it goes once a field has variants.
23213
+ */
23214
+ const SEGMENT_NOT_YET = [
23215
+ "// Segment (the audiences for variants) does not exist in this project yet.",
23216
+ "// To add fields to it:",
23217
+ "// 1. Give a field of one of your models variantEnabled: true.",
23218
+ "// 2. Uncomment the line below and add Segment to models.",
23219
+ "// Both can go in the same plan.",
23220
+ "// const Segment = system.model.segment({ fields: [] });"
23221
+ ].join("\n");
22814
23222
  //#endregion
22815
23223
  //#region src/export/resources/taxonomy.ts
22816
23224
  /**
@@ -22856,10 +23264,11 @@ const NO_QUERY_FIELDS = {
22856
23264
  * The config a user commits: one const per enumeration, then per
22857
23265
  * taxonomy, per remote source, per component and per model, in IR
22858
23266
  * order, then Asset and Query, also with no fields of yours, so the first
22859
- * asset field only adds its field back there. Then the environment that
22860
- * lists them with every locale and stage written inline, and the target as
22861
- * the default export. The token is read from HYGRAPH_TOKEN when the config
22862
- * loads, never written.
23267
+ * asset field only adds its field back there. Then Segment, as a comment
23268
+ * while live has none. Then the environment that lists them with every
23269
+ * locale and stage written inline, and the target as the default export.
23270
+ * The token is read from HYGRAPH_TOKEN when the config loads, never
23271
+ * written.
22863
23272
  */
22864
23273
  async function printConfig(target, environment) {
22865
23274
  return formatSource([
@@ -22871,6 +23280,7 @@ async function printConfig(target, environment) {
22871
23280
  ...environment.models.map(printModel),
22872
23281
  printSystemAsset(environment.asset ?? NO_ASSET_FIELDS),
22873
23282
  printSystemQuery(environment.query ?? NO_QUERY_FIELDS),
23283
+ environment.segment ? printSystemSegment(environment.segment) : SEGMENT_NOT_YET,
22874
23284
  printEnvironment(environment),
22875
23285
  printTarget(target)
22876
23286
  ].join("\n\n"));
@@ -22880,9 +23290,10 @@ async function printConfig(target, environment) {
22880
23290
  * every stage in its live order, also when Draft and Published are the only
22881
23291
  * ones, so the config shows where a new stage goes. `enumerations`,
22882
23292
  * `taxonomies`, `remoteSources` and `components` are left out when there
22883
- * are none, their default. `models` ends with Asset and Query.
23293
+ * are none, their default. `models` ends with Asset, Query and Segment,
23294
+ * when live has it.
22884
23295
  */
22885
- function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSources, components, models, asset }) {
23296
+ function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSources, components, models, asset, segment }) {
22886
23297
  const list = (resources) => `[${resources.map((resource) => resource.apiId).join(", ")}]`;
22887
23298
  return `const environment = define.environment({ ${[
22888
23299
  `locales: [${locales.map(printLocale).join(", ")}]`,
@@ -22894,7 +23305,8 @@ function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSou
22894
23305
  `models: ${list([
22895
23306
  ...models,
22896
23307
  asset ?? NO_ASSET_FIELDS,
22897
- { apiId: "Query" }
23308
+ { apiId: "Query" },
23309
+ ...segment ? [segment] : []
22898
23310
  ])}`
22899
23311
  ].join(", ")} });`;
22900
23312
  }
@@ -22909,26 +23321,121 @@ function printTarget(target) {
22909
23321
  ])});`;
22910
23322
  }
22911
23323
  //#endregion
23324
+ //#region src/export/token.ts
23325
+ /** Export sends the token to the endpoint, so only these hosts are taken. */
23326
+ const HYGRAPH_DOMAINS = [".hygraph.com", ".hygraph.dev"];
23327
+ function readTokenHints(token) {
23328
+ const claims = decodeClaims(token);
23329
+ if (claims === void 0) return {};
23330
+ return {
23331
+ endpoint: endpointFrom(claims.iss),
23332
+ environment: environmentFrom(claims.aud)
23333
+ };
23334
+ }
23335
+ function decodeClaims(token) {
23336
+ const payload = token.split(".")[1];
23337
+ if (payload === void 0) return;
23338
+ try {
23339
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
23340
+ return typeof claims === "object" && claims !== null ? claims : void 0;
23341
+ } catch {
23342
+ return;
23343
+ }
23344
+ }
23345
+ /**
23346
+ * An https issuer on a Hygraph domain. Tokens copied before management
23347
+ * server signed with its regional URL carry `https://management.graphcms.com/`,
23348
+ * which names no region.
23349
+ */
23350
+ function endpointFrom(iss) {
23351
+ const url = parseUrl(iss);
23352
+ if (url === void 0 || url.protocol !== "https:" || !HYGRAPH_DOMAINS.some((domain) => url.hostname.endsWith(domain))) return;
23353
+ url.pathname = url.pathname.replace(/\/?$/, "/graphql");
23354
+ return url.href;
23355
+ }
23356
+ /** The last path segment of the audience that is a content API URL. */
23357
+ function environmentFrom(aud) {
23358
+ const audiences = Array.isArray(aud) ? aud : [aud];
23359
+ for (const audience of audiences) {
23360
+ const segments = parseUrl(audience)?.pathname.split("/").filter(Boolean);
23361
+ if (segments !== void 0 && segments.length >= 2) return segments.at(-1);
23362
+ }
23363
+ }
23364
+ function parseUrl(value) {
23365
+ if (typeof value !== "string") return;
23366
+ try {
23367
+ return new URL(value);
23368
+ } catch {
23369
+ return;
23370
+ }
23371
+ }
23372
+ //#endregion
23373
+ //#region src/utils/ask.ts
23374
+ /**
23375
+ * Asks once on the terminal and echoes the answer as it is typed.
23376
+ * Undefined when the user stops with Ctrl+C or Ctrl+D.
23377
+ */
23378
+ function ask(question, { input, write }) {
23379
+ return readLine(question, input, writable(write));
23380
+ }
23381
+ /**
23382
+ * Asks once on the terminal and shows nothing of the answer, not even `*`.
23383
+ * Readline puts a terminal into raw mode and echoes into an output that
23384
+ * discards everything. Undefined when the user stops with Ctrl+C or Ctrl+D.
23385
+ */
23386
+ async function askSecret(question, { input, write }) {
23387
+ write(question);
23388
+ try {
23389
+ return await readLine("", input, writable(() => {}));
23390
+ } finally {
23391
+ write("\n");
23392
+ }
23393
+ }
23394
+ async function readLine(question, input, output) {
23395
+ const readline = createInterface({
23396
+ input,
23397
+ output,
23398
+ terminal: true
23399
+ });
23400
+ const stop = new AbortController();
23401
+ readline.on("SIGINT", () => stop.abort());
23402
+ readline.on("close", () => stop.abort());
23403
+ try {
23404
+ return await readline.question(question, { signal: stop.signal });
23405
+ } catch {
23406
+ return;
23407
+ } finally {
23408
+ readline.close();
23409
+ }
23410
+ }
23411
+ function writable(write) {
23412
+ return new Writable({ write(chunk, _encoding, callback) {
23413
+ write(chunk.toString());
23414
+ callback();
23415
+ } });
23416
+ }
23417
+ //#endregion
22912
23418
  //#region src/commands/export.ts
22913
23419
  /** What only export can find out is wrong. The command prints it and exits 1. */
22914
23420
  var ExportFailure = class extends Failure {};
22915
23421
  function registerExport(program) {
22916
- program.command("export").description("write a live environment out as TypeScript").requiredOption("--project <id>", "project to export").requiredOption("--endpoint <url>", "the project's management API endpoint").option("--environment <name>", "environment to export", "master").option("--name <name>", "target name in the config (default: the environment)").option("--out <file>", "write to a file instead of stdout").option("--no-color", "print without colours").action(async function(options) {
23422
+ program.command("export").description("write a live environment out as TypeScript").option("--project <id>", "project to export (default: the token's)").option("--endpoint <url>", "the project's management API endpoint (default: the token's)").option("--environment <name>", "environment to export (default: the token's, else master)").option("--name <name>", "target name in the config (default: the environment)").option("--out <file>", "write to a file instead of stdout").option("--no-color", "print without colours").action(async function(options) {
22917
23423
  const write = (text) => this.configureOutput().writeOut?.(text);
22918
23424
  const writeErr = (text) => this.configureOutput().writeErr?.(text);
22919
23425
  try {
22920
- const { config, environment } = await exportEnvironment(options);
23426
+ const input = await readInput(options, writeErr);
23427
+ const { config, environment } = await exportEnvironment(input);
22921
23428
  const headers = renderHeaderNote(remoteHeaderEnvNames(environment)) + renderSecretNote(oAuthSecretEnvNames(environment));
22922
- if (options.out === void 0) {
23429
+ if (input.out === void 0) {
22923
23430
  write(config);
22924
- writeErr(headers);
23431
+ writeErr(headers + (input.tokenTyped ? "\nThe config reads the token from HYGRAPH_TOKEN. Set it before you run plan.\n" : ""));
22925
23432
  return;
22926
23433
  }
22927
- writeConfigFile(config, options.out);
23434
+ writeConfigFile(config, input.out);
22928
23435
  const colors = import_picocolors.default.createColors(options.color && import_picocolors.default.isColorSupported);
22929
- write(renderCheck(`wrote ${options.out}`, count(environment), colors));
23436
+ write(renderCheck(`wrote ${input.out}`, count(environment), colors));
22930
23437
  write(headers);
22931
- write(`\nRun \`hygraph plan ${options.out}\` next. It should show no changes.\n`);
23438
+ write(input.tokenTyped ? `\nSet HYGRAPH_TOKEN to the token, then run \`hygraph plan ${input.out}\`. It should show no changes.\n` : `\nRun \`hygraph plan ${input.out}\` next. It should show no changes.\n`);
22932
23439
  } catch (error) {
22933
23440
  if (error instanceof Failure) this.error(`error: ${error.message}`, {
22934
23441
  exitCode: 1,
@@ -22936,21 +23443,107 @@ function registerExport(program) {
22936
23443
  });
22937
23444
  throw error;
22938
23445
  }
22939
- }).addHelpText("after", examples([["hygraph export --project 19330edb... --endpoint https://...", "print to stdout"], ["hygraph export --project 19330edb... --endpoint https://... --out hygraph.config.ts"]]));
23446
+ }).addHelpText("after", examples([
23447
+ ["hygraph export", "read the endpoint, project and environment from HYGRAPH_TOKEN"],
23448
+ ["hygraph export --out hygraph.config.ts"],
23449
+ ["hygraph export --project 19330edb... --endpoint https://...", "for a token that does not name its endpoint"]
23450
+ ]));
22940
23451
  }
22941
23452
  /**
22942
- * Reads the environment with the token in HYGRAPH_TOKEN and prints it as
22943
- * the config that would plan no changes against it.
23453
+ * The flags first, then what the token says, then on a terminal an answer
23454
+ * for each value still missing, with the default in brackets. The token
23455
+ * comes first because it names the endpoint and the environment, and the
23456
+ * endpoint names the project. A value found this way goes to stderr. A
23457
+ * typed token is used for this run only, and the config goes to a file
23458
+ * only when stdout is a terminal too.
22944
23459
  */
22945
- async function exportEnvironment(options) {
22946
- const token = process.env.HYGRAPH_TOKEN;
22947
- if (isEmpty(token)) throw new ExportFailure(`HYGRAPH_TOKEN is not set. Set it to a permanent auth token of project ${options.project}.`);
22948
- const target$1 = target({
22949
- name: options.name ?? options.environment,
22950
- project: options.project,
22951
- environment: options.environment,
22952
- endpoint: options.endpoint,
23460
+ async function readInput(options, writeErr) {
23461
+ const variable = process.env.HYGRAPH_TOKEN;
23462
+ const terminal = process.stdin.isTTY === true ? {
23463
+ input: process.stdin,
23464
+ write: writeErr
23465
+ } : void 0;
23466
+ let token = variable;
23467
+ if (isEmpty(token)) {
23468
+ if (terminal === void 0) throw new ExportFailure("HYGRAPH_TOKEN is not set. Set it to a permanent auth token of the project.");
23469
+ token = await askRequired("HYGRAPH_TOKEN is not set. Enter a permanent auth token (the input is hidden): ", "no token entered. Set HYGRAPH_TOKEN or enter a permanent auth token.", terminal, askSecret);
23470
+ }
23471
+ const hints = readTokenHints(token);
23472
+ let endpoint = options.endpoint;
23473
+ if (endpoint === void 0 && hints.endpoint !== void 0) {
23474
+ endpoint = hints.endpoint;
23475
+ writeErr(`Endpoint: ${endpoint} (from the token)\n`);
23476
+ }
23477
+ if (endpoint === void 0) {
23478
+ if (terminal === void 0) throw new ExportFailure("the token does not name its management API endpoint. Pass --endpoint <url> (Project Settings > Endpoints).");
23479
+ endpoint = await askRequired("Management API endpoint (Project Settings > Endpoints): ", "no endpoint entered", terminal);
23480
+ }
23481
+ let project = options.project;
23482
+ if (project === void 0) {
23483
+ const found = await tokenProject(endpoint, token);
23484
+ project = found.id;
23485
+ writeErr(`Project: ${found.id} (${found.name})\n`);
23486
+ }
23487
+ let environment = options.environment;
23488
+ if (environment === void 0 && hints.environment !== void 0) {
23489
+ environment = hints.environment;
23490
+ writeErr(`Environment: ${environment} (from the token)\n`);
23491
+ }
23492
+ environment ??= terminal === void 0 ? "master" : await askWithDefault("Environment", "master", terminal);
23493
+ const name = options.name ?? (terminal === void 0 ? environment : await askWithDefault("Target name in the config", environment, terminal));
23494
+ const out = options.out ?? (terminal !== void 0 && process.stdout.isTTY === true ? await askWithDefault("Write the config to", "hygraph.config.ts", terminal) : void 0);
23495
+ return {
23496
+ project,
23497
+ endpoint,
23498
+ environment,
23499
+ name,
23500
+ out,
22953
23501
  token,
23502
+ tokenTyped: isEmpty(variable)
23503
+ };
23504
+ }
23505
+ /** The project the token belongs to, as the management API answers. */
23506
+ async function tokenProject(endpoint, token) {
23507
+ let result;
23508
+ try {
23509
+ result = await createManagementClient({
23510
+ endpoint,
23511
+ token
23512
+ }).request(WhoamiDocument);
23513
+ } catch (error) {
23514
+ throw new ExportFailure(describeManagementError(error, endpoint));
23515
+ }
23516
+ const { viewer } = result;
23517
+ if (viewer.__typename !== "TokenViewer") throw new ExportFailure(`the token is a ${viewer.__typename}, not a permanent auth token`);
23518
+ if (!viewer.project) throw new ExportFailure("the token's project could not be read");
23519
+ return viewer.project;
23520
+ }
23521
+ async function askRequired(question, whenEmpty, terminal, prompt = ask) {
23522
+ const answer = await answerTo(question, terminal, prompt);
23523
+ if (answer === "") throw new ExportFailure(whenEmpty);
23524
+ return answer;
23525
+ }
23526
+ async function askWithDefault(question, fallback, terminal) {
23527
+ const answer = await answerTo(`${question} [${fallback}]: `, terminal, ask);
23528
+ return answer === "" ? fallback : answer;
23529
+ }
23530
+ /** The trimmed answer; Ctrl+C or Ctrl+D stops the command. */
23531
+ async function answerTo(question, terminal, prompt) {
23532
+ const answer = await prompt(question, terminal);
23533
+ if (answer === void 0) throw new ExportFailure("stopped, nothing was exported");
23534
+ return answer.trim();
23535
+ }
23536
+ /**
23537
+ * Reads the environment with the token and prints it as the config that
23538
+ * would plan no changes against it.
23539
+ */
23540
+ async function exportEnvironment(input) {
23541
+ const target$1 = target({
23542
+ name: input.name,
23543
+ project: input.project,
23544
+ environment: input.environment,
23545
+ endpoint: input.endpoint,
23546
+ token: input.token,
22954
23547
  apply: environment({
22955
23548
  locales: [],
22956
23549
  stages: [stage.draft(), stage.published()],
@@ -23038,8 +23631,9 @@ const RESOURCE_STARTS = [
23038
23631
  [/^const (\w+) = define\.enumeration\(/, (name) => `enumeration ${name}`],
23039
23632
  [/^const (\w+) = define\.taxonomy\(/, (name) => `taxonomy ${name}`],
23040
23633
  [/^const (\w+)RemoteSource = define\.(?:graphql|rest)RemoteSource\(/, (prefix) => `remote source ${prefix}`],
23041
- [/^const \w+ = system\.asset\(/, () => "system.asset"],
23042
- [/^const \w+ = system\.query\(/, () => "system.query"],
23634
+ [/^const \w+ = system\.model\.asset\(/, () => "system.model.asset"],
23635
+ [/^const \w+ = system\.model\.query\(/, () => "system.model.query"],
23636
+ [/^const \w+ = system\.model\.segment\(/, () => "system.model.segment"],
23043
23637
  [/^const environment = define\.environment\(/, () => "environment"],
23044
23638
  [/^export default define\.target\(/, () => "target"]
23045
23639
  ];
@@ -23233,7 +23827,7 @@ async function whoamiEach(targets, { write, writeErr }, fetch) {
23233
23827
  }
23234
23828
  /** Resolves the target's token against its management API and describes it. */
23235
23829
  async function whoami(target, fetch) {
23236
- if (isEmpty(target.token)) throw new WhoamiFailure(`target "${target.name}" has no token`);
23830
+ if (isEmpty(target.token)) throw new WhoamiFailure(`target "${target.name}" has no token. An exported config reads it from HYGRAPH_TOKEN.`);
23237
23831
  const client = createManagementClient({
23238
23832
  endpoint: target.endpoint,
23239
23833
  token: target.token,