@baeta/plugin-graphql 0.1.0 → 0.1.2

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/index.js CHANGED
@@ -8,6 +8,7 @@ var __export = (target, all) => {
8
8
  import { createPluginV1, isMatch } from "@baeta/generator-sdk";
9
9
 
10
10
  // lib/codegen.ts
11
+ import { join as join2 } from "@baeta/util-path";
11
12
  import { codegen as gqlCodegen } from "@graphql-codegen/core";
12
13
  import { normalizeConfig, normalizeInstanceOrArray } from "@graphql-codegen/plugin-helpers";
13
14
  import * as typescriptPlugin from "@graphql-codegen/typescript";
@@ -29,17 +30,10 @@ function createCache() {
29
30
 
30
31
  // utils/load.ts
31
32
  import { getCachedDocumentNodeFromSchema as getCachedDocumentNodeFromSchema2 } from "@graphql-codegen/plugin-helpers";
32
- import { ApolloEngineLoader } from "@graphql-tools/apollo-engine-loader";
33
- import { CodeFileLoader } from "@graphql-tools/code-file-loader";
34
- import { GitLoader } from "@graphql-tools/git-loader";
35
- import { GithubLoader } from "@graphql-tools/github-loader";
36
33
  import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
37
- import { JsonFileLoader } from "@graphql-tools/json-file-loader";
38
34
  import {
39
35
  loadSchema as loadSchemaToolkit
40
36
  } from "@graphql-tools/load";
41
- import { PrismaLoader } from "@graphql-tools/prisma-loader";
42
- import { UrlLoader } from "@graphql-tools/url-loader";
43
37
  import { validateSchema } from "graphql";
44
38
 
45
39
  // utils/hash.ts
@@ -54,18 +48,9 @@ function hashSchema(schema) {
54
48
  }
55
49
 
56
50
  // utils/load.ts
57
- async function loadSchema(schemaPointerMap, cwd) {
51
+ async function loadSchema(schemaPointerMap, cwd, extraLoaders = []) {
58
52
  const outputSchemaAst = await loadSchemaToolkit(schemaPointerMap, {
59
- loaders: [
60
- new CodeFileLoader(),
61
- new GitLoader(),
62
- new GithubLoader(),
63
- new GraphQLFileLoader(),
64
- new JsonFileLoader(),
65
- new UrlLoader(),
66
- new ApolloEngineLoader(),
67
- new PrismaLoader()
68
- ],
53
+ loaders: [new GraphQLFileLoader(), ...extraLoaders],
69
54
  cwd,
70
55
  includeSources: true
71
56
  });
@@ -80,23 +65,52 @@ ${messages}`);
80
65
  if (!outputSchemaAst.extensions) {
81
66
  outputSchemaAst.extensions = {};
82
67
  }
83
- outputSchemaAst.extensions["hash"] = hashSchema(outputSchemaAst);
68
+ outputSchemaAst.extensions.hash = hashSchema(outputSchemaAst);
84
69
  return {
85
70
  outputSchemaAst,
86
71
  outputSchema: getCachedDocumentNodeFromSchema2(outputSchemaAst)
87
72
  };
88
73
  }
89
74
 
75
+ // utils/scalars.ts
76
+ import { dirname, isAbsolute, joinSafe, relative } from "@baeta/util-path";
77
+ import { parseMapper } from "@graphql-codegen/visitor-plugin-common";
78
+ function buildScalarMap(map, cwd, typesPath) {
79
+ if (!map) {
80
+ return {};
81
+ }
82
+ const fixedMap = {};
83
+ for (const key in map) {
84
+ const mapped = parseMapper(map[key]);
85
+ if (!mapped.isExternal) {
86
+ fixedMap[key] = map[key];
87
+ continue;
88
+ }
89
+ if (isAbsolute(mapped.source)) {
90
+ fixedMap[key] = map[key];
91
+ continue;
92
+ }
93
+ const scalarPath = joinSafe(cwd, mapped.source);
94
+ const relativePath = relative(dirname(typesPath), scalarPath);
95
+ if (mapped.default) {
96
+ fixedMap[key] = `${relativePath}#default`;
97
+ continue;
98
+ }
99
+ fixedMap[key] = `${relativePath}#${mapped.import}`;
100
+ }
101
+ return fixedMap;
102
+ }
103
+
90
104
  // lib/context/index.ts
91
105
  var context_exports = {};
92
106
  __export(context_exports, {
93
107
  default: () => context_default,
94
108
  plugin: () => plugin
95
109
  });
96
- import { buildMapperImport, parseMapper } from "@graphql-codegen/visitor-plugin-common";
110
+ import { buildMapperImport, parseMapper as parseMapper2 } from "@graphql-codegen/visitor-plugin-common";
97
111
  var plugin = async (schema, documents, config) => {
98
112
  const prepend = [];
99
- const mapper = parseMapper(config.contextType || "any");
113
+ const mapper = parseMapper2(config.contextType || "any");
100
114
  if (mapper.isExternal && mapper.source) {
101
115
  const identifier = mapper.default ? "ContextType" : `${mapper.import} as ContextType`;
102
116
  const result = buildMapperImport(
@@ -124,7 +138,7 @@ var plugin = async (schema, documents, config) => {
124
138
  var context_default = { plugin };
125
139
 
126
140
  // lib/modules/index.ts
127
- import { join, relative, resolve } from "@baeta/util-path";
141
+ import { basename, join, relative as relative2, resolve } from "@baeta/util-path";
128
142
  import { BaseVisitor, getConfigValue } from "@graphql-codegen/visitor-plugin-common";
129
143
  import {
130
144
  concatAST,
@@ -134,19 +148,61 @@ import {
134
148
  // lib/modules/builder.ts
135
149
  import { pascalCase } from "change-case-all";
136
150
  import {
137
- Kind as Kind2,
151
+ Kind as Kind3,
138
152
  isInterfaceType,
139
153
  isScalarType,
140
154
  isUnionType,
141
155
  visit
142
156
  } from "graphql";
143
157
 
158
+ // lib/modules/hashes.ts
159
+ import {
160
+ Kind
161
+ } from "graphql";
162
+ import hash from "murmurhash";
163
+ function getObjectTypeHash(node) {
164
+ const fieldNames = buildFieldsNames(node.fields);
165
+ const typeFields = fieldNames.map(([fieldName, fieldType]) => `${fieldName}:${fieldType}`).join(",");
166
+ const fieldMap = {};
167
+ for (const [fieldName, fieldType] of fieldNames) {
168
+ fieldMap[fieldName] = hash.v3(fieldType).toString(36);
169
+ }
170
+ return {
171
+ hash: hash.v3(typeFields).toString(36),
172
+ fieldsHashes: fieldMap
173
+ };
174
+ }
175
+ function buildFieldsNames(fields = []) {
176
+ if (fields.length === 0) {
177
+ return [];
178
+ }
179
+ const fieldsNames = [];
180
+ for (const field of fields) {
181
+ const fieldName = field.name.value;
182
+ const fieldType = buildTypeName(field.type);
183
+ fieldsNames.push([fieldName, fieldType]);
184
+ }
185
+ return fieldsNames.sort(([a], [b]) => a.localeCompare(b));
186
+ }
187
+ function buildTypeName(node) {
188
+ if (node.kind === Kind.NAMED_TYPE) {
189
+ return node.name.value;
190
+ }
191
+ if (node.kind === Kind.LIST_TYPE) {
192
+ return `[${buildTypeName(node.type)}]`;
193
+ }
194
+ if (node.kind === Kind.NON_NULL_TYPE) {
195
+ return `${buildTypeName(node.type)}!`;
196
+ }
197
+ return "";
198
+ }
199
+
144
200
  // lib/modules/utils.ts
145
201
  import { platform } from "node:os";
146
202
  import { getBaseType } from "@graphql-codegen/plugin-helpers";
147
203
  import { DEFAULT_SCALARS, wrapTypeWithModifiers } from "@graphql-codegen/visitor-plugin-common";
148
204
  import {
149
- Kind
205
+ Kind as Kind2
150
206
  } from "graphql";
151
207
  import parse from "parse-filepath";
152
208
  var sep = "/";
@@ -159,7 +215,7 @@ function collectUsedTypes(doc) {
159
215
  pushUnique(used, type);
160
216
  }
161
217
  function findRelated(node) {
162
- if (node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_EXTENSION) {
218
+ if (node.kind === Kind2.OBJECT_TYPE_DEFINITION || node.kind === Kind2.OBJECT_TYPE_EXTENSION) {
163
219
  markAsUsed(node.name.value);
164
220
  if (node.fields) {
165
221
  for (const field of node.fields) {
@@ -171,14 +227,14 @@ function collectUsedTypes(doc) {
171
227
  findRelated(_interface);
172
228
  }
173
229
  }
174
- } else if (node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION) {
230
+ } else if (node.kind === Kind2.INPUT_OBJECT_TYPE_DEFINITION || node.kind === Kind2.INPUT_OBJECT_TYPE_EXTENSION) {
175
231
  markAsUsed(node.name.value);
176
232
  if (node.fields) {
177
233
  for (const field of node.fields) {
178
234
  findRelated(field);
179
235
  }
180
236
  }
181
- } else if (node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_EXTENSION) {
237
+ } else if (node.kind === Kind2.INTERFACE_TYPE_DEFINITION || node.kind === Kind2.INTERFACE_TYPE_EXTENSION) {
182
238
  markAsUsed(node.name.value);
183
239
  if (node.fields) {
184
240
  for (const field of node.fields) {
@@ -190,29 +246,29 @@ function collectUsedTypes(doc) {
190
246
  findRelated(_interface);
191
247
  }
192
248
  }
193
- } else if (node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_EXTENSION) {
249
+ } else if (node.kind === Kind2.UNION_TYPE_DEFINITION || node.kind === Kind2.UNION_TYPE_EXTENSION) {
194
250
  markAsUsed(node.name.value);
195
251
  if (node.types) {
196
252
  for (const type of node.types) {
197
253
  findRelated(type);
198
254
  }
199
255
  }
200
- } else if (node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_EXTENSION) {
256
+ } else if (node.kind === Kind2.ENUM_TYPE_DEFINITION || node.kind === Kind2.ENUM_TYPE_EXTENSION) {
201
257
  markAsUsed(node.name.value);
202
- } else if (node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.SCALAR_TYPE_EXTENSION) {
258
+ } else if (node.kind === Kind2.SCALAR_TYPE_DEFINITION || node.kind === Kind2.SCALAR_TYPE_EXTENSION) {
203
259
  if (!isGraphQLPrimitive(node.name.value)) {
204
260
  markAsUsed(node.name.value);
205
261
  }
206
- } else if (node.kind === Kind.INPUT_VALUE_DEFINITION) {
262
+ } else if (node.kind === Kind2.INPUT_VALUE_DEFINITION) {
207
263
  findRelated(resolveTypeNode(node.type));
208
- } else if (node.kind === Kind.FIELD_DEFINITION) {
264
+ } else if (node.kind === Kind2.FIELD_DEFINITION) {
209
265
  findRelated(resolveTypeNode(node.type));
210
266
  if (node.arguments) {
211
267
  for (const argument of node.arguments) {
212
268
  findRelated(argument);
213
269
  }
214
270
  }
215
- } else if (node.kind === Kind.NAMED_TYPE && // Named type
271
+ } else if (node.kind === Kind2.NAMED_TYPE && // Named type
216
272
  !isGraphQLPrimitive(node.name.value)) {
217
273
  markAsUsed(node.name.value);
218
274
  }
@@ -256,7 +312,7 @@ function collectObjectFieldTypesAndArguments(schema) {
256
312
  }
257
313
  const schemaTypes = schema.getTypeMap();
258
314
  for (const type of Object.values(schemaTypes)) {
259
- if (type.astNode?.kind !== Kind.OBJECT_TYPE_DEFINITION) {
315
+ if (type.astNode?.kind !== Kind2.OBJECT_TYPE_DEFINITION) {
260
316
  continue;
261
317
  }
262
318
  const schemaType = schemaTypes[type.name];
@@ -269,10 +325,10 @@ function collectObjectFieldTypesAndArguments(schema) {
269
325
  return { fieldTypes, fieldArguments };
270
326
  }
271
327
  function resolveTypeNode(node) {
272
- if (node.kind === Kind.LIST_TYPE) {
328
+ if (node.kind === Kind2.LIST_TYPE) {
273
329
  return resolveTypeNode(node.type);
274
330
  }
275
- if (node.kind === Kind.NON_NULL_TYPE) {
331
+ if (node.kind === Kind2.NON_NULL_TYPE) {
276
332
  return resolveTypeNode(node.type);
277
333
  }
278
334
  return node;
@@ -392,6 +448,7 @@ function buildModule(name, doc, {
392
448
  );
393
449
  const defined = createObject(registryKeys, () => []);
394
450
  const extended = createObject(registryKeys, () => []);
451
+ const hashes = {};
395
452
  const usedTypes = collectUsedTypes(doc);
396
453
  visit(doc, {
397
454
  ObjectTypeDefinition(node) {
@@ -438,7 +495,7 @@ function buildModule(name, doc, {
438
495
  );
439
496
  const imports = [
440
497
  `import * as ${importNamespace} from "${importPath}";`,
441
- 'import { DocumentNode } from "graphql";',
498
+ 'import type { DocumentNode } from "graphql";',
442
499
  'import * as Baeta from "@baeta/core/sdk";'
443
500
  ];
444
501
  if (extensionsPath) {
@@ -472,6 +529,7 @@ ${shouldDeclare ? `${indent(2)(imports.join("\n"))}
472
529
  return `export namespace ModuleMetadata {
473
530
  export const id = '${name}';
474
531
  export const dirname = './${name}';
532
+ export const hashes = ${JSON.stringify(hashes)};
475
533
  export const typedef = ${JSON.stringify(doc)} as unknown as DocumentNode;
476
534
  ${printBaetaManager()}
477
535
  }`;
@@ -716,31 +774,32 @@ ${body}
716
774
  function collectTypeDefinition(node) {
717
775
  const name2 = node.name.value;
718
776
  switch (node.kind) {
719
- case Kind2.OBJECT_TYPE_DEFINITION: {
777
+ case Kind3.OBJECT_TYPE_DEFINITION: {
720
778
  defined.objects.push(name2);
721
779
  collectFields(node, picks.objects);
780
+ hashes[name2] = getObjectTypeHash(node);
722
781
  break;
723
782
  }
724
- case Kind2.ENUM_TYPE_DEFINITION: {
783
+ case Kind3.ENUM_TYPE_DEFINITION: {
725
784
  defined.enums.push(name2);
726
785
  collectValuesFromEnum(node);
727
786
  break;
728
787
  }
729
- case Kind2.INPUT_OBJECT_TYPE_DEFINITION: {
788
+ case Kind3.INPUT_OBJECT_TYPE_DEFINITION: {
730
789
  defined.inputs.push(name2);
731
790
  collectFields(node, picks.inputs);
732
791
  break;
733
792
  }
734
- case Kind2.SCALAR_TYPE_DEFINITION: {
793
+ case Kind3.SCALAR_TYPE_DEFINITION: {
735
794
  defined.scalars.push(name2);
736
795
  break;
737
796
  }
738
- case Kind2.INTERFACE_TYPE_DEFINITION: {
797
+ case Kind3.INTERFACE_TYPE_DEFINITION: {
739
798
  defined.interfaces.push(name2);
740
799
  collectFields(node, picks.interfaces);
741
800
  break;
742
801
  }
743
- case Kind2.UNION_TYPE_DEFINITION: {
802
+ case Kind3.UNION_TYPE_DEFINITION: {
744
803
  defined.unions.push(name2);
745
804
  collectUnionTypes(node);
746
805
  break;
@@ -750,8 +809,9 @@ ${body}
750
809
  function collectTypeExtension(node) {
751
810
  const name2 = node.name.value;
752
811
  switch (node.kind) {
753
- case Kind2.OBJECT_TYPE_EXTENSION: {
812
+ case Kind3.OBJECT_TYPE_EXTENSION: {
754
813
  collectFields(node, picks.objects);
814
+ hashes[name2] = getObjectTypeHash(node);
755
815
  if (rootTypes.includes(name2)) {
756
816
  pushUnique(defined.objects, name2);
757
817
  return;
@@ -759,22 +819,22 @@ ${body}
759
819
  pushUnique(extended.objects, name2);
760
820
  break;
761
821
  }
762
- case Kind2.ENUM_TYPE_EXTENSION: {
822
+ case Kind3.ENUM_TYPE_EXTENSION: {
763
823
  collectValuesFromEnum(node);
764
824
  pushUnique(extended.enums, name2);
765
825
  break;
766
826
  }
767
- case Kind2.INPUT_OBJECT_TYPE_EXTENSION: {
827
+ case Kind3.INPUT_OBJECT_TYPE_EXTENSION: {
768
828
  collectFields(node, picks.inputs);
769
829
  pushUnique(extended.inputs, name2);
770
830
  break;
771
831
  }
772
- case Kind2.INTERFACE_TYPE_EXTENSION: {
832
+ case Kind3.INTERFACE_TYPE_EXTENSION: {
773
833
  collectFields(node, picks.interfaces);
774
834
  pushUnique(extended.interfaces, name2);
775
835
  break;
776
836
  }
777
- case Kind2.UNION_TYPE_EXTENSION: {
837
+ case Kind3.UNION_TYPE_EXTENSION: {
778
838
  pushUnique(extended.unions, name2);
779
839
  break;
780
840
  }
@@ -782,17 +842,17 @@ ${body}
782
842
  }
783
843
  function getParentType(type) {
784
844
  if (["Query", "Mutation", "Subscription"].includes(type)) {
785
- return "{}";
845
+ return "{ }";
786
846
  }
787
847
  return type;
788
848
  }
789
849
  function getResultType(type, field) {
790
- return fieldTypes?.[type]?.[field] || "{}";
850
+ return fieldTypes?.[type]?.[field] || "{ }";
791
851
  }
792
852
  function getArgsType(type, field) {
793
853
  const hasArgs = fieldArguments?.[type]?.[field] ?? false;
794
854
  if (!hasArgs) {
795
- return "{}";
855
+ return "{ }";
796
856
  }
797
857
  const fieldUpper = field[0].toUpperCase() + field.slice(1);
798
858
  return `Types.${type}${fieldUpper}Args`;
@@ -806,7 +866,7 @@ ${body}
806
866
  var preset = {
807
867
  buildGeneratesSection: (options) => {
808
868
  const { baseOutputDir } = options;
809
- const { baseTypesPath, extensionsPath, encapsulateModuleTypes } = options.presetConfig;
869
+ const { baseTypesPath, extensionsPath, encapsulateModuleTypes, importExtension } = options.presetConfig;
810
870
  const requireRootResolvers = getConfigValue(options?.presetConfig.requireRootResolvers, false);
811
871
  const cwd = resolve(options.presetConfig.cwd || process.cwd());
812
872
  const importTypesNamespace = options.presetConfig.importTypesNamespace || "Types";
@@ -973,12 +1033,12 @@ ${result}
973
1033
  },
974
1034
  schemaAst: options.schemaAst
975
1035
  };
976
- const baseTypesFilename = baseTypesPath.replace(/\.(js|ts|d.ts)$/, "");
1036
+ const baseTypesFilename = basename(baseTypesPath).replace(/\.(js|ts|d.ts)$/, "") + (importExtension || "");
977
1037
  const baseTypesDir = stripFilename(baseOutput.filename);
978
1038
  const outputs = modules.map((moduleName) => {
979
1039
  const filename = resolve(cwd, baseOutputDir, moduleName, options.presetConfig.filename);
980
1040
  const dirpath = stripFilename(filename);
981
- const relativePath = relative(dirpath, baseTypesDir);
1041
+ const relativePath = relative2(dirpath, baseTypesDir);
982
1042
  const importPath = options.presetConfig.importBaseTypesFrom || normalize(join(relativePath, baseTypesFilename));
983
1043
  const sources2 = sourcesByModuleMap[moduleName];
984
1044
  const documents = sources2.map((source) => source.document);
@@ -1049,9 +1109,9 @@ async function generate(options) {
1049
1109
  Object.assign(schemaPointerMap, ptr);
1050
1110
  }
1051
1111
  }
1052
- const hash = JSON.stringify(schemaPointerMap);
1053
- const result = await cache("schema", hash, async () => {
1054
- return loadSchema(schemaPointerMap, options.cwd);
1112
+ const hash2 = JSON.stringify(schemaPointerMap);
1113
+ const result = await cache("schema", hash2, async () => {
1114
+ return loadSchema(schemaPointerMap, options.cwd, options.loaders);
1055
1115
  });
1056
1116
  const outputs = await preset.buildGeneratesSection({
1057
1117
  baseOutputDir: options.modulesDir,
@@ -1059,7 +1119,8 @@ async function generate(options) {
1059
1119
  baseTypesPath: rootConfig.baseTypesPath,
1060
1120
  filename: rootConfig.moduleDefinitionName,
1061
1121
  encapsulateModuleTypes: "none",
1062
- extensionsPath: options.extensions
1122
+ extensionsPath: options.extensions,
1123
+ importExtension: options.importExtension
1063
1124
  },
1064
1125
  schema: result.outputSchema,
1065
1126
  schemaAst: result.outputSchemaAst,
@@ -1070,9 +1131,11 @@ async function generate(options) {
1070
1131
  inputMaybeValue: "T | undefined",
1071
1132
  contextType: rootConfig.contextType,
1072
1133
  useTypeImports: true,
1073
- scalars: {
1074
- ...rootConfig.scalars
1075
- }
1134
+ scalars: buildScalarMap(
1135
+ rootConfig.scalars,
1136
+ options.cwd,
1137
+ join2(options.modulesDir, options.baseTypesPath)
1138
+ )
1076
1139
  }
1077
1140
  });
1078
1141
  const promises = outputs.map(async (output) => {