@contello/client 1.2.2 → 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-PGYNYGNX.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
@@ -453,7 +472,7 @@ function generateOperationTypes(schema, operations, fragments) {
453
472
  }
454
473
 
455
474
  // src/generate/operations.ts
456
- function generateOperationsObject(operations) {
475
+ function generateOperationsType(operations) {
457
476
  const lines = [];
458
477
  lines.push("export type Operations = {");
459
478
  for (const op of operations) {
@@ -470,13 +489,16 @@ function generateOperationsObject(operations) {
470
489
  lines.push(" };");
471
490
  }
472
491
  lines.push("};");
473
- lines.push("");
474
- 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 = {");
475
497
  for (const op of operations) {
476
498
  const camelName = uncapitalize(op.name.value);
477
499
  lines.push(` ${camelName}: { document: ${camelName}Document, kind: '${op.operation}' },`);
478
500
  }
479
- lines.push("} as Operations;");
501
+ lines.push("};");
480
502
  return lines.join("\n");
481
503
  }
482
504
 
@@ -616,17 +638,148 @@ function generateSchemaTypes(schema) {
616
638
  if (unions.length > 0) {
617
639
  lines.push("");
618
640
  }
619
- if (entityModelNames.size > 0) {
620
- const sorted = [...entityModelNames.entries()].sort(([a], [b]) => a.localeCompare(b));
621
- lines.push("export const models = {");
622
- for (const [typeName, model] of sorted) {
623
- 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);
624
653
  }
625
- lines.push("} as const;");
626
- lines.push("");
627
- lines.push("export type ModelType = keyof typeof models;");
628
- lines.push("");
629
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("};");
630
783
  return lines.join("\n");
631
784
  }
632
785
 
@@ -634,9 +787,9 @@ function generateSchemaTypes(schema) {
634
787
  import {
635
788
  Kind as Kind3,
636
789
  isCompositeType as isCompositeType2,
637
- isListType as isListType3,
638
- isNonNullType as isNonNullType3,
639
- isObjectType as isObjectType3,
790
+ isListType as isListType4,
791
+ isNonNullType as isNonNullType4,
792
+ isObjectType as isObjectType4,
640
793
  isUnionType as isUnionType2,
641
794
  parse
642
795
  } from "graphql";
@@ -655,8 +808,8 @@ function isComponentSubtype(schema, typeName) {
655
808
  return union.getTypes().some((t) => t.name === typeName);
656
809
  }
657
810
  function getNamedTypeName(type) {
658
- if (isNonNullType3(type)) return getNamedTypeName(type.ofType);
659
- if (isListType3(type)) return getNamedTypeName(type.ofType);
811
+ if (isNonNullType4(type)) return getNamedTypeName(type.ofType);
812
+ if (isListType4(type)) return getNamedTypeName(type.ofType);
660
813
  return type?.name;
661
814
  }
662
815
  var FLAT_REF_SELECTIONS = parse(
@@ -678,7 +831,7 @@ function addFlatRefSelections(selectionSet) {
678
831
  }
679
832
  function transformSelectionSet(schema, selectionSet, parentTypeName, fragments, refsOnly = false) {
680
833
  const parentType = schema.getType(parentTypeName);
681
- if (!parentType || !isObjectType3(parentType)) {
834
+ if (!parentType || !isObjectType4(parentType)) {
682
835
  return selectionSet;
683
836
  }
684
837
  const parentFields = parentType.getFields();
@@ -729,7 +882,7 @@ function transformSelectionSet(schema, selectionSet, parentTypeName, fragments,
729
882
  } else if (selection.kind === Kind3.INLINE_FRAGMENT) {
730
883
  const typeName = selection.typeCondition?.name.value;
731
884
  const type = typeName ? schema.getType(typeName) : void 0;
732
- if (typeName && type && isCompositeType2(type) && isObjectType3(type)) {
885
+ if (typeName && type && isCompositeType2(type) && isObjectType4(type)) {
733
886
  recurse(selection, typeName);
734
887
  } else {
735
888
  newSelections.push(selection);
@@ -764,7 +917,7 @@ function transformFragment(schema, fragment, fragments) {
764
917
  if (typeName === COMPONENT_UNION) {
765
918
  selectionSet = addFlatRefSelections(selectionSet);
766
919
  }
767
- if (isObjectType3(type)) {
920
+ if (isObjectType4(type)) {
768
921
  const refsOnly = isComponentSubtype(schema, typeName);
769
922
  selectionSet = transformSelectionSet(schema, selectionSet, typeName, fragments, refsOnly);
770
923
  } else if (isUnionType2(type)) {
@@ -772,7 +925,7 @@ function transformFragment(schema, fragment, fragments) {
772
925
  if (sel.kind === Kind3.INLINE_FRAGMENT && sel.typeCondition && sel.selectionSet) {
773
926
  const inlineTypeName = sel.typeCondition.name.value;
774
927
  const inlineType = schema.getType(inlineTypeName);
775
- if (inlineType && isObjectType3(inlineType)) {
928
+ if (inlineType && isObjectType4(inlineType)) {
776
929
  const transformed = transformSelectionSet(schema, sel.selectionSet, inlineTypeName, fragments, true);
777
930
  if (transformed !== sel.selectionSet) {
778
931
  return { ...sel, selectionSet: transformed };
@@ -797,6 +950,15 @@ var bold = (s) => styled(s, "1m", "22m");
797
950
  var green = (s) => styled(s, "32m", "39m");
798
951
  var yellow = (s) => styled(s, "33m", "39m");
799
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
+ }
800
962
  async function main() {
801
963
  const cwd = process.cwd();
802
964
  const config = await loadConfig(cwd);
@@ -822,21 +984,120 @@ async function main() {
822
984
  [...fragments].map(([name, frag]) => [name, transformFragment(schema, frag, fragments)])
823
985
  );
824
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);
825
1050
  const parts = [];
826
1051
  parts.push("/* eslint-disable */");
827
1052
  parts.push("// @ts-nocheck");
828
1053
  parts.push("/* this file is generated by contello-client \u2014 do not edit */");
829
1054
  parts.push("");
1055
+ parts.push(`import type { SourceDef } from '@contello/client';`);
1056
+ parts.push("");
830
1057
  parts.push(generateSchemaTypes(schema));
831
1058
  parts.push(generateFragmentTypes(schema, fragments));
832
1059
  parts.push(generateOperationTypes(schema, operations, fragments));
1060
+ if (transformedFragments.size > 0) {
1061
+ parts.push(generateFragmentSchemas(transformedFragments));
1062
+ parts.push("");
1063
+ }
833
1064
  for (let i = 0; i < operations.length; i++) {
834
1065
  const camelName = uncapitalize(operations[i].name.value);
835
- const docString = generateDocumentString(transformedOperations[i], transformedFragments);
836
- 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;");
837
1096
  parts.push("");
838
1097
  }
839
- 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;");
840
1101
  let output = parts.join("\n");
841
1102
  if (project.namespace) {
842
1103
  const indented = output.split("\n").map((line) => line ? ` ${line}` : "").join("\n");