@baeta/plugin-graphql 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs DELETED
@@ -1,1215 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
-
26
- // index.ts
27
- var graphql_exports = {};
28
- __export(graphql_exports, {
29
- default: () => graphql_default
30
- });
31
- module.exports = __toCommonJS(graphql_exports);
32
- var import_plugin2 = require("@baeta/plugin");
33
-
34
- // lib/codegen.ts
35
- var import_plugin = require("@baeta/plugin");
36
- var import_core = require("@graphql-codegen/core");
37
- var import_plugin_helpers4 = require("@graphql-codegen/plugin-helpers");
38
- var typescriptPlugin = __toESM(require("@graphql-codegen/typescript"), 1);
39
- var import_path2 = __toESM(require("path"), 1);
40
-
41
- // modules/index.ts
42
- var import_visitor_plugin_common = require("@graphql-codegen/visitor-plugin-common");
43
- var import_graphql3 = require("graphql");
44
- var import_path = require("path");
45
-
46
- // modules/builder.ts
47
- var import_change_case_all = require("change-case-all");
48
- var import_graphql2 = require("graphql");
49
-
50
- // modules/utils.ts
51
- var import_graphql = require("graphql");
52
- var import_parse_filepath = __toESM(require("parse-filepath"), 1);
53
- var sep = "/";
54
- function collectUsedTypes(doc) {
55
- const used = [];
56
- doc.definitions.forEach(findRelated);
57
- function markAsUsed(type) {
58
- pushUnique(used, type);
59
- }
60
- function findRelated(node) {
61
- if (node.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || node.kind === import_graphql.Kind.OBJECT_TYPE_EXTENSION) {
62
- markAsUsed(node.name.value);
63
- if (node.fields) {
64
- node.fields.forEach(findRelated);
65
- }
66
- if (node.interfaces) {
67
- node.interfaces.forEach(findRelated);
68
- }
69
- } else if (node.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) {
70
- markAsUsed(node.name.value);
71
- if (node.fields) {
72
- node.fields.forEach(findRelated);
73
- }
74
- } else if (node.kind === import_graphql.Kind.INTERFACE_TYPE_DEFINITION || node.kind === import_graphql.Kind.INTERFACE_TYPE_EXTENSION) {
75
- markAsUsed(node.name.value);
76
- if (node.fields) {
77
- node.fields.forEach(findRelated);
78
- }
79
- if (node.interfaces) {
80
- node.interfaces.forEach(findRelated);
81
- }
82
- } else if (node.kind === import_graphql.Kind.UNION_TYPE_DEFINITION || node.kind === import_graphql.Kind.UNION_TYPE_EXTENSION) {
83
- markAsUsed(node.name.value);
84
- if (node.types) {
85
- node.types.forEach(findRelated);
86
- }
87
- } else if (node.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION || node.kind === import_graphql.Kind.ENUM_TYPE_EXTENSION) {
88
- markAsUsed(node.name.value);
89
- } else if (node.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION || node.kind === import_graphql.Kind.SCALAR_TYPE_EXTENSION) {
90
- if (!isGraphQLPrimitive(node.name.value)) {
91
- markAsUsed(node.name.value);
92
- }
93
- } else if (node.kind === import_graphql.Kind.INPUT_VALUE_DEFINITION) {
94
- findRelated(resolveTypeNode(node.type));
95
- } else if (node.kind === import_graphql.Kind.FIELD_DEFINITION) {
96
- findRelated(resolveTypeNode(node.type));
97
- if (node.arguments) {
98
- node.arguments.forEach(findRelated);
99
- }
100
- } else if (node.kind === import_graphql.Kind.NAMED_TYPE && !isGraphQLPrimitive(node.name.value)) {
101
- markAsUsed(node.name.value);
102
- }
103
- }
104
- return used;
105
- }
106
- function resolveTypeNode(node) {
107
- if (node.kind === import_graphql.Kind.LIST_TYPE) {
108
- return resolveTypeNode(node.type);
109
- }
110
- if (node.kind === import_graphql.Kind.NON_NULL_TYPE) {
111
- return resolveTypeNode(node.type);
112
- }
113
- return node;
114
- }
115
- function isGraphQLPrimitive(name) {
116
- return ["String", "Boolean", "ID", "Float", "Int"].includes(name);
117
- }
118
- function unique(val, i, all) {
119
- return i === all.indexOf(val);
120
- }
121
- function withQuotes(val) {
122
- return `'${val}'`;
123
- }
124
- function indent(size) {
125
- const space = new Array(size).fill(" ").join("");
126
- function indentInner(val) {
127
- return val.split("\n").map((line) => `${space}${line}`).join("\n");
128
- }
129
- return indentInner;
130
- }
131
- function buildBlock({ name, lines }) {
132
- if (!lines.length) {
133
- return "";
134
- }
135
- return [`${name} {`, ...lines.map(indent(2)), "};"].join("\n");
136
- }
137
- var getRelativePath = function(filepath, basePath) {
138
- const normalizedFilepath = normalize(filepath);
139
- const normalizedBasePath = ensureStartsWithSeparator(
140
- normalize(ensureEndsWithSeparator(basePath))
141
- );
142
- const [, relativePath] = normalizedFilepath.split(normalizedBasePath);
143
- return relativePath;
144
- };
145
- function groupSourcesByModule(sources, basePath) {
146
- const grouped = {};
147
- sources.forEach((source) => {
148
- if (!source.location) {
149
- return;
150
- }
151
- const relativePath = getRelativePath(source.location, basePath);
152
- if (relativePath) {
153
- const mod = extractModuleDirectory(source.location, basePath);
154
- if (!grouped[mod]) {
155
- grouped[mod] = [];
156
- }
157
- grouped[mod].push(source);
158
- }
159
- });
160
- return grouped;
161
- }
162
- function extractModuleDirectory(filepath, basePath) {
163
- const relativePath = getRelativePath(filepath, basePath);
164
- const [moduleDirectory] = relativePath.split(sep);
165
- return moduleDirectory;
166
- }
167
- function stripFilename(path2) {
168
- const parsedPath = (0, import_parse_filepath.default)(path2);
169
- return normalize(parsedPath.dir);
170
- }
171
- function normalize(path2) {
172
- return path2.replace(/\\/g, "/");
173
- }
174
- function ensureEndsWithSeparator(path2) {
175
- return path2.endsWith(sep) ? path2 : path2 + sep;
176
- }
177
- function ensureStartsWithSeparator(path2) {
178
- return path2.startsWith(".") ? path2.replace(/^(..\/)|(.\/)/, "/") : path2.startsWith("/") ? path2 : `/${path2}`;
179
- }
180
- function pushUnique(list, item) {
181
- if (!list.includes(item)) {
182
- list.push(item);
183
- }
184
- }
185
- function concatByKey(left, right, key) {
186
- return [.../* @__PURE__ */ new Set([...left[key], ...right[key]])];
187
- }
188
- function uniqueByKey(left, right, key) {
189
- return left[key].filter((item) => !right[key].includes(item));
190
- }
191
- function createObject(keys, valueFn) {
192
- const obj = {};
193
- keys.forEach((key) => {
194
- obj[key] = valueFn(key);
195
- });
196
- return obj;
197
- }
198
-
199
- // modules/builder.ts
200
- var registryKeys = [
201
- "objects",
202
- "inputs",
203
- "interfaces",
204
- "scalars",
205
- "unions",
206
- "enums"
207
- ];
208
- var resolverKeys = [
209
- "scalars",
210
- "objects",
211
- "enums"
212
- ];
213
- function buildModule(name, doc, {
214
- importNamespace,
215
- importPath,
216
- encapsulate,
217
- requireRootResolvers,
218
- shouldDeclare,
219
- rootTypes,
220
- schema,
221
- baseVisitor
222
- }) {
223
- const picks = createObject(
224
- registryKeys,
225
- () => ({})
226
- );
227
- const defined = createObject(registryKeys, () => []);
228
- const extended = createObject(registryKeys, () => []);
229
- const usedTypes = collectUsedTypes(doc);
230
- (0, import_graphql2.visit)(doc, {
231
- ObjectTypeDefinition(node) {
232
- collectTypeDefinition(node);
233
- },
234
- ObjectTypeExtension(node) {
235
- collectTypeExtension(node);
236
- },
237
- InputObjectTypeDefinition(node) {
238
- collectTypeDefinition(node);
239
- },
240
- InputObjectTypeExtension(node) {
241
- collectTypeExtension(node);
242
- },
243
- InterfaceTypeDefinition(node) {
244
- collectTypeDefinition(node);
245
- },
246
- InterfaceTypeExtension(node) {
247
- collectTypeExtension(node);
248
- },
249
- ScalarTypeDefinition(node) {
250
- collectTypeDefinition(node);
251
- },
252
- UnionTypeDefinition(node) {
253
- collectTypeDefinition(node);
254
- },
255
- UnionTypeExtension(node) {
256
- collectTypeExtension(node);
257
- },
258
- EnumTypeDefinition(node) {
259
- collectTypeDefinition(node);
260
- },
261
- EnumTypeExtension(node) {
262
- collectTypeExtension(node);
263
- }
264
- });
265
- const visited = createObject(
266
- registryKeys,
267
- (key) => concatByKey(defined, extended, key)
268
- );
269
- const external = createObject(
270
- registryKeys,
271
- (key) => uniqueByKey(extended, defined, key)
272
- );
273
- const imports = [
274
- `import * as ${importNamespace} from "${importPath}";`,
275
- 'import { DocumentNode } from "graphql";',
276
- 'import * as Baeta from "@baeta/core/sdk";'
277
- ];
278
- let content = [
279
- printDefinedFields(),
280
- printDefinedEnumValues(),
281
- printDefinedInputFields(),
282
- printSchemaTypes(usedTypes),
283
- printScalars(visited),
284
- printResolveSignaturesPerType(visited),
285
- printResolversType(visited),
286
- printMetadata()
287
- ].filter(Boolean).join("\n\n");
288
- const moduleNamespace = baseVisitor.convertName(name, {
289
- suffix: "Module",
290
- useTypesPrefix: false,
291
- useTypesSuffix: false
292
- });
293
- if (encapsulate === "namespace") {
294
- content = `${shouldDeclare ? "declare" : "export"} namespace ${baseVisitor.convertName(name, {
295
- suffix: "Module",
296
- useTypesPrefix: false,
297
- useTypesSuffix: false
298
- })} {
299
- ${shouldDeclare ? `${indent(2)(imports.join("\n"))}
300
- ` : ""}${indent(2)(content)}
301
- }`;
302
- }
303
- return [...shouldDeclare ? [] : imports, content, printFactoryMethod()].filter(Boolean).join("\n");
304
- function printMetadata() {
305
- return `export namespace ModuleMetadata {
306
- export const id = '${name}';
307
- export const dirname = './${name}';
308
- export const typedef = ${JSON.stringify(doc)} as unknown as DocumentNode;
309
- ${printBaetaManager()}
310
- }`;
311
- }
312
- function printDefinedFields() {
313
- return buildBlock({
314
- name: "interface DefinedFields",
315
- lines: [...visited.objects, ...visited.interfaces].map(
316
- (typeName) => `${typeName}: ${printPicks(typeName, {
317
- ...picks.objects,
318
- ...picks.interfaces
319
- })};`
320
- )
321
- });
322
- }
323
- function printFactoryMethod() {
324
- const name2 = moduleNamespace.slice(0, moduleNamespace.length - 6);
325
- const createModuleFn = `create${name2}Module`;
326
- const getModuleFn = `get${name2}Module`;
327
- return `
328
- export const ${createModuleFn} = () => Baeta.createModuleManager(ModuleMetadata);
329
- export const ${getModuleFn} = Baeta.createSingletonModule(${createModuleFn});
330
- `;
331
- }
332
- function printObjectFieldResolverBuilder(typeName, field) {
333
- const resolverType = `${typeName}Resolvers["${field}"]`;
334
- return `${field}: Baeta.createResolverBuilder<NonNullable<${resolverType}>>(module, "${typeName}", "${field}"),`;
335
- }
336
- function printObjectResolverBuilder(typeName, objects) {
337
- const fields = objects[typeName]?.filter(unique).map((field) => printObjectFieldResolverBuilder(typeName, field)) ?? [];
338
- if (fields.length === 0) {
339
- return "";
340
- }
341
- const resolversType = `${typeName}Resolvers`;
342
- const content2 = `{
343
- ${fields.map(indent(2)).join("\n")}
344
- }`;
345
- return `${typeName}: Baeta.aggregateResolvers(module, "${typeName}", {} as ${resolversType}, ${content2}),`;
346
- }
347
- function printSubscriptionFieldBuilder(field) {
348
- const resolverType = `SubscriptionResolvers["${field}"]`;
349
- return `${field}: Baeta.createSubscriptionBuilder<${resolverType}>(module, "${field}"),`;
350
- }
351
- function printSubscriptionObjectBuilder() {
352
- const subscriptions = picks.objects["Subscription"]?.filter(unique) ?? [];
353
- if (subscriptions.length === 0) {
354
- return "";
355
- }
356
- const fields = subscriptions.map((subscription) => printSubscriptionFieldBuilder(subscription));
357
- const resolversType = "SubscriptionResolvers";
358
- const content2 = `{
359
- ${fields.map(indent(2)).join("\n")}
360
- }`;
361
- return `Subscription: Baeta.aggregateSubscriptions(module, {} as ${resolversType}, ${content2}),`;
362
- }
363
- function printScalarBuilder() {
364
- const scalars = visited.scalars;
365
- if (scalars.length === 0) {
366
- return "";
367
- }
368
- const fields = scalars.map(
369
- (scalar) => `${scalar}: Baeta.createScalarBuilder(module, "${scalar}"),`
370
- );
371
- const content2 = fields.map(indent(2)).join("\n");
372
- return `Scalar: {
373
- ${content2}
374
- },`;
375
- }
376
- function printBaetaManager() {
377
- const objects = visited.objects.filter((type) => type !== "Subscription").map((typeName) => printObjectResolverBuilder(typeName, picks.objects)).filter(Boolean);
378
- const bodyFields = [...objects, printScalarBuilder(), printSubscriptionObjectBuilder()];
379
- const body = bodyFields.filter(Boolean).map(indent(6)).join("\n");
380
- const content2 = `{
381
- ${body}
382
- }`;
383
- return `
384
- export function createManager(module: Baeta.ModuleBuilder) {
385
- return Baeta.aggregateBuilders(module, {} as Resolvers, ${content2});
386
- }`;
387
- }
388
- function printDefinedEnumValues() {
389
- return buildBlock({
390
- name: "interface DefinedEnumValues",
391
- lines: visited.enums.map((typeName) => `${typeName}: ${printPicks(typeName, picks.enums)};`)
392
- });
393
- }
394
- function encapsulateTypeName(typeName) {
395
- if (encapsulate === "prefix") {
396
- return `${(0, import_change_case_all.pascalCase)(name)}_${typeName}`;
397
- }
398
- return typeName;
399
- }
400
- function printDefinedInputFields() {
401
- return buildBlock({
402
- name: "interface DefinedInputFields",
403
- lines: visited.inputs.map(
404
- (typeName) => `${typeName}: ${printPicks(typeName, picks.inputs)};`
405
- )
406
- });
407
- }
408
- function printSchemaTypes(types) {
409
- return types.filter((type) => !visited.scalars.includes(type)).map(printExportType).join("\n");
410
- }
411
- function printResolveSignaturesPerType(registry) {
412
- return [
413
- [...registry.objects, ...registry.interfaces].map(
414
- (name2) => printResolverType(
415
- name2,
416
- "DefinedFields",
417
- requireRootResolvers && rootTypes.includes(name2),
418
- !rootTypes.includes(name2) && defined.objects.includes(name2) ? ` | '__isTypeOf'` : ""
419
- )
420
- ).join("\n")
421
- ].join("\n");
422
- }
423
- function printScalars(registry) {
424
- if (!registry.scalars.length) {
425
- return "";
426
- }
427
- return [
428
- `export type ${encapsulateTypeName(
429
- "Scalars"
430
- )} = Pick<${importNamespace}.Scalars, ${registry.scalars.map(withQuotes).join(" | ")}>;`,
431
- ...registry.scalars.map((scalar) => {
432
- const convertedName = baseVisitor.convertName(scalar, {
433
- suffix: "ScalarConfig"
434
- });
435
- return `export type ${encapsulateTypeName(
436
- convertedName
437
- )} = ${importNamespace}.${convertedName};`;
438
- })
439
- ].join("\n");
440
- }
441
- function printResolversType(registry) {
442
- const lines = [];
443
- for (const kind in registry) {
444
- if (!Object.prototype.hasOwnProperty.call(registry, kind)) {
445
- continue;
446
- }
447
- if (!resolverKeys.includes(kind)) {
448
- continue;
449
- }
450
- const k = kind;
451
- const types = registry[k];
452
- types.forEach((typeName) => {
453
- if (k === "enums") {
454
- return;
455
- }
456
- if (k === "scalars") {
457
- lines.push(
458
- `${typeName}?: ${encapsulateTypeName(importNamespace)}.Resolvers['${typeName}'];`
459
- );
460
- } else {
461
- const fieldModifier = requireRootResolvers && rootTypes.includes(typeName) ? "" : "?";
462
- lines.push(`${typeName}${fieldModifier}: ${encapsulateTypeName(typeName)}Resolvers;`);
463
- }
464
- });
465
- }
466
- return buildBlock({
467
- name: `export interface ${encapsulateTypeName("Resolvers")}`,
468
- lines
469
- });
470
- }
471
- function printResolverType(typeName, picksTypeName, requireFieldsResolvers = false, extraKeys = "") {
472
- const typeSignature = `Pick<${importNamespace}.${baseVisitor.convertName(typeName, {
473
- suffix: "Resolvers"
474
- })}, ${picksTypeName}['${typeName}']${extraKeys}>`;
475
- return `export type ${encapsulateTypeName(`${typeName}Resolvers`)} = ${requireFieldsResolvers ? `Required<${typeSignature}>` : typeSignature};`;
476
- }
477
- function printPicks(typeName, records) {
478
- return records[typeName].filter(unique).map(withQuotes).join(" | ");
479
- }
480
- function printTypeBody(typeName) {
481
- const coreType = `${importNamespace}.${baseVisitor.convertName(typeName, {
482
- useTypesSuffix: true,
483
- useTypesPrefix: true
484
- })}`;
485
- if (external.enums.includes(typeName) || external.objects.includes(typeName)) {
486
- if (schema && (0, import_graphql2.isScalarType)(schema.getType(typeName))) {
487
- return `${importNamespace}.Scalars['${typeName}']`;
488
- }
489
- return coreType;
490
- }
491
- if (defined.enums.includes(typeName) && picks.enums[typeName]) {
492
- return `DefinedEnumValues['${typeName}']`;
493
- }
494
- if (defined.objects.includes(typeName) && picks.objects[typeName]) {
495
- return `Pick<${coreType}, DefinedFields['${typeName}']>`;
496
- }
497
- if (defined.interfaces.includes(typeName) && picks.interfaces[typeName]) {
498
- return `Pick<${coreType}, DefinedFields['${typeName}']>`;
499
- }
500
- if (defined.inputs.includes(typeName) && picks.inputs[typeName]) {
501
- return `Pick<${coreType}, DefinedInputFields['${typeName}']>`;
502
- }
503
- return coreType;
504
- }
505
- function printExportType(typeName) {
506
- return `export type ${encapsulateTypeName(typeName)} = ${printTypeBody(typeName)};`;
507
- }
508
- function collectFields(node, picksObj) {
509
- const name2 = node.name.value;
510
- if (node.fields) {
511
- if (!picksObj[name2]) {
512
- picksObj[name2] = [];
513
- }
514
- node.fields.forEach((field) => {
515
- picksObj[name2].push(field.name.value);
516
- });
517
- }
518
- }
519
- function collectValuesFromEnum(node) {
520
- const name2 = node.name.value;
521
- if (node.values) {
522
- if (!picks.enums[name2]) {
523
- picks.enums[name2] = [];
524
- }
525
- node.values.forEach((field) => {
526
- picks.enums[name2].push(field.name.value);
527
- });
528
- }
529
- }
530
- function collectTypeDefinition(node) {
531
- const name2 = node.name.value;
532
- switch (node.kind) {
533
- case import_graphql2.Kind.OBJECT_TYPE_DEFINITION: {
534
- defined.objects.push(name2);
535
- collectFields(node, picks.objects);
536
- break;
537
- }
538
- case import_graphql2.Kind.ENUM_TYPE_DEFINITION: {
539
- defined.enums.push(name2);
540
- collectValuesFromEnum(node);
541
- break;
542
- }
543
- case import_graphql2.Kind.INPUT_OBJECT_TYPE_DEFINITION: {
544
- defined.inputs.push(name2);
545
- collectFields(node, picks.inputs);
546
- break;
547
- }
548
- case import_graphql2.Kind.SCALAR_TYPE_DEFINITION: {
549
- defined.scalars.push(name2);
550
- break;
551
- }
552
- case import_graphql2.Kind.INTERFACE_TYPE_DEFINITION: {
553
- defined.interfaces.push(name2);
554
- collectFields(node, picks.interfaces);
555
- break;
556
- }
557
- case import_graphql2.Kind.UNION_TYPE_DEFINITION: {
558
- defined.unions.push(name2);
559
- break;
560
- }
561
- }
562
- }
563
- function collectTypeExtension(node) {
564
- const name2 = node.name.value;
565
- switch (node.kind) {
566
- case import_graphql2.Kind.OBJECT_TYPE_EXTENSION: {
567
- collectFields(node, picks.objects);
568
- if (rootTypes.includes(name2)) {
569
- pushUnique(defined.objects, name2);
570
- return;
571
- }
572
- pushUnique(extended.objects, name2);
573
- break;
574
- }
575
- case import_graphql2.Kind.ENUM_TYPE_EXTENSION: {
576
- collectValuesFromEnum(node);
577
- pushUnique(extended.enums, name2);
578
- break;
579
- }
580
- case import_graphql2.Kind.INPUT_OBJECT_TYPE_EXTENSION: {
581
- collectFields(node, picks.inputs);
582
- pushUnique(extended.inputs, name2);
583
- break;
584
- }
585
- case import_graphql2.Kind.INTERFACE_TYPE_EXTENSION: {
586
- collectFields(node, picks.interfaces);
587
- pushUnique(extended.interfaces, name2);
588
- break;
589
- }
590
- case import_graphql2.Kind.UNION_TYPE_EXTENSION: {
591
- pushUnique(extended.unions, name2);
592
- break;
593
- }
594
- }
595
- }
596
- }
597
-
598
- // modules/index.ts
599
- var preset = {
600
- buildGeneratesSection: (options) => {
601
- const { baseOutputDir } = options;
602
- const { baseTypesPath, encapsulateModuleTypes } = options.presetConfig;
603
- const requireRootResolvers = (0, import_visitor_plugin_common.getConfigValue)(options?.presetConfig.requireRootResolvers, false);
604
- const cwd = (0, import_path.resolve)(options.presetConfig.cwd || process.cwd());
605
- const importTypesNamespace = options.presetConfig.importTypesNamespace || "Types";
606
- if (!baseTypesPath) {
607
- throw new Error(
608
- `Preset "graphql-modules" requires you to specify "baseTypesPath" configuration and point it to your base types file (generated by "typescript" plugin)!`
609
- );
610
- }
611
- if (!options.schemaAst?.extensions.sources) {
612
- throw new Error(`Preset "graphql-modules" requires to use GraphQL SDL`);
613
- }
614
- const extensions = options.schemaAst?.extensions;
615
- const sources = extensions?.extendedSources ?? [];
616
- const sourcesByModuleMap = groupSourcesByModule(sources, baseOutputDir);
617
- const modules = Object.keys(sourcesByModuleMap);
618
- const baseVisitor = new import_visitor_plugin_common.BaseVisitor(options.config, {});
619
- const baseOutput = {
620
- filename: (0, import_path.resolve)(cwd, baseOutputDir, baseTypesPath),
621
- schema: options.schema,
622
- documents: options.documents,
623
- plugins: [
624
- ...options.plugins,
625
- {
626
- "modules-exported-scalars": {}
627
- }
628
- ],
629
- pluginMap: {
630
- ...options.pluginMap,
631
- "modules-exported-scalars": {
632
- plugin: (schema) => {
633
- const typeMap = schema.getTypeMap();
634
- return Object.keys(typeMap).map((t) => {
635
- if (t && typeMap[t] && (0, import_graphql3.isScalarType)(typeMap[t]) && !isGraphQLPrimitive(t)) {
636
- const convertedName = baseVisitor.convertName(t);
637
- return `export type ${convertedName} = Scalars["${t}"];`;
638
- }
639
- return null;
640
- }).filter(Boolean).join("\n");
641
- }
642
- }
643
- },
644
- config: {
645
- ...options.config,
646
- enumsAsTypes: true
647
- },
648
- schemaAst: options.schemaAst
649
- };
650
- const baseTypesFilename = baseTypesPath.replace(/\.(js|ts|d.ts)$/, "");
651
- const baseTypesDir = stripFilename(baseOutput.filename);
652
- const outputs = modules.map((moduleName) => {
653
- const filename = (0, import_path.resolve)(cwd, baseOutputDir, moduleName, options.presetConfig.filename);
654
- const dirpath = stripFilename(filename);
655
- const relativePath = (0, import_path.relative)(dirpath, baseTypesDir);
656
- const importPath = options.presetConfig.importBaseTypesFrom || normalize((0, import_path.join)(relativePath, baseTypesFilename));
657
- const sources2 = sourcesByModuleMap[moduleName];
658
- const documents = sources2.map((source) => source.document);
659
- const moduleDocument = (0, import_graphql3.concatAST)(documents);
660
- const shouldDeclare = filename.endsWith(".d.ts");
661
- return {
662
- filename,
663
- schema: options.schema,
664
- documents: [],
665
- plugins: [
666
- ...options.plugins.filter((p) => typeof p === "object" && !!p.add),
667
- {
668
- "graphql-modules-plugin": {}
669
- }
670
- ],
671
- pluginMap: {
672
- ...options.pluginMap,
673
- "graphql-modules-plugin": {
674
- plugin: (schema) => buildModule(moduleName, moduleDocument, {
675
- importNamespace: importTypesNamespace,
676
- importPath,
677
- encapsulate: encapsulateModuleTypes || "namespace",
678
- requireRootResolvers,
679
- shouldDeclare,
680
- schema,
681
- baseVisitor,
682
- useGraphQLModules: false,
683
- rootTypes: [
684
- schema.getQueryType()?.name || "",
685
- schema.getMutationType()?.name || "",
686
- schema.getSubscriptionType()?.name || ""
687
- ].filter(Boolean)
688
- })
689
- }
690
- },
691
- config: options.config,
692
- schemaAst: options.schemaAst
693
- };
694
- });
695
- return [baseOutput].concat(outputs);
696
- }
697
- };
698
-
699
- // resolvers/index.ts
700
- var resolvers_exports = {};
701
- __export(resolvers_exports, {
702
- plugin: () => plugin
703
- });
704
- var import_plugin_helpers = require("@graphql-codegen/plugin-helpers");
705
- var import_visitor_plugin_common3 = require("@graphql-codegen/visitor-plugin-common");
706
-
707
- // resolvers/visitor.ts
708
- var import_typescript = require("@graphql-codegen/typescript");
709
- var import_visitor_plugin_common2 = require("@graphql-codegen/visitor-plugin-common");
710
- var import_auto_bind = __toESM(require("auto-bind"), 1);
711
- var ENUM_RESOLVERS_SIGNATURE = "export type EnumResolverSignature<T, AllowedValues = any> = { [key in keyof T]?: AllowedValues };";
712
- var TypeScriptResolversVisitor = class extends import_visitor_plugin_common2.BaseResolversVisitor {
713
- constructor(pluginConfig, schema) {
714
- super(
715
- pluginConfig,
716
- {
717
- avoidOptionals: (0, import_visitor_plugin_common2.getConfigValue)(pluginConfig.avoidOptionals, false),
718
- useIndexSignature: (0, import_visitor_plugin_common2.getConfigValue)(pluginConfig.useIndexSignature, false),
719
- wrapFieldDefinitions: (0, import_visitor_plugin_common2.getConfigValue)(pluginConfig.wrapFieldDefinitions, false),
720
- allowParentTypeOverride: (0, import_visitor_plugin_common2.getConfigValue)(pluginConfig.allowParentTypeOverride, false),
721
- optionalInfoArgument: (0, import_visitor_plugin_common2.getConfigValue)(pluginConfig.optionalInfoArgument, false)
722
- },
723
- schema
724
- );
725
- (0, import_auto_bind.default)(this);
726
- this.setVariablesTransformer(
727
- new import_typescript.TypeScriptOperationVariablesToObject(
728
- this.scalars,
729
- this.convertName,
730
- this.config.avoidOptionals,
731
- this.config.immutableTypes,
732
- this.config.namespacedImportName,
733
- [],
734
- this.config.enumPrefix,
735
- this.config.enumValues
736
- )
737
- );
738
- if (this.config.useIndexSignature) {
739
- this._declarationBlockConfig = {
740
- blockTransformer(block) {
741
- return `ResolversObject<${block}>`;
742
- }
743
- };
744
- }
745
- }
746
- transformParentGenericType(parentType) {
747
- if (this.config.allowParentTypeOverride) {
748
- return `ParentType = ${parentType}`;
749
- }
750
- return `ParentType extends ${parentType} = ${parentType}`;
751
- }
752
- formatRootResolver(schemaTypeName, resolverType, declarationKind) {
753
- const avoidOptionals = this.config.avoidOptionals?.resolvers ?? this.config.avoidOptionals === true;
754
- return `${schemaTypeName}${avoidOptionals ? "" : "?"}: ${resolverType}${this.getPunctuation(
755
- declarationKind
756
- )}`;
757
- }
758
- clearOptional(str) {
759
- if (str.startsWith("Maybe")) {
760
- return str.replace(/Maybe<(.*?)>$/, "$1");
761
- }
762
- return str;
763
- }
764
- ListType(node) {
765
- return `Maybe<${super.ListType(node)}>`;
766
- }
767
- wrapWithListType(str) {
768
- return `${this.config.immutableTypes ? "ReadonlyArray" : "Array"}<${str}>`;
769
- }
770
- getParentTypeForSignature(node) {
771
- if (this._federation.isResolveReferenceField(node) && this.config.wrapFieldDefinitions) {
772
- return "UnwrappedObject<ParentType>";
773
- }
774
- return "ParentType";
775
- }
776
- NamedType(node) {
777
- return `Maybe<${super.NamedType(node)}>`;
778
- }
779
- NonNullType(node) {
780
- const baseValue = super.NonNullType(node);
781
- return this.clearOptional(baseValue);
782
- }
783
- getPunctuation(_declarationKind) {
784
- return ";";
785
- }
786
- buildEnumResolverContentBlock(node, mappedEnumType) {
787
- const valuesMap = `{ ${(node.values || []).map((v) => `${v.name}${this.config.avoidOptionals ? "" : "?"}: any`).join(", ")} }`;
788
- this._globalDeclarations.add(ENUM_RESOLVERS_SIGNATURE);
789
- return `EnumResolverSignature<${valuesMap}, ${mappedEnumType}>`;
790
- }
791
- buildEnumResolversExplicitMappedValues(node, valuesMapping) {
792
- return `{ ${(node.values || []).map((v) => {
793
- const valueName = v.name;
794
- const mappedValue = valuesMapping[valueName];
795
- return `${valueName}: ${typeof mappedValue === "number" ? mappedValue : `'${mappedValue}'`}`;
796
- }).join(", ")} }`;
797
- }
798
- };
799
-
800
- // resolvers/index.ts
801
- var capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
802
- var plugin = (schema, documents, config) => {
803
- const imports = [];
804
- if (!config.customResolveInfo) {
805
- imports.push("GraphQLResolveInfo");
806
- }
807
- const showUnusedMappers = typeof config.showUnusedMappers === "boolean" ? config.showUnusedMappers : true;
808
- const noSchemaStitching = typeof config.noSchemaStitching === "boolean" ? config.noSchemaStitching : true;
809
- const indexSignature = config.useIndexSignature ? [
810
- "export type WithIndex<TObject> = TObject & Record<string, any>;",
811
- "export type ResolversObject<TObject> = WithIndex<TObject>;"
812
- ].join("\n") : "";
813
- const importType = config.useTypeImports ? "import type" : "import";
814
- const prepend = [];
815
- const defsToInclude = [];
816
- const directiveResolverMappings = {};
817
- if (config.directiveResolverMappings) {
818
- for (const [directiveName, mapper] of Object.entries(config.directiveResolverMappings)) {
819
- const parsedMapper = (0, import_visitor_plugin_common3.parseMapper)(mapper);
820
- const capitalizedDirectiveName = capitalize(directiveName);
821
- const resolverFnName = `ResolverFn${capitalizedDirectiveName}`;
822
- const resolverFnUsage2 = `${resolverFnName}<TResult, TParent, TContext, TArgs>`;
823
- const resolverWithResolveUsage2 = `Resolver${capitalizedDirectiveName}WithResolve<TResult, TParent, TContext, TArgs>`;
824
- const resolverWithResolve2 = `
825
- export type Resolver${capitalizedDirectiveName}WithResolve<TResult, TParent, TContext, TArgs> = {
826
- resolve: ${resolverFnName}<TResult, TParent, TContext, TArgs>;
827
- };`;
828
- const resolverTypeName = `Resolver${capitalizedDirectiveName}`;
829
- const resolverType2 = `export type ${resolverTypeName}<TResult, TParent = {}, TContext = {}, TArgs = {}> =`;
830
- if (parsedMapper.isExternal) {
831
- if (parsedMapper.default) {
832
- prepend.push(`${importType} ${resolverFnName} from '${parsedMapper.source}';`);
833
- } else {
834
- prepend.push(
835
- `${importType} { ${parsedMapper.import} ${parsedMapper.import !== resolverFnName ? `as ${resolverFnName} ` : ""}} from '${parsedMapper.source}';`
836
- );
837
- }
838
- prepend.push(`export${config.useTypeImports ? " type" : ""} { ${resolverFnName} };`);
839
- } else {
840
- defsToInclude.push(
841
- `export type ${resolverFnName}<TResult, TParent, TContext, TArgs> = ${parsedMapper.type}`
842
- );
843
- }
844
- if (config.makeResolverTypeCallable) {
845
- defsToInclude.push(`${resolverType2} ${resolverFnUsage2};`);
846
- } else {
847
- defsToInclude.push(resolverWithResolve2);
848
- defsToInclude.push(`${resolverType2} ${resolverFnUsage2} | ${resolverWithResolveUsage2};`);
849
- }
850
- directiveResolverMappings[directiveName] = resolverTypeName;
851
- }
852
- }
853
- const transformedSchema = config.federation ? (0, import_plugin_helpers.addFederationReferencesToSchema)(schema) : schema;
854
- const visitor = new TypeScriptResolversVisitor(
855
- { ...config, directiveResolverMappings },
856
- transformedSchema
857
- );
858
- const namespacedImportPrefix = visitor.config.namespacedImportName ? `${visitor.config.namespacedImportName}.` : "";
859
- const astNode = (0, import_plugin_helpers.getCachedDocumentNodeFromSchema)(transformedSchema);
860
- const visitorResult = (0, import_plugin_helpers.oldVisit)(astNode, { leave: visitor });
861
- const optionalSignForInfoArg = visitor.config.optionalInfoArgument ? "?" : "";
862
- const legacyStitchingResolverType = `
863
- export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = {
864
- fragment: string;
865
- resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
866
- };`;
867
- const newStitchingResolverType = `
868
- export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = {
869
- selectionSet: string | ((fieldNode: FieldNode) => SelectionSetNode);
870
- resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
871
- };`;
872
- const stitchingResolverType = "export type StitchingResolver<TResult, TParent, TContext, TArgs> = LegacyStitchingResolver<TResult, TParent, TContext, TArgs> | NewStitchingResolver<TResult, TParent, TContext, TArgs>;";
873
- const resolverWithResolve = `
874
- export type ResolverWithResolve<TResult, TParent, TContext, TArgs> = {
875
- resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
876
- };`;
877
- const resolverType = "export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =";
878
- const resolverFnUsage = "ResolverFn<TResult, TParent, TContext, TArgs>";
879
- const resolverWithResolveUsage = "ResolverWithResolve<TResult, TParent, TContext, TArgs>";
880
- const stitchingResolverUsage = "StitchingResolver<TResult, TParent, TContext, TArgs>";
881
- if (visitor.hasFederation()) {
882
- if (visitor.config.wrapFieldDefinitions) {
883
- defsToInclude.push(`export type UnwrappedObject<T> = {
884
- [P in keyof T]: T[P] extends infer R | Promise<infer R> | (() => infer R2 | Promise<infer R2>)
885
- ? R & R2 : T[P]
886
- };`);
887
- }
888
- defsToInclude.push(`export type ReferenceResolver<TResult, TReference, TContext> = (
889
- reference: TReference,
890
- context: TContext,
891
- info${optionalSignForInfoArg}: GraphQLResolveInfo
892
- ) => Promise<TResult> | TResult;`);
893
- defsToInclude.push(`
894
- type ScalarCheck<T, S> = S extends true ? T : NullableCheck<T, S>;
895
- type NullableCheck<T, S> = ${namespacedImportPrefix}Maybe<T> extends T ? ${namespacedImportPrefix}Maybe<ListCheck<NonNullable<T>, S>> : ListCheck<T, S>;
896
- type ListCheck<T, S> = T extends (infer U)[] ? NullableCheck<U, S>[] : GraphQLRecursivePick<T, S>;
897
- export type GraphQLRecursivePick<T, S> = { [K in keyof T & keyof S]: ScalarCheck<T[K], S[K]> };
898
- `);
899
- }
900
- if (!config.makeResolverTypeCallable) {
901
- defsToInclude.push(resolverWithResolve);
902
- }
903
- if (noSchemaStitching) {
904
- const defs = config.makeResolverTypeCallable ? `${resolverType} ${resolverFnUsage};` : `${resolverType} ${resolverFnUsage} | ${resolverWithResolveUsage};`;
905
- defsToInclude.push(defs);
906
- } else {
907
- defsToInclude.push(
908
- [
909
- legacyStitchingResolverType,
910
- newStitchingResolverType,
911
- stitchingResolverType,
912
- resolverType,
913
- ` | ${resolverFnUsage}`,
914
- config.makeResolverTypeCallable ? "" : ` | ${resolverWithResolveUsage}`,
915
- ` | ${stitchingResolverUsage};`
916
- ].join("\n")
917
- );
918
- imports.push("SelectionSetNode", "FieldNode");
919
- }
920
- if (config.customResolverFn) {
921
- const parsedMapper = (0, import_visitor_plugin_common3.parseMapper)(config.customResolverFn);
922
- if (parsedMapper.isExternal) {
923
- if (parsedMapper.default) {
924
- prepend.push(`${importType} ResolverFn from '${parsedMapper.source}';`);
925
- } else {
926
- prepend.push(
927
- `${importType} { ${parsedMapper.import} ${parsedMapper.import !== "ResolverFn" ? "as ResolverFn " : ""}} from '${parsedMapper.source}';`
928
- );
929
- }
930
- prepend.push(`export${config.useTypeImports ? " type" : ""} { ResolverFn };`);
931
- } else {
932
- prepend.push(
933
- `export type ResolverFn<TResult, TParent, TContext, TArgs> = ${parsedMapper.type}`
934
- );
935
- }
936
- } else {
937
- const defaultResolverFn = `
938
- export type ResolverFn<TResult, TParent, TContext, TArgs> = (
939
- parent: TParent,
940
- args: TArgs,
941
- context: TContext,
942
- info${optionalSignForInfoArg}: GraphQLResolveInfo
943
- ) => Promise<TResult> | TResult;`;
944
- defsToInclude.push(defaultResolverFn);
945
- }
946
- if (config.customSubscriptionResolver) {
947
- const parsedMapper = (0, import_visitor_plugin_common3.parseMapper)(config.customSubscriptionResolver);
948
- if (parsedMapper.isExternal) {
949
- if (parsedMapper.default) {
950
- prepend.push(`${importType} SubscriptionResolver from '${parsedMapper.source}';`);
951
- } else {
952
- prepend.push(
953
- `${importType} { ${parsedMapper.import} ${parsedMapper.import !== "SubscriptionResolver" ? "as SubscriptionResolver " : ""}} from '${parsedMapper.source}';`
954
- );
955
- }
956
- prepend.push(`export${config.useTypeImports ? " type" : ""} { SubscriptionResolver };`);
957
- } else {
958
- prepend.push(
959
- `export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> = ${parsedMapper.type}`
960
- );
961
- }
962
- } else {
963
- const defaultSubscriptionDef = `
964
- export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
965
- parent: TParent,
966
- args: TArgs,
967
- context: TContext,
968
- info${optionalSignForInfoArg}: GraphQLResolveInfo
969
- ) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>;
970
-
971
- export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
972
- parent: TParent,
973
- args: TArgs,
974
- context: TContext,
975
- info${optionalSignForInfoArg}: GraphQLResolveInfo
976
- ) => TResult | Promise<TResult>;
977
-
978
- export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
979
- subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
980
- resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
981
- }
982
-
983
- export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
984
- subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
985
- resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
986
- }
987
-
988
- export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
989
- | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
990
- | SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
991
-
992
- export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> =
993
- | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
994
- | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
995
- `;
996
- defsToInclude.push(defaultSubscriptionDef);
997
- }
998
- const header = `${indexSignature}
999
-
1000
- ${visitor.getResolverTypeWrapperSignature()}
1001
-
1002
- ${defsToInclude.join("\n")}
1003
-
1004
- export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
1005
- parent: TParent,
1006
- context: TContext,
1007
- info${optionalSignForInfoArg}: GraphQLResolveInfo
1008
- ) => ${namespacedImportPrefix}Maybe<TTypes> | Promise<${namespacedImportPrefix}Maybe<TTypes>>;
1009
-
1010
- export type IsTypeOfResolverFn<T = {}, TContext = {}> = (obj: T, context: TContext, info${optionalSignForInfoArg}: GraphQLResolveInfo) => boolean | Promise<boolean>;
1011
-
1012
- export type NextResolverFn<T> = () => Promise<T>;
1013
-
1014
- export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = (
1015
- next: NextResolverFn<TResult>,
1016
- parent: TParent,
1017
- args: TArgs,
1018
- context: TContext,
1019
- info${optionalSignForInfoArg}: GraphQLResolveInfo
1020
- ) => TResult | Promise<TResult>;
1021
- `;
1022
- const resolversTypeMapping = visitor.buildResolversTypes();
1023
- const resolversParentTypeMapping = visitor.buildResolversParentTypes();
1024
- const { getRootResolver, getAllDirectiveResolvers, mappersImports, unusedMappers, hasScalars } = visitor;
1025
- if (hasScalars()) {
1026
- imports.push("GraphQLScalarType", "GraphQLScalarTypeConfig");
1027
- }
1028
- if (showUnusedMappers && unusedMappers.length) {
1029
- console.warn(`Unused mappers: ${unusedMappers.join(",")}`);
1030
- }
1031
- if (imports.length) {
1032
- prepend.push(`${importType} { ${imports.join(", ")} } from 'graphql';`);
1033
- }
1034
- if (config.customResolveInfo) {
1035
- const parsedMapper = (0, import_visitor_plugin_common3.parseMapper)(config.customResolveInfo);
1036
- if (parsedMapper.isExternal) {
1037
- if (parsedMapper.default) {
1038
- prepend.push(`import GraphQLResolveInfo from '${parsedMapper.source}'`);
1039
- }
1040
- prepend.push(
1041
- `import { ${parsedMapper.import} ${parsedMapper.import !== "GraphQLResolveInfo" ? "as GraphQLResolveInfo" : ""} } from '${parsedMapper.source}';`
1042
- );
1043
- } else {
1044
- prepend.push(`type GraphQLResolveInfo = ${parsedMapper.type}`);
1045
- }
1046
- }
1047
- prepend.push(...mappersImports, ...visitor.globalDeclarations);
1048
- return {
1049
- prepend,
1050
- content: [
1051
- header,
1052
- resolversTypeMapping,
1053
- resolversParentTypeMapping,
1054
- ...visitorResult.definitions.filter((d) => typeof d === "string"),
1055
- getRootResolver(),
1056
- getAllDirectiveResolvers()
1057
- ].join("\n")
1058
- };
1059
- };
1060
-
1061
- // utils/cache.ts
1062
- function createCache() {
1063
- const cache = /* @__PURE__ */ new Map();
1064
- return function ensure(namespace, key, factory) {
1065
- const cacheKey = `${namespace}:${key}`;
1066
- const cachedValue = cache.get(cacheKey);
1067
- if (cachedValue) {
1068
- return cachedValue;
1069
- }
1070
- const value = factory();
1071
- cache.set(cacheKey, value);
1072
- return value;
1073
- };
1074
- }
1075
-
1076
- // utils/load.ts
1077
- var import_plugin_helpers3 = require("@graphql-codegen/plugin-helpers");
1078
- var import_apollo_engine_loader = require("@graphql-tools/apollo-engine-loader");
1079
- var import_code_file_loader = require("@graphql-tools/code-file-loader");
1080
- var import_git_loader = require("@graphql-tools/git-loader");
1081
- var import_github_loader = require("@graphql-tools/github-loader");
1082
- var import_graphql_file_loader = require("@graphql-tools/graphql-file-loader");
1083
- var import_json_file_loader = require("@graphql-tools/json-file-loader");
1084
- var import_load = require("@graphql-tools/load");
1085
- var import_prisma_loader = require("@graphql-tools/prisma-loader");
1086
- var import_url_loader = require("@graphql-tools/url-loader");
1087
-
1088
- // utils/hash.ts
1089
- var import_plugin_helpers2 = require("@graphql-codegen/plugin-helpers");
1090
- var import_graphql4 = require("graphql");
1091
- var import_node_crypto = require("crypto");
1092
- function hashContent(content) {
1093
- return (0, import_node_crypto.createHash)("sha256").update(content).digest("hex");
1094
- }
1095
- function hashSchema(schema) {
1096
- return hashContent((0, import_graphql4.print)((0, import_plugin_helpers2.getCachedDocumentNodeFromSchema)(schema)));
1097
- }
1098
-
1099
- // utils/load.ts
1100
- async function loadSchema(schemaPointerMap, cwd) {
1101
- const outputSchemaAst = await (0, import_load.loadSchema)(schemaPointerMap, {
1102
- loaders: [
1103
- new import_code_file_loader.CodeFileLoader(),
1104
- new import_git_loader.GitLoader(),
1105
- new import_github_loader.GithubLoader(),
1106
- new import_graphql_file_loader.GraphQLFileLoader(),
1107
- new import_json_file_loader.JsonFileLoader(),
1108
- new import_url_loader.UrlLoader(),
1109
- new import_apollo_engine_loader.ApolloEngineLoader(),
1110
- new import_prisma_loader.PrismaLoader()
1111
- ],
1112
- cwd,
1113
- includeSources: true
1114
- });
1115
- if (!outputSchemaAst.extensions) {
1116
- outputSchemaAst.extensions = {};
1117
- }
1118
- outputSchemaAst.extensions["hash"] = hashSchema(outputSchemaAst);
1119
- return {
1120
- outputSchemaAst,
1121
- outputSchema: (0, import_plugin_helpers3.getCachedDocumentNodeFromSchema)(outputSchemaAst)
1122
- };
1123
- }
1124
-
1125
- // lib/codegen.ts
1126
- async function generate(options) {
1127
- const root = process.cwd();
1128
- const modulesDir = import_path2.default.relative(root, options.modulesDir || "modules");
1129
- const rootConfig = {
1130
- schemas: (0, import_plugin_helpers4.normalizeInstanceOrArray)(options.schemas),
1131
- modulesDir,
1132
- baseTypesPath: import_path2.default.relative(modulesDir, options.baseTypesPath || "./__generated__/types.ts"),
1133
- contextType: options.contextType,
1134
- moduleDefinitionName: options.moduleDefinitionName || "typedef.ts",
1135
- scalars: options.scalars,
1136
- plugins: (0, import_plugin_helpers4.normalizeConfig)(["typescript", "typescript-resolvers"]),
1137
- pluginMap: {
1138
- typescript: typescriptPlugin,
1139
- "typescript-resolvers": resolvers_exports
1140
- }
1141
- };
1142
- const cache = createCache();
1143
- const schemaPointerMap = {};
1144
- for (const ptr of rootConfig.schemas) {
1145
- if (typeof ptr === "string") {
1146
- schemaPointerMap[ptr] = {};
1147
- } else if (typeof ptr === "object") {
1148
- Object.assign(schemaPointerMap, ptr);
1149
- }
1150
- }
1151
- const hash = JSON.stringify(schemaPointerMap);
1152
- const result = await cache("schema", hash, async () => {
1153
- return loadSchema(schemaPointerMap, root);
1154
- });
1155
- const outputs = await preset.buildGeneratesSection({
1156
- baseOutputDir: modulesDir,
1157
- presetConfig: {
1158
- baseTypesPath: rootConfig.baseTypesPath,
1159
- filename: rootConfig.moduleDefinitionName,
1160
- encapsulateModuleTypes: "none"
1161
- },
1162
- schema: result.outputSchema,
1163
- schemaAst: result.outputSchemaAst,
1164
- documents: [],
1165
- pluginMap: rootConfig.pluginMap,
1166
- plugins: rootConfig.plugins,
1167
- config: {
1168
- useIndexSignature: true,
1169
- inputMaybeValue: "T | undefined",
1170
- mapperTypeSuffix: "Prisma",
1171
- contextType: rootConfig.contextType,
1172
- customResolverFn: "@baeta/core#Resolver",
1173
- customSubscriptionResolver: "@baeta/core#SubscriptionResolver",
1174
- useTypeImports: true,
1175
- makeResolverTypeCallable: true,
1176
- includeDirectives: true,
1177
- resolverTypeWrapperSignature: "T",
1178
- emitLegacyCommonJSImports: false,
1179
- scalars: {
1180
- BigInt: "number",
1181
- Bytes: "Buffer",
1182
- DateTime: "Date",
1183
- Decimal: "number",
1184
- Json: "{}",
1185
- ...rootConfig.scalars
1186
- }
1187
- }
1188
- });
1189
- const promises = outputs.map(async (output) => {
1190
- const result2 = await (0, import_core.codegen)({
1191
- ...output,
1192
- cache
1193
- });
1194
- return new import_plugin.File(output.filename, result2, "graphql");
1195
- });
1196
- return Promise.all(promises);
1197
- }
1198
-
1199
- // index.ts
1200
- var graphql_default = (0, import_plugin2.createPluginFactoryV1)({
1201
- name: "graphql",
1202
- watch: (baetaConfig, pluginConfig) => {
1203
- return {
1204
- include: pluginConfig.schemas,
1205
- ignore: []
1206
- };
1207
- },
1208
- generate: async (params) => {
1209
- const files = await generate(params.config);
1210
- params.ctx.fileManager.add(...files);
1211
- return params.next();
1212
- }
1213
- });
1214
- // Annotate the CommonJS export names for ESM import in node:
1215
- 0 && (module.exports = {});