@contello/client 1.2.1 → 2.0.0

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
@@ -4,7 +4,7 @@
4
4
  var command = process.argv[2];
5
5
  switch (command) {
6
6
  case "generate":
7
- await import("./generate-AVDKBRM7.js");
7
+ await import("./generate-KWWYQGKR.js");
8
8
  break;
9
9
  default:
10
10
  console.error(command ? `unknown command: ${command}` : "usage: contello-client <command>");
@@ -4,7 +4,7 @@
4
4
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
5
5
  import { glob } from "fs/promises";
6
6
  import { dirname, relative, resolve as resolve2 } from "path";
7
- import { Source, parse as parse2 } from "graphql";
7
+ import { Kind as Kind4, Source, parse as parse2, visit } from "graphql";
8
8
 
9
9
  // src/generate/config.ts
10
10
  import { resolve } from "path";
@@ -103,7 +103,7 @@ function collectUsedFragments(node, allFragments, collected) {
103
103
  function sortFragmentsByDependency(fragments) {
104
104
  const sorted = [];
105
105
  const visited = /* @__PURE__ */ new Set();
106
- function visit(name) {
106
+ function visit2(name) {
107
107
  if (visited.has(name)) {
108
108
  return;
109
109
  }
@@ -116,13 +116,13 @@ function sortFragmentsByDependency(fragments) {
116
116
  collectUsedFragments(fragment, fragments, deps);
117
117
  for (const [depName] of deps) {
118
118
  if (depName !== name) {
119
- visit(depName);
119
+ visit2(depName);
120
120
  }
121
121
  }
122
122
  sorted.push(fragment);
123
123
  }
124
124
  for (const [name] of fragments) {
125
- visit(name);
125
+ visit2(name);
126
126
  }
127
127
  return sorted;
128
128
  }
@@ -152,12 +152,31 @@ ${locations.join("\n")}` : ` ${err.message}`;
152
152
  ${formatted.join("\n\n")}
153
153
  `);
154
154
  }
155
- function generateDocumentString(operation, allFragments) {
155
+ function operationDocumentExpression(operation, allFragments) {
156
156
  const usedFragments = /* @__PURE__ */ new Map();
157
157
  collectUsedFragments(operation, allFragments, usedFragments);
158
158
  const sortedFragments = sortFragmentsByDependency(usedFragments);
159
- const parts = [...sortedFragments.map((f) => print(f)), print(operation)];
160
- return parts.join("\n");
159
+ const parts = sortedFragments.map((f) => `\${${f.name.value}FragmentSchema}`);
160
+ parts.push(print(operation));
161
+ return `\`${parts.join("\n")}\``;
162
+ }
163
+ function fragmentBundleExpression(fragment, allFragments) {
164
+ const usedFragments = /* @__PURE__ */ new Map();
165
+ collectUsedFragments(fragment, allFragments, usedFragments);
166
+ usedFragments.set(fragment.name.value, fragment);
167
+ const sortedFragments = sortFragmentsByDependency(usedFragments);
168
+ if (sortedFragments.length === 1) {
169
+ return `${sortedFragments[0].name.value}FragmentSchema`;
170
+ }
171
+ return `\`${sortedFragments.map((f) => `\${${f.name.value}FragmentSchema}`).join("\n")}\``;
172
+ }
173
+ function generateFragmentSchemas(fragments) {
174
+ const sorted = [...fragments.values()].sort((a, b) => a.name.value.localeCompare(b.name.value));
175
+ const lines = [];
176
+ for (const fragment of sorted) {
177
+ lines.push(`const ${fragment.name.value}FragmentSchema = \`${print(fragment)}\`;`);
178
+ }
179
+ return lines.join("\n");
161
180
  }
162
181
 
163
182
  // src/generate/introspect.ts
@@ -256,9 +275,10 @@ function unwrapType(type) {
256
275
  }
257
276
  return { namedType: current, isList, isNonNull };
258
277
  }
259
- function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent, visited) {
278
+ function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent) {
260
279
  const fields = [];
261
280
  const inlineUnions = [];
281
+ const fragmentRefs = [];
262
282
  let hasTypenameField = false;
263
283
  for (const selection of selectionSet.selections) {
264
284
  if (selection.kind === Kind2.FIELD) {
@@ -274,7 +294,7 @@ function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent
274
294
  const { namedType, isList, isNonNull } = unwrapType(schemaField.type);
275
295
  let tsType;
276
296
  if (selection.selectionSet && isCompositeType(namedType)) {
277
- tsType = resolveSelectionSetType(schema, selection.selectionSet, namedType, fragments, `${indent} `, visited);
297
+ tsType = resolveSelectionSetType(schema, selection.selectionSet, namedType, fragments, `${indent} `);
278
298
  } else if (isScalarType(namedType)) {
279
299
  tsType = resolveScalarType(namedType.name);
280
300
  } else if (isEnumType(namedType)) {
@@ -283,7 +303,7 @@ function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent
283
303
  tsType = namedType.toString();
284
304
  }
285
305
  if (isList) {
286
- const wrapped = tsType.includes(" | ") ? `(${tsType})` : tsType;
306
+ const wrapped = /[ |&]/.test(tsType) ? `(${tsType})` : tsType;
287
307
  tsType = `${wrapped}[]`;
288
308
  }
289
309
  if (isNonNull) {
@@ -300,24 +320,11 @@ function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent
300
320
  }
301
321
  if (isCompositeType(conditionalType)) {
302
322
  if (isInterfaceType(conditionalType)) {
303
- const inner = resolveSelectionSet(
304
- schema,
305
- selection.selectionSet,
306
- conditionalType,
307
- fragments,
308
- indent,
309
- visited
310
- );
323
+ const inner = resolveSelectionSet(schema, selection.selectionSet, conditionalType, fragments, indent);
311
324
  fields.push(...inner.fields);
325
+ fragmentRefs.push(...inner.fragmentRefs);
312
326
  } else if (isObjectType(conditionalType)) {
313
- const nested = resolveSelectionSetType(
314
- schema,
315
- selection.selectionSet,
316
- conditionalType,
317
- fragments,
318
- indent,
319
- visited
320
- );
327
+ const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
321
328
  if (nested.startsWith("{")) {
322
329
  const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
323
330
  const discriminant = model ? `${indent} __typename: '${conditionalType.name}';
@@ -326,27 +333,23 @@ ${indent} __model: '${model}';` : `${indent} __typename: '${conditionalType.na
326
333
  ${discriminant}
327
334
  ${nested.slice(2)}`);
328
335
  } else {
329
- inlineUnions.push(nested);
336
+ const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
337
+ const discriminant = model ? `{
338
+ ${indent} __typename: '${conditionalType.name}';
339
+ ${indent} __model: '${model}';
340
+ ${indent}}` : `{
341
+ ${indent} __typename: '${conditionalType.name}';
342
+ ${indent}}`;
343
+ inlineUnions.push(`${discriminant} & ${nested}`);
330
344
  }
331
345
  } else {
332
- const nested = resolveSelectionSetType(
333
- schema,
334
- selection.selectionSet,
335
- conditionalType,
336
- fragments,
337
- indent,
338
- visited
339
- );
346
+ const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
340
347
  inlineUnions.push(nested);
341
348
  }
342
349
  }
343
350
  }
344
351
  } else if (selection.kind === Kind2.FRAGMENT_SPREAD) {
345
352
  const fragmentName = selection.name.value;
346
- if (visited.has(fragmentName)) {
347
- inlineUnions.push(`${fragmentName}Fragment`);
348
- continue;
349
- }
350
353
  const fragment = fragments.get(fragmentName);
351
354
  if (fragment?.selectionSet) {
352
355
  const fragmentType = schema.getType(fragment.typeCondition.name.value);
@@ -356,50 +359,42 @@ ${nested.slice(2)}`);
356
359
  `fragment "${fragmentName}" (on ${fragmentType.name}) cannot be spread on type "${parentType.name}"`
357
360
  );
358
361
  }
359
- const nextVisited = new Set(visited);
360
- nextVisited.add(fragmentName);
361
- const fragmentResult = resolveSelectionSet(
362
- schema,
363
- fragment.selectionSet,
364
- fragmentType,
365
- fragments,
366
- indent,
367
- nextVisited
368
- );
369
- fields.push(...fragmentResult.fields);
370
- inlineUnions.push(...fragmentResult.inlineUnions);
371
- if (fragmentResult.hasTypenameField) {
372
- hasTypenameField = true;
373
- }
362
+ fragmentRefs.push(`${fragmentName}Fragment`);
374
363
  }
375
364
  }
376
365
  }
377
366
  }
378
- return { fields, inlineUnions, hasTypenameField };
367
+ return { fields, inlineUnions, fragmentRefs, hasTypenameField };
379
368
  }
380
- function resolveSelectionSetType(schema, selectionSet, parentType, fragments, indent, visited = /* @__PURE__ */ new Set()) {
381
- const { fields, inlineUnions, hasTypenameField } = resolveSelectionSet(
369
+ function resolveSelectionSetType(schema, selectionSet, parentType, fragments, indent) {
370
+ const { fields, inlineUnions, fragmentRefs, hasTypenameField } = resolveSelectionSet(
382
371
  schema,
383
372
  selectionSet,
384
373
  parentType,
385
374
  fragments,
386
- indent,
387
- visited
375
+ indent
388
376
  );
389
377
  if (hasTypenameField && inlineUnions.length === 0) {
390
378
  const typenameField = isObjectType(parentType) ? `${indent} __typename: '${parentType.name}';` : `${indent} __typename: string;`;
391
379
  fields.unshift(typenameField);
392
380
  }
393
- if (inlineUnions.length > 0 && fields.length === 0) {
381
+ if (fields.length === 0 && fragmentRefs.length === 0 && inlineUnions.length > 0) {
394
382
  return inlineUnions.join(" | ");
395
383
  }
396
- const baseType = fields.length > 0 ? `{
384
+ const parts = [];
385
+ if (fields.length > 0) {
386
+ parts.push(`{
397
387
  ${fields.join("\n")}
398
- ${indent}}` : "{}";
388
+ ${indent}}`);
389
+ }
390
+ parts.push(...fragmentRefs);
399
391
  if (inlineUnions.length > 0) {
400
- return `${baseType} & (${inlineUnions.join(" | ")})`;
392
+ parts.push(`(${inlineUnions.join(" | ")})`);
401
393
  }
402
- return baseType;
394
+ if (parts.length === 0) {
395
+ return "{}";
396
+ }
397
+ return parts.join(" & ");
403
398
  }
404
399
  function generateVariablesType(schema, operation) {
405
400
  const vars = operation.variableDefinitions ?? [];
@@ -477,7 +472,7 @@ function generateOperationTypes(schema, operations, fragments) {
477
472
  }
478
473
 
479
474
  // src/generate/operations.ts
480
- function generateOperationsObject(operations) {
475
+ function generateOperationsType(operations) {
481
476
  const lines = [];
482
477
  lines.push("export type Operations = {");
483
478
  for (const op of operations) {
@@ -494,13 +489,16 @@ function generateOperationsObject(operations) {
494
489
  lines.push(" };");
495
490
  }
496
491
  lines.push("};");
497
- lines.push("");
498
- lines.push("export const operations: Operations = {");
492
+ return lines.join("\n");
493
+ }
494
+ function generateOperationsConst(operations) {
495
+ const lines = [];
496
+ lines.push("const operations: Operations = {");
499
497
  for (const op of operations) {
500
498
  const camelName = uncapitalize(op.name.value);
501
499
  lines.push(` ${camelName}: { document: ${camelName}Document, kind: '${op.operation}' },`);
502
500
  }
503
- lines.push("} as Operations;");
501
+ lines.push("};");
504
502
  return lines.join("\n");
505
503
  }
506
504
 
@@ -640,17 +638,148 @@ function generateSchemaTypes(schema) {
640
638
  if (unions.length > 0) {
641
639
  lines.push("");
642
640
  }
643
- if (entityModelNames.size > 0) {
644
- const sorted = [...entityModelNames.entries()].sort(([a], [b]) => a.localeCompare(b));
645
- lines.push("export const models = {");
646
- for (const [typeName, model] of sorted) {
647
- lines.push(` ${model}: '${typeName}',`);
641
+ return lines.join("\n");
642
+ }
643
+ function extractEntityModels(schema) {
644
+ const map = /* @__PURE__ */ new Map();
645
+ const union = schema.getTypeMap()["ContelloEntity"];
646
+ if (!union || !isUnionType(union)) {
647
+ return map;
648
+ }
649
+ for (const member of union.getTypes()) {
650
+ const model = deriveModelName(member.name);
651
+ if (model) {
652
+ map.set(model, member.name);
648
653
  }
649
- lines.push("} as const;");
650
- lines.push("");
651
- lines.push("export type ModelType = keyof typeof models;");
652
- lines.push("");
653
654
  }
655
+ return map;
656
+ }
657
+
658
+ // src/generate/sources.ts
659
+ import {
660
+ isListType as isListType3,
661
+ isNonNullType as isNonNullType3,
662
+ isObjectType as isObjectType3
663
+ } from "graphql";
664
+ var BUILT_IN_SOURCES = [
665
+ { typeName: "ContelloRoute", cardinality: "route", fieldName: "contelloRoutesBatch" },
666
+ { typeName: "ContelloAsset", cardinality: "asset", fieldName: "contelloAssetsBatch" },
667
+ { typeName: "ContelloI18nMessage", cardinality: "i18nMessage", fieldName: "contelloI18nMessagesBatch" }
668
+ ];
669
+ function indexEntitySources(schema) {
670
+ const result = /* @__PURE__ */ new Map();
671
+ const subscription = schema.getSubscriptionType();
672
+ if (!subscription) {
673
+ return result;
674
+ }
675
+ const singletonCandidates = /* @__PURE__ */ new Map();
676
+ for (const field of Object.values(subscription.getFields())) {
677
+ const { entityType, isList } = unwrapEntity(field.type);
678
+ if (!entityType || !isContelloModel(schema, entityType.name)) {
679
+ continue;
680
+ }
681
+ const model = deriveModelName(entityType.name);
682
+ if (!model) {
683
+ continue;
684
+ }
685
+ if (isList) {
686
+ result.set(entityType.name, { cardinality: "entity", fieldName: field.name, model });
687
+ } else if (!singletonCandidates.has(entityType.name)) {
688
+ singletonCandidates.set(entityType.name, { fieldName: field.name });
689
+ }
690
+ }
691
+ for (const [typeName, { fieldName }] of singletonCandidates) {
692
+ if (result.has(typeName)) {
693
+ continue;
694
+ }
695
+ const model = deriveModelName(typeName);
696
+ if (!model) {
697
+ continue;
698
+ }
699
+ result.set(typeName, { cardinality: "singleton", fieldName, model });
700
+ }
701
+ return result;
702
+ }
703
+ function indexBuiltInSources(schema) {
704
+ const result = /* @__PURE__ */ new Map();
705
+ const subscription = schema.getSubscriptionType();
706
+ if (!subscription) {
707
+ return result;
708
+ }
709
+ const fields = subscription.getFields();
710
+ for (const builtIn of BUILT_IN_SOURCES) {
711
+ if (!schema.getType(builtIn.typeName) || !fields[builtIn.fieldName]) {
712
+ continue;
713
+ }
714
+ result.set(builtIn.typeName, {
715
+ cardinality: builtIn.cardinality,
716
+ fieldName: builtIn.fieldName
717
+ });
718
+ }
719
+ return result;
720
+ }
721
+ function unwrapEntity(type) {
722
+ let current = type;
723
+ let isList = false;
724
+ if (isNonNullType3(current)) {
725
+ current = current.ofType;
726
+ }
727
+ if (isListType3(current)) {
728
+ isList = true;
729
+ current = current.ofType;
730
+ if (isNonNullType3(current)) {
731
+ current = current.ofType;
732
+ }
733
+ }
734
+ return {
735
+ entityType: isObjectType3(current) ? current : void 0,
736
+ isList
737
+ };
738
+ }
739
+ function organize(entries) {
740
+ const byKey = /* @__PURE__ */ new Map();
741
+ for (const entry of entries) {
742
+ const existing = byKey.get(entry.binding.sourceKey);
743
+ if (existing) {
744
+ throw new Error(
745
+ `multiple fragments target the same source key "${entry.binding.sourceKey}": "${existing.fragmentName}" and "${entry.fragmentName}". A source key can have at most one fragment \u2014 merge the fragments or use the raw client for the alternative shape.`
746
+ );
747
+ }
748
+ byKey.set(entry.binding.sourceKey, entry);
749
+ }
750
+ return [...byKey.values()].sort((a, b) => a.binding.sourceKey.localeCompare(b.binding.sourceKey));
751
+ }
752
+ function generateSourcesType(entries) {
753
+ const sorted = organize(entries);
754
+ if (sorted.length === 0) {
755
+ return "";
756
+ }
757
+ const lines = [];
758
+ lines.push("export type Sources = {");
759
+ for (const { fragmentName, binding } of sorted) {
760
+ const type = `SourceDef<'${binding.sourceKey}', '${binding.cardinality}', ${fragmentName}Fragment>`;
761
+ lines.push(` ${binding.sourceKey}: ${type};`);
762
+ }
763
+ lines.push("};");
764
+ return lines.join("\n");
765
+ }
766
+ function generateSourcesConst(entries) {
767
+ const sorted = organize(entries);
768
+ if (sorted.length === 0) {
769
+ return "";
770
+ }
771
+ const lines = [];
772
+ lines.push("const sources: Sources = {");
773
+ for (const { fragmentName, binding, fragmentExpression } of sorted) {
774
+ lines.push(` ${binding.sourceKey}: {`);
775
+ lines.push(` document: ${fragmentExpression},`);
776
+ lines.push(` fragment: '${fragmentName}',`);
777
+ lines.push(` subscription: '${binding.fieldName}',`);
778
+ lines.push(` __model: '${binding.sourceKey}',`);
779
+ lines.push(` __cardinality: '${binding.cardinality}',`);
780
+ lines.push(` },`);
781
+ }
782
+ lines.push("};");
654
783
  return lines.join("\n");
655
784
  }
656
785
 
@@ -658,9 +787,9 @@ function generateSchemaTypes(schema) {
658
787
  import {
659
788
  Kind as Kind3,
660
789
  isCompositeType as isCompositeType2,
661
- isListType as isListType3,
662
- isNonNullType as isNonNullType3,
663
- isObjectType as isObjectType3,
790
+ isListType as isListType4,
791
+ isNonNullType as isNonNullType4,
792
+ isObjectType as isObjectType4,
664
793
  isUnionType as isUnionType2,
665
794
  parse
666
795
  } from "graphql";
@@ -679,8 +808,8 @@ function isComponentSubtype(schema, typeName) {
679
808
  return union.getTypes().some((t) => t.name === typeName);
680
809
  }
681
810
  function getNamedTypeName(type) {
682
- if (isNonNullType3(type)) return getNamedTypeName(type.ofType);
683
- if (isListType3(type)) return getNamedTypeName(type.ofType);
811
+ if (isNonNullType4(type)) return getNamedTypeName(type.ofType);
812
+ if (isListType4(type)) return getNamedTypeName(type.ofType);
684
813
  return type?.name;
685
814
  }
686
815
  var FLAT_REF_SELECTIONS = parse(
@@ -702,7 +831,7 @@ function addFlatRefSelections(selectionSet) {
702
831
  }
703
832
  function transformSelectionSet(schema, selectionSet, parentTypeName, fragments, refsOnly = false) {
704
833
  const parentType = schema.getType(parentTypeName);
705
- if (!parentType || !isObjectType3(parentType)) {
834
+ if (!parentType || !isObjectType4(parentType)) {
706
835
  return selectionSet;
707
836
  }
708
837
  const parentFields = parentType.getFields();
@@ -753,7 +882,7 @@ function transformSelectionSet(schema, selectionSet, parentTypeName, fragments,
753
882
  } else if (selection.kind === Kind3.INLINE_FRAGMENT) {
754
883
  const typeName = selection.typeCondition?.name.value;
755
884
  const type = typeName ? schema.getType(typeName) : void 0;
756
- if (typeName && type && isCompositeType2(type) && isObjectType3(type)) {
885
+ if (typeName && type && isCompositeType2(type) && isObjectType4(type)) {
757
886
  recurse(selection, typeName);
758
887
  } else {
759
888
  newSelections.push(selection);
@@ -788,7 +917,7 @@ function transformFragment(schema, fragment, fragments) {
788
917
  if (typeName === COMPONENT_UNION) {
789
918
  selectionSet = addFlatRefSelections(selectionSet);
790
919
  }
791
- if (isObjectType3(type)) {
920
+ if (isObjectType4(type)) {
792
921
  const refsOnly = isComponentSubtype(schema, typeName);
793
922
  selectionSet = transformSelectionSet(schema, selectionSet, typeName, fragments, refsOnly);
794
923
  } else if (isUnionType2(type)) {
@@ -796,7 +925,7 @@ function transformFragment(schema, fragment, fragments) {
796
925
  if (sel.kind === Kind3.INLINE_FRAGMENT && sel.typeCondition && sel.selectionSet) {
797
926
  const inlineTypeName = sel.typeCondition.name.value;
798
927
  const inlineType = schema.getType(inlineTypeName);
799
- if (inlineType && isObjectType3(inlineType)) {
928
+ if (inlineType && isObjectType4(inlineType)) {
800
929
  const transformed = transformSelectionSet(schema, sel.selectionSet, inlineTypeName, fragments, true);
801
930
  if (transformed !== sel.selectionSet) {
802
931
  return { ...sel, selectionSet: transformed };
@@ -821,6 +950,15 @@ var bold = (s) => styled(s, "1m", "22m");
821
950
  var green = (s) => styled(s, "32m", "39m");
822
951
  var yellow = (s) => styled(s, "33m", "39m");
823
952
  var cyan = (s) => styled(s, "36m", "39m");
953
+ function collectFragmentSpreads(fragment) {
954
+ const refs = /* @__PURE__ */ new Set();
955
+ visit(fragment, {
956
+ [Kind4.FRAGMENT_SPREAD](node) {
957
+ refs.add(node.name.value);
958
+ }
959
+ });
960
+ return refs;
961
+ }
824
962
  async function main() {
825
963
  const cwd = process.cwd();
826
964
  const config = await loadConfig(cwd);
@@ -846,21 +984,120 @@ async function main() {
846
984
  [...fragments].map(([name, frag]) => [name, transformFragment(schema, frag, fragments)])
847
985
  );
848
986
  const transformedOperations = operations.map((op) => transformOperation(schema, op, transformedFragments));
987
+ const entityBindings = indexEntitySources(schema);
988
+ const builtInBindings = indexBuiltInSources(schema);
989
+ const sourceEntries = [];
990
+ for (const [name, fragment] of fragments) {
991
+ const entityBinding = entityBindings.get(fragment.typeCondition.name.value);
992
+ if (!entityBinding) {
993
+ continue;
994
+ }
995
+ const transformed = transformedFragments.get(name);
996
+ if (!transformed) {
997
+ continue;
998
+ }
999
+ sourceEntries.push({
1000
+ fragmentName: name,
1001
+ binding: {
1002
+ cardinality: entityBinding.cardinality,
1003
+ fieldName: entityBinding.fieldName,
1004
+ sourceKey: entityBinding.model
1005
+ },
1006
+ fragmentExpression: fragmentBundleExpression(transformed, transformedFragments)
1007
+ });
1008
+ }
1009
+ for (const [typeName, builtInBinding] of builtInBindings) {
1010
+ const candidates = [];
1011
+ for (const [name, fragment] of fragments) {
1012
+ if (fragment.typeCondition.name.value === typeName) {
1013
+ candidates.push({ name, fragment });
1014
+ }
1015
+ }
1016
+ if (candidates.length === 0) {
1017
+ continue;
1018
+ }
1019
+ const candidateNames = new Set(candidates.map((c) => c.name));
1020
+ const spreadByOther = /* @__PURE__ */ new Set();
1021
+ for (const { name, fragment } of candidates) {
1022
+ for (const ref of collectFragmentSpreads(fragment)) {
1023
+ if (ref !== name && candidateNames.has(ref)) {
1024
+ spreadByOther.add(ref);
1025
+ }
1026
+ }
1027
+ }
1028
+ const roots = candidates.filter((c) => !spreadByOther.has(c.name));
1029
+ const picked = roots.length === 1 ? roots[0] : void 0;
1030
+ if (!picked) {
1031
+ throw new Error(
1032
+ `multiple fragments target the built-in type "${typeName}" without a clear root: ${candidates.map((c) => `"${c.name}"`).join(", ")}. Either have one fragment spread the others, or remove the extras.`
1033
+ );
1034
+ }
1035
+ const transformed = transformedFragments.get(picked.name);
1036
+ if (!transformed) {
1037
+ continue;
1038
+ }
1039
+ sourceEntries.push({
1040
+ fragmentName: picked.name,
1041
+ binding: {
1042
+ cardinality: builtInBinding.cardinality,
1043
+ fieldName: builtInBinding.fieldName,
1044
+ sourceKey: uncapitalize(picked.name)
1045
+ },
1046
+ fragmentExpression: fragmentBundleExpression(transformed, transformedFragments)
1047
+ });
1048
+ }
1049
+ const entityModels = extractEntityModels(schema);
849
1050
  const parts = [];
850
1051
  parts.push("/* eslint-disable */");
851
1052
  parts.push("// @ts-nocheck");
852
1053
  parts.push("/* this file is generated by contello-client \u2014 do not edit */");
853
1054
  parts.push("");
1055
+ parts.push(`import type { SourceDef } from '@contello/client';`);
1056
+ parts.push("");
854
1057
  parts.push(generateSchemaTypes(schema));
855
1058
  parts.push(generateFragmentTypes(schema, fragments));
856
1059
  parts.push(generateOperationTypes(schema, operations, fragments));
1060
+ if (transformedFragments.size > 0) {
1061
+ parts.push(generateFragmentSchemas(transformedFragments));
1062
+ parts.push("");
1063
+ }
857
1064
  for (let i = 0; i < operations.length; i++) {
858
1065
  const camelName = uncapitalize(operations[i].name.value);
859
- const docString = generateDocumentString(transformedOperations[i], transformedFragments);
860
- parts.push(`export const ${camelName}Document = \`${docString}\`;`);
1066
+ const docExpr = operationDocumentExpression(transformedOperations[i], transformedFragments);
1067
+ parts.push(`export const ${camelName}Document = ${docExpr};`);
1068
+ }
1069
+ if (operations.length > 0) {
1070
+ parts.push("");
1071
+ }
1072
+ parts.push(generateOperationsType(operations));
1073
+ parts.push("");
1074
+ const sourcesTypeSrc = generateSourcesType(sourceEntries);
1075
+ if (sourcesTypeSrc) {
1076
+ parts.push(sourcesTypeSrc);
1077
+ parts.push("");
1078
+ }
1079
+ parts.push(generateOperationsConst(operations));
1080
+ parts.push("");
1081
+ const sourcesConstSrc = generateSourcesConst(sourceEntries);
1082
+ if (sourcesConstSrc) {
1083
+ parts.push(sourcesConstSrc);
1084
+ parts.push("");
1085
+ }
1086
+ if (entityModels.size > 0) {
1087
+ const sorted = [...entityModels.entries()].sort(([a], [b]) => a.localeCompare(b));
1088
+ parts.push("const models = {");
1089
+ for (const [model, typeName] of sorted) {
1090
+ parts.push(` ${model}: '${typeName}',`);
1091
+ }
1092
+ parts.push("} as const;");
1093
+ parts.push("");
1094
+ } else {
1095
+ parts.push("const models = {} as const;");
861
1096
  parts.push("");
862
1097
  }
863
- parts.push(generateOperationsObject(operations));
1098
+ const sourcesPart = sourcesConstSrc ? ", sources" : ", sources: {}";
1099
+ parts.push(`export const schema = { operations${sourcesPart}, models };`);
1100
+ parts.push("export type Schema = typeof schema;");
864
1101
  let output = parts.join("\n");
865
1102
  if (project.namespace) {
866
1103
  const indented = output.split("\n").map((line) => line ? ` ${line}` : "").join("\n");