@baeta/plugin-graphql 2.0.0-next.1 → 2.0.0-next.10

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
@@ -1,314 +1,276 @@
1
- // index.ts
2
1
  import { createPluginV1, isMatch } from "@baeta/generator-sdk";
3
-
4
- // lib/codegen.ts
5
- import { join as join2 } from "@baeta/util-path";
6
- import { concatAST } from "graphql";
7
-
8
- // utils/load.ts
2
+ import { join, normalize, posixPath, relative } from "@baeta/util-path";
3
+ import { Kind, concatAST, validateSchema, visit } from "graphql";
9
4
  import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
10
- import {
11
- loadSchema as loadSchemaToolkit
12
- } from "@graphql-tools/load";
13
- import {
14
- getDocumentNodeFromSchema
15
- } from "@graphql-tools/utils";
16
- import { validateSchema } from "graphql";
17
- async function loadSchema(schemas, cwd, extraLoaders = []) {
18
- const schemaPointerMap = {};
19
- for (const ptr of Array.isArray(schemas) ? schemas : [schemas]) {
20
- schemaPointerMap[ptr] = {};
21
- }
22
- const outputSchemaAst = await loadSchemaToolkit(schemaPointerMap, {
23
- loaders: [new GraphQLFileLoader(), ...extraLoaders],
24
- cwd,
25
- includeSources: true
26
- });
27
- const errors = validateSchema(outputSchemaAst);
28
- if (errors.length > 0) {
29
- const messages = errors.map((e) => e.toString()).join("\n\n--------------------\n\n");
30
- const subject = errors.length === 1 ? "error" : "errors";
31
- throw new Error(`Invalid schema. Found ${errors.length} ${subject}:
5
+ import { loadSchema } from "@graphql-tools/load";
6
+ import { getDocumentNodeFromSchema } from "@graphql-tools/utils";
7
+ import { camelCase, pascalCase } from "change-case-all";
32
8
 
33
- ${messages}`);
34
- }
35
- if (!outputSchemaAst.extensions) {
36
- outputSchemaAst.extensions = {};
37
- }
38
- return {
39
- outputSchemaAst,
40
- outputSchema: getDocumentNodeFromSchema(outputSchemaAst)
41
- };
9
+ //#region utils/load.ts
10
+ async function loadSchema$1(schemas, cwd, extraLoaders = []) {
11
+ const schemaPointerMap = {};
12
+ for (const ptr of Array.isArray(schemas) ? schemas : [schemas]) schemaPointerMap[ptr] = {};
13
+ const outputSchemaAst = await loadSchema(schemaPointerMap, {
14
+ loaders: [new GraphQLFileLoader(), ...extraLoaders],
15
+ cwd,
16
+ includeSources: true
17
+ });
18
+ const errors = validateSchema(outputSchemaAst);
19
+ if (errors.length > 0) {
20
+ const messages = errors.map((e) => e.toString()).join("\n\n--------------------\n\n");
21
+ const subject = errors.length === 1 ? "error" : "errors";
22
+ throw new Error(`Invalid schema. Found ${errors.length} ${subject}:\n\n${messages}`);
23
+ }
24
+ if (!outputSchemaAst.extensions) outputSchemaAst.extensions = {};
25
+ return {
26
+ outputSchemaAst,
27
+ outputSchema: getDocumentNodeFromSchema(outputSchemaAst)
28
+ };
42
29
  }
43
30
 
44
- // utils/path.ts
45
- import path, { normalize } from "@baeta/util-path";
46
- var sep = "/";
31
+ //#endregion
32
+ //#region utils/path.ts
33
+ const sep = "/";
47
34
  function getRelativePath(filepath, basePath) {
48
- const normalizedFilepath = normalize(filepath);
49
- const normalizedBasePath = ensureStartsWithSeparator(
50
- ensureEndsWithSeparator(normalize(basePath))
51
- );
52
- const [, relativePath] = normalizedFilepath.split(normalizedBasePath);
53
- return relativePath;
35
+ const normalizedFilepath = normalize(filepath);
36
+ const normalizedBasePath = ensureStartsWithSeparator(ensureEndsWithSeparator(normalize(basePath)));
37
+ const [, relativePath] = normalizedFilepath.split(normalizedBasePath);
38
+ return relativePath;
54
39
  }
55
40
  function extractModuleDirectory(relativePath) {
56
- const [moduleDirectory] = relativePath.split(sep);
57
- return moduleDirectory;
41
+ const [moduleDirectory] = relativePath.split(sep);
42
+ return moduleDirectory;
58
43
  }
59
- function ensureStartsWithSeparator(path2) {
60
- return path2.startsWith(sep) ? path2 : sep + path2;
44
+ function ensureStartsWithSeparator(path$1) {
45
+ return path$1.startsWith(sep) ? path$1 : sep + path$1;
61
46
  }
62
- function ensureEndsWithSeparator(path2) {
63
- return path2.endsWith(sep) ? path2 : path2 + sep;
47
+ function ensureEndsWithSeparator(path$1) {
48
+ return path$1.endsWith(sep) ? path$1 : path$1 + sep;
64
49
  }
65
50
 
66
- // utils/source.ts
51
+ //#endregion
52
+ //#region utils/source.ts
67
53
  function groupSourcesByModule(sources, basePath) {
68
- const map = /* @__PURE__ */ new Map();
69
- for (const source of sources) {
70
- if (!source.location) {
71
- continue;
72
- }
73
- const relativePath = getRelativePath(source.location, basePath);
74
- if (!relativePath) {
75
- continue;
76
- }
77
- const mod = extractModuleDirectory(relativePath);
78
- const existing = map.get(mod) ?? [];
79
- existing.push(source);
80
- map.set(mod, existing);
81
- }
82
- return map;
54
+ const map = /* @__PURE__ */ new Map();
55
+ for (const source of sources) {
56
+ if (!source.location) continue;
57
+ const relativePath = getRelativePath(source.location, basePath);
58
+ if (!relativePath) continue;
59
+ const mod = extractModuleDirectory(relativePath);
60
+ const existing = map.get(mod) ?? [];
61
+ existing.push(source);
62
+ map.set(mod, existing);
63
+ }
64
+ return map;
83
65
  }
84
66
  function getSourcesFromSchema(schema) {
85
- const extensions = schema.extensions;
86
- return extensions?.extendedSources ?? [];
67
+ return schema.extensions?.extendedSources ?? [];
87
68
  }
88
69
 
89
- // lib/printer/printer-autoload.ts
90
- import { camelCase } from "change-case-all";
70
+ //#endregion
71
+ //#region lib/printer/printer-autoload.ts
91
72
  function printAutoload(config, modules) {
92
- return [printImports(config, modules), printExport(modules)].join("\n\n");
73
+ return [printImports(config, modules), printExport(modules)].join("\n\n");
93
74
  }
94
75
  function printImports(config, modules) {
95
- return modules.map(
96
- (module) => `import ${camelCase(module)} from "./${module}/index${config.importExtension}"`
97
- ).join("\n");
76
+ const dependencyImports = ["import type { ModuleCompilerFactory } from \"@baeta/core/sdk\";", `import type { Ctx, Info } from "./types${config.importExtension}"`];
77
+ const moduleTypeImports = modules.map((module) => `import type { BaetaModuleTypes as ${pascalCase(module)}ModuleTypes } from "./${module}/typedef${config.importExtension}"`);
78
+ const moduleImports = modules.flatMap((module) => `import ${camelCase(module)} from "./${module}/index${config.importExtension}"`);
79
+ return [
80
+ ...dependencyImports,
81
+ ...moduleTypeImports,
82
+ ...moduleImports
83
+ ].join("\n");
98
84
  }
99
85
  function printExport(modules) {
100
- return `export default [${modules.map((m) => camelCase(m)).join(", ")}];`;
86
+ return `export default [\n${modules.map(printModuleWithSatisfies).join(",\n")}\n];`;
87
+ }
88
+ function printModuleWithSatisfies(module) {
89
+ return ` ${camelCase(module)} satisfies ModuleCompilerFactory<Ctx, Info, ${pascalCase(module)}ModuleTypes["Factories"]>`;
101
90
  }
102
91
 
103
- // lib/printer/printer-module.ts
104
- import { join, relative } from "@baeta/util-path";
105
- import { pascalCase } from "change-case-all";
106
-
107
- // lib/printer/printer-utils.ts
92
+ //#endregion
93
+ //#region lib/printer/printer-utils.ts
108
94
  function buildBlock({ name, lines }) {
109
- return [`${name} {`, ...lines.filter(Boolean).map(indent(2)), "};"].join("\n");
95
+ return [
96
+ `${name} {`,
97
+ ...lines.filter(Boolean).map(indent(2)),
98
+ "};"
99
+ ].join("\n");
110
100
  }
111
101
  function buildCodeBlock({ name, lines }) {
112
- const linesWithSep = lines.filter(Boolean).map(indent(2)).join(",\n");
113
- return [`${name} {`, linesWithSep, "}"].join("\n");
102
+ const linesWithSep = lines.filter(Boolean).map(indent(2)).join(",\n");
103
+ return [
104
+ `${name} {`,
105
+ linesWithSep,
106
+ "}"
107
+ ].join("\n");
114
108
  }
115
109
  function indent(size) {
116
- const space = new Array(size).fill(" ").join("");
117
- function indentInner(val) {
118
- return val.split("\n").map((line) => `${space}${line}`).join("\n");
119
- }
120
- return indentInner;
110
+ const space = new Array(size).fill(" ").join("");
111
+ function indentInner(val) {
112
+ return val.split("\n").map((line) => `${space}${line}`).join("\n");
113
+ }
114
+ return indentInner;
115
+ }
116
+ function makeRelativePathForImport(from, to) {
117
+ const res = posixPath(relative(from, to));
118
+ if (res.startsWith(".") || res.startsWith("/")) return res;
119
+ return `./${res}`;
121
120
  }
122
121
 
123
- // lib/printer/printer-module.ts
122
+ //#endregion
123
+ //#region lib/printer/printer-module.ts
124
124
  function printModuleImports(config, moduleName) {
125
- const typesDir = relative(join(config.modulesDir, moduleName), config.typesDir);
126
- return [
127
- 'import type { DocumentNode, GraphQLScalarType } from "graphql";',
128
- 'import * as Baeta from "@baeta/core/sdk";',
129
- `import extensions from "../extensions${config.importExtension}";`,
130
- `import type {Ctx, Info} from "../types${config.importExtension}";`,
131
- `import * as Types from "${typesDir}/types${config.importExtension}";`
132
- ].join("\n");
125
+ const typesDir = makeRelativePathForImport(join(config.modulesDir, moduleName), config.typesDir);
126
+ return [
127
+ "import type { DocumentNode, GraphQLScalarType } from \"graphql\";",
128
+ "import * as Baeta from \"@baeta/core/sdk\";",
129
+ `import extensions from "../extensions${config.importExtension}";`,
130
+ `import type {Ctx, Info} from "../types${config.importExtension}";`,
131
+ `import type * as Types from "${typesDir}/types${config.importExtension}";`
132
+ ].join("\n");
133
133
  }
134
134
  function printModuleMetadata(name, doc) {
135
- return buildCodeBlock({
136
- name: "const moduleMetadata =",
137
- lines: [
138
- `id: '${name}'`,
139
- `dirname: './${name}'`,
140
- `typedef: ${JSON.stringify(doc)} as unknown as DocumentNode`
141
- ]
142
- });
135
+ return buildCodeBlock({
136
+ name: "const moduleMetadata =",
137
+ lines: [
138
+ `id: '${name}'`,
139
+ `dirname: './${name}'`,
140
+ `typedef: ${JSON.stringify(doc)} as unknown as DocumentNode`
141
+ ]
142
+ });
143
143
  }
144
144
  function printBaetaModuleTypes(config) {
145
- return buildBlock({
146
- name: "interface BaetaModuleTypes",
147
- lines: [
148
- buildBlock({
149
- name: "Builders:",
150
- lines: printBaetaModuleTypesForFields(config, false)
151
- }),
152
- buildBlock({
153
- name: "Factories:",
154
- lines: [
155
- ...printBaetaModuleTypesForFields(config, true),
156
- ...printBaetaModuleTypesScalars(config)
157
- ]
158
- })
159
- ]
160
- });
145
+ return buildBlock({
146
+ name: "export interface BaetaModuleTypes",
147
+ lines: [buildBlock({
148
+ name: "Builders:",
149
+ lines: printBaetaModuleTypesForFields(config, false)
150
+ }), buildBlock({
151
+ name: "Factories:",
152
+ lines: [...printBaetaModuleTypesForFields(config, true), ...printBaetaModuleTypesScalars(config)]
153
+ })]
154
+ });
161
155
  }
162
156
  function printBaetaModuleTypesForFields(config, isFactory) {
163
- return config.registry.defined.objects.map(
164
- (typeName) => printObjectTypeModuleType(typeName, config.registry.picks.objects, isFactory)
165
- ).filter(Boolean);
157
+ return config.registry.defined.objects.map((typeName) => printObjectTypeModuleType(typeName, config.registry.picks.objects, isFactory)).filter(Boolean);
166
158
  }
167
159
  function printObjectTypeModuleType(typeName, objects, isFactory) {
168
- const object = objects[typeName];
169
- if (!object) {
170
- return "";
171
- }
172
- const parentType = getParentType(typeName);
173
- const contextType = getContextType();
174
- const infoType = getInfoType();
175
- if (isFactory) {
176
- return `${typeName}: Baeta.TypeCompilerFactory<${parentType}, ${contextType}, ${infoType}, BaetaModuleObjectTypeFields['${typeName}']['Factory']>`;
177
- }
178
- return `${typeName}: Baeta.TypeMethods<${parentType}, ${contextType}, ${infoType}, BaetaModuleObjectTypeFields['${typeName}']['Builder'], BaetaModuleObjectTypeFields['${typeName}']['Factory']>`;
160
+ if (!objects[typeName]) return "";
161
+ const parentType = getParentType(typeName);
162
+ const contextType = getContextType();
163
+ const infoType = getInfoType();
164
+ if (isFactory) return `${typeName}: Baeta.TypeCompilerFactory<${parentType}, ${contextType}, ${infoType}, BaetaModuleObjectTypeFields['${typeName}']['Factory']>`;
165
+ return `${typeName}: Baeta.TypeMethods<${parentType}, ${contextType}, ${infoType}, BaetaModuleObjectTypeFields['${typeName}']['Builder'], BaetaModuleObjectTypeFields['${typeName}']['Factory']>`;
179
166
  }
180
167
  function printBaetaModuleTypesScalars(config) {
181
- return config.registry.defined.scalars.map((scalar) => `${scalar}: GraphQLScalarType`);
168
+ return config.registry.defined.scalars.map((scalar) => `${scalar}: GraphQLScalarType`);
182
169
  }
183
170
  function printModuleObjectTypeFields(config) {
184
- const objects = config.registry.defined.objects.map((typeName) => printObjectTypeFields(config, typeName, config.registry.picks.objects)).filter(Boolean);
185
- return buildBlock({
186
- name: "interface BaetaModuleObjectTypeFields",
187
- lines: objects
188
- });
171
+ return buildBlock({
172
+ name: "interface BaetaModuleObjectTypeFields",
173
+ lines: config.registry.defined.objects.map((typeName) => printObjectTypeFields(config, typeName, config.registry.picks.objects)).filter(Boolean)
174
+ });
189
175
  }
190
176
  function printObjectTypeFields(config, typeName, objects) {
191
- const fields = objects[typeName];
192
- if (!fields || fields.length === 0) {
193
- return "";
194
- }
195
- const fieldsBuilders = fields.map(
196
- (field) => printObjectTypeFieldBuilders(config, typeName, field)
197
- );
198
- const fieldsFactories = fields.map(
199
- (field) => printObjectTypeFieldFactories(config, typeName, field)
200
- );
201
- return buildBlock({
202
- name: `${typeName}:`,
203
- lines: [
204
- buildBlock({
205
- name: "Builder:",
206
- lines: fieldsBuilders
207
- }),
208
- buildBlock({
209
- name: "Factory:",
210
- lines: fieldsFactories
211
- })
212
- ]
213
- });
177
+ const fields = objects[typeName];
178
+ if (!fields || fields.length === 0) return "";
179
+ const fieldsBuilders = fields.map((field) => printObjectTypeFieldBuilders(config, typeName, field));
180
+ const fieldsFactories = fields.map((field) => printObjectTypeFieldFactories(config, typeName, field));
181
+ return buildBlock({
182
+ name: `${typeName}:`,
183
+ lines: [buildBlock({
184
+ name: "Builder:",
185
+ lines: fieldsBuilders
186
+ }), buildBlock({
187
+ name: "Factory:",
188
+ lines: fieldsFactories
189
+ })]
190
+ });
214
191
  }
215
192
  function printObjectTypeFieldBuilders(config, typeName, field) {
216
- const parentType = getParentType(typeName);
217
- const resultType = getResultType(config, typeName, field);
218
- const argumentsType = getArgsType(config, typeName, field);
219
- const contextType = getContextType();
220
- const infoType = getInfoType();
221
- const namespace = typeName === "Subscription" ? "SubscriptionMethods" : "FieldMethods";
222
- return `${field}: Baeta.${namespace}<${resultType}, ${parentType}, ${contextType}, ${argumentsType}, ${infoType}>`;
193
+ const parentType = getParentType(typeName);
194
+ const resultType = getResultType(config, typeName, field);
195
+ const argumentsType = getArgsType(config, typeName, field);
196
+ const contextType = getContextType();
197
+ const infoType = getInfoType();
198
+ return `${field}: Baeta.${typeName === "Subscription" ? "SubscriptionMethods" : "FieldMethods"}<${resultType}, ${parentType}, ${contextType}, ${argumentsType}, ${infoType}>`;
223
199
  }
224
200
  function printObjectTypeFieldFactories(config, typeName, field) {
225
- const parentType = getParentType(typeName);
226
- const resultType = getResultType(config, typeName, field);
227
- const argumentsType = getArgsType(config, typeName, field);
228
- const contextType = getContextType();
229
- const infoType = getInfoType();
230
- const namespace = typeName === "Subscription" ? "SubscriptionField" : "Field";
231
- return `${field}: Baeta.${namespace}<${resultType}, ${resultType}, ${parentType}, ${contextType}, ${argumentsType}, ${infoType}>`;
201
+ const parentType = getParentType(typeName);
202
+ const resultType = getResultType(config, typeName, field);
203
+ const argumentsType = getArgsType(config, typeName, field);
204
+ const contextType = getContextType();
205
+ const infoType = getInfoType();
206
+ return `${field}: Baeta.${typeName === "Subscription" ? "SubscriptionField" : "Field"}<${resultType}, ${resultType}, ${parentType}, ${contextType}, ${argumentsType}, ${infoType}>`;
232
207
  }
233
208
  function printModuleBuilder(config, moduleName) {
234
- const objectTypes = config.registry.defined.objects.map((typeName) => printObjectTypeBuilder(typeName, config.registry.picks.objects)).filter(Boolean);
235
- const builders = buildCodeBlock({
236
- name: "",
237
- lines: objectTypes
238
- });
239
- const typeNameResolvers = buildCodeBlock({
240
- name: "",
241
- lines: [...config.registry.defined.unions, ...config.registry.defined.interfaces].map(
242
- (name) => `${name}: ${printTypeNameResolver()}`
243
- )
244
- });
245
- const infoType = getInfoType();
246
- const contextType = getContextType();
247
- return [
248
- `export const ${pascalCase(moduleName)}Module = Baeta.createModuleBuilder<${contextType}, ${infoType}, BaetaModuleTypes['Builders'], BaetaModuleTypes['Factories']>(moduleMetadata.id, moduleMetadata.typedef,`,
249
- builders,
250
- ",",
251
- typeNameResolvers,
252
- `, ${getExtensionsVar()});`
253
- ].join("");
209
+ const builders = buildCodeBlock({
210
+ name: "",
211
+ lines: config.registry.defined.objects.map((typeName) => printObjectTypeBuilder(typeName, config.registry.picks.objects)).filter(Boolean)
212
+ });
213
+ const typeNameResolvers = buildCodeBlock({
214
+ name: "",
215
+ lines: [...config.registry.defined.unions, ...config.registry.defined.interfaces].map((name) => `${name}: ${printTypeNameResolver()}`)
216
+ });
217
+ const infoType = getInfoType();
218
+ const contextType = getContextType();
219
+ return [
220
+ `export const ${pascalCase(moduleName)}Module = Baeta.createModuleBuilder<${contextType}, ${infoType}, BaetaModuleTypes['Builders'], BaetaModuleTypes['Factories']>(moduleMetadata.id, moduleMetadata.typedef,`,
221
+ builders,
222
+ ",",
223
+ typeNameResolvers,
224
+ `, ${getExtensionsVar()});`
225
+ ].join("");
254
226
  }
255
227
  function printObjectTypeBuilder(typeName, objects) {
256
- const fields = objects[typeName]?.map((field) => printObjectTypeFieldBuilder(typeName, field));
257
- if (fields == null || fields.length === 0) {
258
- return "";
259
- }
260
- const content = buildCodeBlock({
261
- name: "",
262
- lines: fields
263
- });
264
- return `${typeName}: Baeta.createTypeBuilder("${typeName}",${content}, ${getExtensionsVar()})`;
228
+ const fields = objects[typeName]?.map((field) => printObjectTypeFieldBuilder(typeName, field));
229
+ if (fields == null || fields.length === 0) return "";
230
+ return `${typeName}: Baeta.createTypeBuilder("${typeName}",${buildCodeBlock({
231
+ name: "",
232
+ lines: fields
233
+ })}, ${getExtensionsVar()})`;
265
234
  }
266
235
  function printTypeNameResolver() {
267
- return "{ __resolveType: (source: {__typename: string}) => { return source.__typename; }}";
236
+ return "{ __resolveType: (source: {__typename: string}) => { return source.__typename; }}";
268
237
  }
269
238
  function getParentType(type) {
270
- if (["Query", "Mutation", "Subscription"].includes(type)) {
271
- return "{}";
272
- }
273
- return `Types.${type}`;
239
+ if ([
240
+ "Query",
241
+ "Mutation",
242
+ "Subscription"
243
+ ].includes(type)) return "{}";
244
+ return `Types.${type}`;
274
245
  }
275
246
  function getResultType(config, type, field) {
276
- const fieldType = config.fieldInfo.get(type)?.get(field)?.type;
277
- if (fieldType == null) {
278
- return "{}";
279
- }
280
- return fieldType;
247
+ const fieldType = config.fieldInfo.get(type)?.get(field)?.type;
248
+ if (fieldType == null) return "{}";
249
+ return fieldType;
281
250
  }
282
251
  function getArgsType(config, type, field) {
283
- const hasArgs = config.fieldInfo.get(type)?.get(field)?.hasArguments ?? false;
284
- if (!hasArgs) {
285
- return "{}";
286
- }
287
- const fieldUpper = field[0].toUpperCase() + field.slice(1);
288
- return `Types.${type}${fieldUpper}Args`;
252
+ if (!(config.fieldInfo.get(type)?.get(field)?.hasArguments ?? false)) return "{}";
253
+ return `Types.${type}${field[0].toUpperCase() + field.slice(1)}Args`;
289
254
  }
290
255
  function printObjectTypeFieldBuilder(typeName, field) {
291
- if (typeName === "Subscription") {
292
- return `${field}: Baeta.createSubscriptionBuilder("${field}", ${getExtensionsVar()})`;
293
- }
294
- return `${field}: Baeta.createFieldBuilder("${typeName}", "${field}", ${getExtensionsVar()})`;
256
+ if (typeName === "Subscription") return `${field}: Baeta.createSubscriptionBuilder("${field}", ${getExtensionsVar()})`;
257
+ return `${field}: Baeta.createFieldBuilder("${typeName}", "${field}", ${getExtensionsVar()})`;
295
258
  }
296
259
  function getContextType() {
297
- return "Ctx";
260
+ return "Ctx";
298
261
  }
299
262
  function getInfoType() {
300
- return "Info";
263
+ return "Info";
301
264
  }
302
265
  function getExtensionsVar() {
303
- return "extensions";
266
+ return "extensions";
304
267
  }
305
268
 
306
- // lib/printer/printer-templates.ts
307
- import { relative as relative2 } from "@baeta/util-path";
269
+ //#endregion
270
+ //#region lib/printer/printer-templates.ts
308
271
  function printTypesTemplate(options) {
309
- const importDir = relative2(options.modulesDir, options.typesDir);
310
- return `import type { GraphQLResolveInfo } from 'graphql';
311
- import type { BaseObjectTypes, BaseScalars } from '${importDir}/utility${options.importExtension}';
272
+ return `import type { GraphQLResolveInfo } from 'graphql';
273
+ import type { BaseObjectTypes, BaseScalars } from '${makeRelativePathForImport(options.modulesDir, options.typesDir)}/utility${options.importExtension}';
312
274
 
313
275
  export interface Scalars extends BaseScalars {}
314
276
 
@@ -320,491 +282,437 @@ export type Info = GraphQLResolveInfo;
320
282
  `;
321
283
  }
322
284
  function printExtensionsTemplate() {
323
- return `import { createExtensions } from '@baeta/core';
285
+ return `import { createExtensions } from '@baeta/core';
324
286
 
325
287
  export default createExtensions({});
326
288
  `;
327
289
  }
328
290
 
329
- // lib/printer/printer-types.ts
330
- import { pascalCase as pascalCase2 } from "change-case-all";
331
- import {
332
- Kind
333
- } from "graphql";
334
-
335
- // utils/scalar.ts
291
+ //#endregion
292
+ //#region utils/scalar.ts
336
293
  function isScalarType(definitionsMap, defaultScalars, type) {
337
- return definitionsMap.scalarTypeMap.has(type.name.value) || defaultScalars.includes(type.name.value);
294
+ return definitionsMap.scalarTypeMap.has(type.name.value) || defaultScalars.includes(type.name.value);
338
295
  }
339
296
 
340
- // lib/printer/printer-types.ts
297
+ //#endregion
298
+ //#region lib/printer/printer-types.ts
341
299
  function printUtilityTypes() {
342
- return [
343
- "export type Or<A, B> = void extends A ? B : A;",
344
- "export type Maybe<T> = T | null;"
345
- ].join("\n\n");
346
- }
347
- var defaultScalarTypes = {
348
- ID: "string",
349
- String: "string",
350
- Boolean: "boolean",
351
- Int: "number",
352
- Float: "number"
300
+ return ["export type Or<A, B> = void extends A ? B : A;", "export type Maybe<T> = T | null;"].join("\n\n");
301
+ }
302
+ const defaultScalarTypes = {
303
+ ID: "string",
304
+ String: "string",
305
+ Boolean: "boolean",
306
+ Int: "number",
307
+ Float: "number"
353
308
  };
354
309
  function printBaseScalars(config) {
355
- const defaultScalars = config.defaultScalars.map((scalar) => {
356
- const type = defaultScalarTypes[scalar];
357
- if (type == null) return null;
358
- return `${scalar}: ${type};`;
359
- }).filter((el) => el != null);
360
- const customScalars = [...config.globalDefinitions.scalarTypeMap.values()].map(
361
- (scalar) => `${scalar.name.value}: unknown;`
362
- );
363
- return buildBlock({
364
- name: "export type BaseScalars =",
365
- lines: [...defaultScalars, ...customScalars]
366
- });
310
+ const defaultScalars = config.defaultScalars.map((scalar) => {
311
+ const type = defaultScalarTypes[scalar];
312
+ if (type == null) return null;
313
+ return `${scalar}: ${type};`;
314
+ }).filter((el) => el != null);
315
+ const customScalars = [...config.globalDefinitions.scalarTypeMap.values()].map((scalar) => `${scalar.name.value}: unknown;`);
316
+ return buildBlock({
317
+ name: "export type BaseScalars =",
318
+ lines: [...defaultScalars, ...customScalars]
319
+ });
367
320
  }
368
321
  function printBaseObjectTypes(config) {
369
- const objectTypes = [...config.globalDefinitions.objectTypeMap.values()].map((t) => t.name.value);
370
- return buildBlock({
371
- name: "export interface BaseObjectTypes",
372
- lines: objectTypes.map((t) => `${t}: unknown;`)
373
- });
374
- }
375
- function printTypesHeaders() {
376
- return [
377
- 'import * as BaetaUtility from "./utility.ts";',
378
- 'import * as BaetaOverrides from "../modules/types.ts";',
379
- "",
380
- "export type Scalars = BaetaOverrides.Scalars;"
381
- ].join("\n");
322
+ return buildBlock({
323
+ name: "export interface BaseObjectTypes",
324
+ lines: [...config.globalDefinitions.objectTypeMap.values()].map((t) => t.name.value).map((t) => `${t}: unknown;`)
325
+ });
326
+ }
327
+ function printTypesHeaders(config) {
328
+ const overridesDir = makeRelativePathForImport(config.typesDir, config.modulesDir);
329
+ return [
330
+ `import type * as BaetaUtility from "./utility${config.importExtension}";`,
331
+ `import type * as BaetaOverrides from "${overridesDir}/types${config.importExtension}";`,
332
+ "",
333
+ "export type Scalars = BaetaOverrides.Scalars;"
334
+ ].join("\n");
382
335
  }
383
336
  function printRootTypesFromMap(config, rootTypes, map) {
384
- return [...map.values()].filter((type) => rootTypes.includes(type.name.value)).map((type) => printObjectType(config, type)).join("\n\n");
337
+ return [...map.values()].filter((type) => rootTypes.includes(type.name.value)).map((type) => printObjectType(config, type)).join("\n\n");
385
338
  }
386
339
  function printObjectTypeTypesFromMap(config, map) {
387
- return [...map.values()].map((type) => printObjectType(config, type));
340
+ return [...map.values()].map((type) => printObjectType(config, type));
388
341
  }
389
342
  function printObjectType(config, type) {
390
- const fields = type.fields?.map((field) => printObjectTypeField(config, field));
391
- return `export type ${type.name.value} = ${printOrObjectType(type, fields)}`;
343
+ const fields = type.fields?.map((field) => printObjectTypeField(config, field));
344
+ return `export type ${type.name.value} = ${printOrObjectType(type, fields)}`;
392
345
  }
393
346
  function printObjectTypeField(config, field) {
394
- const optionalMarker = printOptionalMarker(config, field.type);
395
- return `${field.name.value}${optionalMarker}: ${printType(config, field.type)}`;
347
+ const optionalMarker = printOptionalMarker(config, field.type);
348
+ return `${field.name.value}${optionalMarker}: ${printType(config, field.type)}`;
396
349
  }
397
350
  function printEnumTypesFromMap(map) {
398
- return [...map.values()].map(printEnumType);
351
+ return [...map.values()].map(printEnumType);
399
352
  }
400
353
  function printEnumType(type) {
401
- const values = type.values?.map((value) => `'${value.name.value}'`);
402
- return `export type ${type.name.value} = ${values?.join(" | ") || "never"}`;
354
+ const values = type.values?.map((value) => `'${value.name.value}'`);
355
+ return `export type ${type.name.value} = ${values?.join(" | ") || "never"}`;
403
356
  }
404
357
  function printInterfaceTypesFromMap(config, map) {
405
- return [...map.values()].map((type) => printInterfaceType(config, type));
358
+ return [...map.values()].map((type) => printInterfaceType(config, type));
406
359
  }
407
360
  function printInterfaceType(config, type) {
408
- const objectTypes = Array.from(config.globalDefinitions.objectTypeMap.values());
409
- const implementingTypes = objectTypes.filter(
410
- (t) => t.interfaces?.some((i) => i.name.value === type.name.value)
411
- );
412
- const types = implementingTypes.map((t) => printNamedTypeForInterface(t.name.value));
413
- return `export type ${type.name.value} = ${types.join(" | ") || "never"}`;
361
+ const types = Array.from(config.globalDefinitions.objectTypeMap.values()).filter((t) => t.interfaces?.some((i) => i.name.value === type.name.value)).map((t) => printNamedTypeForInterface(t.name.value));
362
+ return `export type ${type.name.value} = ${types.join(" | ") || "never"}`;
414
363
  }
415
364
  function printNamedTypeForInterface(name) {
416
- return `${name} & {__typename: "${name}"}`;
365
+ return `${name} & {__typename: "${name}"}`;
417
366
  }
418
367
  function printUnionTypesFromMap(config, map) {
419
- return [...map.values()].map((type) => printUnionType(config, type));
368
+ return [...map.values()].map((type) => printUnionType(config, type));
420
369
  }
421
370
  function printUnionType(config, type) {
422
- const types = type.types?.map((type2) => printNamedTypeForUnion(config, type2));
423
- return `export type ${type.name.value} = ${types?.join(" | ") || "never"}`;
371
+ const types = type.types?.map((type$1) => printNamedTypeForUnion(config, type$1));
372
+ return `export type ${type.name.value} = ${types?.join(" | ") || "never"}`;
424
373
  }
425
374
  function printNamedTypeForUnion(config, type) {
426
- return `${printNamedType(config, type, false)} & {__typename: "${type.name.value}"}`;
375
+ return `${printNamedType$1(config, type, false)} & {__typename: "${type.name.value}"}`;
427
376
  }
428
377
  function printInputObjectTypeTypesFromMap(config, map) {
429
- return [...map.values()].map((type) => printInputObjectType(config, type));
378
+ return [...map.values()].map((type) => printInputObjectType(config, type));
430
379
  }
431
380
  function printInputObjectType(config, type) {
432
- const fields = type.fields?.map((field) => printInputObjectTypeField(config, field));
433
- return buildBlock({
434
- name: `export type ${type.name.value} =`,
435
- lines: fields ?? []
436
- });
381
+ const fields = type.fields?.map((field) => printInputObjectTypeField(config, field));
382
+ return buildBlock({
383
+ name: `export type ${type.name.value} =`,
384
+ lines: fields ?? []
385
+ });
437
386
  }
438
387
  function printInputObjectTypeField(config, field) {
439
- const optionalMarker = printOptionalMarker(config, field.type);
440
- return `${field.name.value}${optionalMarker}: ${printType(config, field.type)}`;
388
+ const optionalMarker = printOptionalMarker(config, field.type);
389
+ return `${field.name.value}${optionalMarker}: ${printType(config, field.type)}`;
441
390
  }
442
391
  function printObjectTypeFieldsArgsFromMap(config, map) {
443
- return [...map.values()].flatMap((type) => printObjectTypeArgs(config, type));
392
+ return [...map.values()].flatMap((type) => printObjectTypeArgs(config, type));
444
393
  }
445
394
  function printObjectTypeArgs(config, type) {
446
- if (type.fields == null) {
447
- return [];
448
- }
449
- return type.fields.map((field) => printObjectTypeFieldArgs(config, type.name.value, field)).filter(Boolean);
395
+ if (type.fields == null) return [];
396
+ return type.fields.map((field) => printObjectTypeFieldArgs(config, type.name.value, field)).filter(Boolean);
450
397
  }
451
398
  function printObjectTypeFieldArgs(config, typeName, field) {
452
- const name = `${typeName + pascalCase2(field.name.value)}Args`;
453
- return buildBlock({
454
- name: `export type ${name} =`,
455
- lines: field.arguments?.map((arg) => printObjectTypeFieldArg(config, arg)) ?? []
456
- });
399
+ return buildBlock({
400
+ name: `export type ${`${typeName + pascalCase(field.name.value)}Args`} =`,
401
+ lines: field.arguments?.map((arg) => printObjectTypeFieldArg(config, arg)) ?? []
402
+ });
457
403
  }
458
404
  function printObjectTypeFieldArg(config, arg) {
459
- return `${arg.name.value}: ${printType(config, arg.type)}`;
405
+ return `${arg.name.value}: ${printType(config, arg.type)}`;
460
406
  }
461
407
  function printType(config, type, nullable = true) {
462
- switch (type.kind) {
463
- case Kind.NAMED_TYPE:
464
- return printNamedType(config, type, nullable);
465
- case Kind.LIST_TYPE:
466
- return printListType(config, type, nullable);
467
- case Kind.NON_NULL_TYPE:
468
- return printType(config, type.type, false);
469
- default:
470
- return type;
471
- }
408
+ switch (type.kind) {
409
+ case Kind.NAMED_TYPE: return printNamedType$1(config, type, nullable);
410
+ case Kind.LIST_TYPE: return printListType(config, type, nullable);
411
+ case Kind.NON_NULL_TYPE: return printType(config, type.type, false);
412
+ default: return type;
413
+ }
472
414
  }
473
415
  function printListType(config, type, nullable = true) {
474
- return printValue(config, `Array<${printType(config, type.type)}>`, nullable);
416
+ return printValue(config, `Array<${printType(config, type.type)}>`, nullable);
475
417
  }
476
- function printNamedType(config, type, nullable = true) {
477
- if (isScalarType(config.globalDefinitions, config.defaultScalars, type)) {
478
- return printScalarType(config, type, nullable);
479
- }
480
- return printValue(config, type.name.value, nullable);
418
+ function printNamedType$1(config, type, nullable = true) {
419
+ if (isScalarType(config.globalDefinitions, config.defaultScalars, type)) return printScalarType(config, type, nullable);
420
+ return printValue(config, type.name.value, nullable);
481
421
  }
482
422
  function printScalarType(config, type, nullable = true) {
483
- return printValue(config, `Scalars["${type.name.value}"]`, nullable);
423
+ return printValue(config, `Scalars["${type.name.value}"]`, nullable);
484
424
  }
485
425
  function printValue(config, value, nullable) {
486
- if (!nullable) {
487
- return value;
488
- }
489
- if (config.withMaybe) {
490
- return `BaetaUtility.Maybe<${value}>`;
491
- }
492
- return `${value} | null`;
426
+ if (!nullable) return value;
427
+ if (config.withMaybe) return `BaetaUtility.Maybe<${value}>`;
428
+ return `${value} | null`;
493
429
  }
494
430
  function printOptionalMarker(config, type) {
495
- return config.withOptional && type.kind !== Kind.NON_NULL_TYPE ? "?" : "";
431
+ return config.withOptional && type.kind !== Kind.NON_NULL_TYPE ? "?" : "";
496
432
  }
497
433
  function printOrObjectType(type, fields) {
498
- return `BaetaUtility.Or<BaetaOverrides.ObjectTypes["${type.name.value}"], {
499
- ${fields?.map(indent(2)).join("\n") ?? ""}
500
- }>`;
434
+ return `BaetaUtility.Or<BaetaOverrides.ObjectTypes["${type.name.value}"], {\n${fields?.map(indent(2)).join("\n") ?? ""}\n}>`;
501
435
  }
502
436
 
503
- // lib/visitors/definitions-map.ts
504
- import {
505
- visit
506
- } from "graphql";
437
+ //#endregion
438
+ //#region lib/visitors/definitions-map.ts
507
439
  function createRegistry() {
508
- return {
509
- scalarTypeMap: /* @__PURE__ */ new Map(),
510
- enumTypeMap: /* @__PURE__ */ new Map(),
511
- objectTypeMap: /* @__PURE__ */ new Map(),
512
- inputObjectTypeMap: /* @__PURE__ */ new Map(),
513
- unionTypeMap: /* @__PURE__ */ new Map(),
514
- interfaceTypeMap: /* @__PURE__ */ new Map()
515
- };
440
+ return {
441
+ scalarTypeMap: /* @__PURE__ */ new Map(),
442
+ enumTypeMap: /* @__PURE__ */ new Map(),
443
+ objectTypeMap: /* @__PURE__ */ new Map(),
444
+ inputObjectTypeMap: /* @__PURE__ */ new Map(),
445
+ unionTypeMap: /* @__PURE__ */ new Map(),
446
+ interfaceTypeMap: /* @__PURE__ */ new Map()
447
+ };
516
448
  }
517
449
  function createDefinitionsMapFromSources(sources) {
518
- const registry = createRegistry();
519
- for (const source of sources) {
520
- if (source.document) {
521
- collectTypesFromDocument(source.document, registry, ["Query", "Mutation", "Subscription"]);
522
- }
523
- }
524
- return registry;
450
+ const registry = createRegistry();
451
+ for (const source of sources) if (source.document) collectTypesFromDocument(source.document, registry, [
452
+ "Query",
453
+ "Mutation",
454
+ "Subscription"
455
+ ]);
456
+ return registry;
525
457
  }
526
458
  function createDefinitionsMapFromDocument(document) {
527
- const registry = createRegistry();
528
- collectTypesFromDocument(document, registry);
529
- return registry;
459
+ const registry = createRegistry();
460
+ collectTypesFromDocument(document, registry);
461
+ return registry;
530
462
  }
531
463
  function collectTypesFromDocument(document, registry, filterObjectTypes = []) {
532
- visit(document, {
533
- ScalarTypeDefinition(node) {
534
- if (registry.scalarTypeMap.has(node.name.value)) {
535
- throw new Error(`Scalar type ${node.name.value} already exists`);
536
- }
537
- registry.scalarTypeMap.set(node.name.value, node);
538
- },
539
- EnumTypeDefinition(node) {
540
- if (registry.enumTypeMap.has(node.name.value)) {
541
- throw new Error(`Enum type ${node.name.value} already exists, use 'extend' instead!`);
542
- }
543
- registry.enumTypeMap.set(node.name.value, node);
544
- },
545
- ObjectTypeDefinition(node) {
546
- if (filterObjectTypes.includes(node.name.value)) {
547
- return;
548
- }
549
- if (registry.objectTypeMap.has(node.name.value)) {
550
- throw new Error(`Object type ${node.name.value} already exists, use 'extend' instead!`);
551
- }
552
- registry.objectTypeMap.set(node.name.value, node);
553
- },
554
- InputObjectTypeDefinition(node) {
555
- if (registry.inputObjectTypeMap.has(node.name.value)) {
556
- throw new Error(`Input type ${node.name.value} already exists. Use 'extend' instead!`);
557
- }
558
- registry.inputObjectTypeMap.set(node.name.value, node);
559
- },
560
- UnionTypeDefinition(node) {
561
- if (registry.unionTypeMap.has(node.name.value)) {
562
- throw new Error(`Union type ${node.name.value} already exists, use 'extend' instead!`);
563
- }
564
- registry.unionTypeMap.set(node.name.value, node);
565
- },
566
- InterfaceTypeDefinition(node) {
567
- if (registry.interfaceTypeMap.has(node.name.value)) {
568
- throw new Error(`Interface type ${node.name.value} already exists. Use 'extend' instead!`);
569
- }
570
- registry.interfaceTypeMap.set(node.name.value, node);
571
- }
572
- });
464
+ visit(document, {
465
+ ScalarTypeDefinition(node) {
466
+ if (registry.scalarTypeMap.has(node.name.value)) throw new Error(`Scalar type ${node.name.value} already exists`);
467
+ registry.scalarTypeMap.set(node.name.value, node);
468
+ },
469
+ EnumTypeDefinition(node) {
470
+ if (registry.enumTypeMap.has(node.name.value)) throw new Error(`Enum type ${node.name.value} already exists, use 'extend' instead!`);
471
+ registry.enumTypeMap.set(node.name.value, node);
472
+ },
473
+ ObjectTypeDefinition(node) {
474
+ if (filterObjectTypes.includes(node.name.value)) return;
475
+ if (registry.objectTypeMap.has(node.name.value)) throw new Error(`Object type ${node.name.value} already exists, use 'extend' instead!`);
476
+ registry.objectTypeMap.set(node.name.value, node);
477
+ },
478
+ InputObjectTypeDefinition(node) {
479
+ if (registry.inputObjectTypeMap.has(node.name.value)) throw new Error(`Input type ${node.name.value} already exists. Use 'extend' instead!`);
480
+ registry.inputObjectTypeMap.set(node.name.value, node);
481
+ },
482
+ UnionTypeDefinition(node) {
483
+ if (registry.unionTypeMap.has(node.name.value)) throw new Error(`Union type ${node.name.value} already exists, use 'extend' instead!`);
484
+ registry.unionTypeMap.set(node.name.value, node);
485
+ },
486
+ InterfaceTypeDefinition(node) {
487
+ if (registry.interfaceTypeMap.has(node.name.value)) throw new Error(`Interface type ${node.name.value} already exists. Use 'extend' instead!`);
488
+ registry.interfaceTypeMap.set(node.name.value, node);
489
+ }
490
+ });
573
491
  }
574
492
 
575
- // lib/visitors/field-info.ts
576
- import { Kind as Kind2 } from "graphql";
493
+ //#endregion
494
+ //#region lib/visitors/field-info.ts
577
495
  function createFieldInfoMap(definitionsMap, defaultScalars) {
578
- const map = /* @__PURE__ */ new Map();
579
- for (const objectType of definitionsMap.objectTypeMap.values()) {
580
- const objectName = objectType.name.value;
581
- for (const field of objectType.fields ?? []) {
582
- const fieldName = field.name.value;
583
- const type = printNamedType2(definitionsMap, defaultScalars, field.type, true);
584
- const hasArguments = field.arguments != null && field.arguments.length > 0;
585
- const fieldMap = map.get(objectName) ?? /* @__PURE__ */ new Map();
586
- fieldMap.set(fieldName, { type, hasArguments });
587
- map.set(objectName, fieldMap);
588
- }
589
- }
590
- return map;
591
- }
592
- function printNamedType2(definitionsMap, defaultScalars, type, nullable = true) {
593
- const withNullable = nullable ? " | null" : "";
594
- switch (type.kind) {
595
- case Kind2.NAMED_TYPE:
596
- if (isScalarType(definitionsMap, defaultScalars, type)) {
597
- return `Types.Scalars["${type.name.value}"]${withNullable}`;
598
- }
599
- return `Types.${type.name.value}${withNullable}`;
600
- case Kind2.LIST_TYPE:
601
- return `Array<${printNamedType2(definitionsMap, defaultScalars, type.type, nullable)}>${withNullable}`;
602
- case Kind2.NON_NULL_TYPE:
603
- return printNamedType2(definitionsMap, defaultScalars, type.type, false);
604
- default:
605
- return type;
606
- }
496
+ const map = /* @__PURE__ */ new Map();
497
+ for (const objectType of definitionsMap.objectTypeMap.values()) {
498
+ const objectName = objectType.name.value;
499
+ for (const field of objectType.fields ?? []) {
500
+ const fieldName = field.name.value;
501
+ const type = printNamedType(definitionsMap, defaultScalars, field.type, true);
502
+ const hasArguments = field.arguments != null && field.arguments.length > 0;
503
+ const fieldMap = map.get(objectName) ?? /* @__PURE__ */ new Map();
504
+ fieldMap.set(fieldName, {
505
+ type,
506
+ hasArguments
507
+ });
508
+ map.set(objectName, fieldMap);
509
+ }
510
+ }
511
+ return map;
512
+ }
513
+ function printNamedType(definitionsMap, defaultScalars, type, nullable = true) {
514
+ const withNullable = nullable ? " | null" : "";
515
+ switch (type.kind) {
516
+ case Kind.NAMED_TYPE:
517
+ if (isScalarType(definitionsMap, defaultScalars, type)) return `Types.Scalars["${type.name.value}"]${withNullable}`;
518
+ return `Types.${type.name.value}${withNullable}`;
519
+ case Kind.LIST_TYPE: return `Array<${printNamedType(definitionsMap, defaultScalars, type.type, nullable)}>${withNullable}`;
520
+ case Kind.NON_NULL_TYPE: return printNamedType(definitionsMap, defaultScalars, type.type, false);
521
+ default: return type;
522
+ }
607
523
  }
608
524
 
609
- // lib/visitors/module-registry.ts
610
- import {
611
- visit as visit2
612
- } from "graphql";
613
- var registryKeys = ["objects", "interfaces", "unions", "scalars"];
525
+ //#endregion
526
+ //#region lib/visitors/module-registry.ts
527
+ const registryKeys = [
528
+ "objects",
529
+ "interfaces",
530
+ "unions",
531
+ "scalars"
532
+ ];
614
533
  function createModuleRegistry(document) {
615
- const picks = createObject(
616
- registryKeys,
617
- () => ({})
618
- );
619
- const defined = createObject(registryKeys, () => []);
620
- visit2(document, {
621
- ObjectTypeDefinition(node) {
622
- defined.objects.push(node.name.value);
623
- collectFields(node, picks.objects);
624
- },
625
- ObjectTypeExtension(node) {
626
- pushUnique(defined.objects, node.name.value);
627
- collectFields(node, picks.objects);
628
- },
629
- InterfaceTypeDefinition(node) {
630
- defined.interfaces.push(node.name.value);
631
- collectFields(node, picks.interfaces);
632
- },
633
- UnionTypeDefinition(node) {
634
- defined.unions.push(node.name.value);
635
- collectUnionTypes(node, picks);
636
- },
637
- ScalarTypeDefinition(node) {
638
- defined.scalars.push(node.name.value);
639
- }
640
- });
641
- return {
642
- defined,
643
- picks
644
- };
534
+ const picks = createObject(registryKeys, () => ({}));
535
+ const defined = createObject(registryKeys, () => []);
536
+ visit(document, {
537
+ ObjectTypeDefinition(node) {
538
+ defined.objects.push(node.name.value);
539
+ collectFields(node, picks.objects);
540
+ },
541
+ ObjectTypeExtension(node) {
542
+ pushUnique(defined.objects, node.name.value);
543
+ collectFields(node, picks.objects);
544
+ },
545
+ InterfaceTypeDefinition(node) {
546
+ defined.interfaces.push(node.name.value);
547
+ collectFields(node, picks.interfaces);
548
+ },
549
+ UnionTypeDefinition(node) {
550
+ defined.unions.push(node.name.value);
551
+ collectUnionTypes(node, picks);
552
+ },
553
+ ScalarTypeDefinition(node) {
554
+ defined.scalars.push(node.name.value);
555
+ }
556
+ });
557
+ return {
558
+ defined,
559
+ picks
560
+ };
645
561
  }
646
562
  function collectFields(node, picksObj) {
647
- const name = node.name.value;
648
- if (node.fields) {
649
- if (!picksObj[name]) {
650
- picksObj[name] = [];
651
- }
652
- for (const field of node.fields) {
653
- picksObj[name].push(field.name.value);
654
- }
655
- }
563
+ const name = node.name.value;
564
+ if (node.fields) {
565
+ if (!picksObj[name]) picksObj[name] = [];
566
+ for (const field of node.fields) picksObj[name].push(field.name.value);
567
+ }
656
568
  }
657
569
  function collectUnionTypes(node, picks) {
658
- const name = node.name.value;
659
- if (node.types) {
660
- if (!picks.unions[name]) {
661
- picks.unions[name] = [];
662
- }
663
- for (const type of node.types) {
664
- picks.unions[name].push(type.name.value);
665
- }
666
- }
570
+ const name = node.name.value;
571
+ if (node.types) {
572
+ if (!picks.unions[name]) picks.unions[name] = [];
573
+ for (const type of node.types) picks.unions[name].push(type.name.value);
574
+ }
667
575
  }
668
576
  function pushUnique(list, item) {
669
- if (!list.includes(item)) {
670
- list.push(item);
671
- }
577
+ if (!list.includes(item)) list.push(item);
672
578
  }
673
579
  function createObject(keys, valueFn) {
674
- const obj = {};
675
- for (const key of keys) {
676
- obj[key] = valueFn(key);
677
- }
678
- return obj;
580
+ const obj = {};
581
+ for (const key of keys) obj[key] = valueFn(key);
582
+ return obj;
679
583
  }
680
584
 
681
- // lib/codegen.ts
585
+ //#endregion
586
+ //#region lib/codegen.ts
682
587
  async function generate(options) {
683
- const { outputSchema, outputSchemaAst } = await loadSchema(
684
- options.schemas,
685
- options.cwd,
686
- options.loaders
687
- );
688
- const sources = getSourcesFromSchema(outputSchemaAst);
689
- const sourcesByModule = groupSourcesByModule(sources, options.modulesDir);
690
- const modules = Array.from(sourcesByModule.keys());
691
- const globalDefinitions = createDefinitionsMapFromDocument(outputSchema);
692
- const modulesDefinitions = createDefinitionsMapFromSources(sources);
693
- const defaultScalars = ["ID", "Int", "Float", "String", "Boolean"];
694
- const config = {
695
- globalDefinitions,
696
- withMaybe: false,
697
- withOptional: false,
698
- defaultScalars
699
- };
700
- const fieldInfo = createFieldInfoMap(globalDefinitions, defaultScalars);
701
- const typesContent = [
702
- printTypesHeaders(),
703
- printRootTypesFromMap(
704
- config,
705
- ["Query", "Mutation", "Subscription"],
706
- globalDefinitions.objectTypeMap
707
- ),
708
- ...printEnumTypesFromMap(globalDefinitions.enumTypeMap),
709
- ...printObjectTypeTypesFromMap(config, modulesDefinitions.objectTypeMap),
710
- ...printObjectTypeFieldsArgsFromMap(config, globalDefinitions.objectTypeMap),
711
- ...printInputObjectTypeTypesFromMap(config, globalDefinitions.inputObjectTypeMap),
712
- ...printInterfaceTypesFromMap(config, globalDefinitions.interfaceTypeMap),
713
- ...printUnionTypesFromMap(config, globalDefinitions.unionTypeMap)
714
- ].join("\n\n");
715
- const utilityContent = [
716
- printUtilityTypes(),
717
- printBaseScalars(config),
718
- printBaseObjectTypes(config)
719
- ].join("\n\n");
720
- const files = [
721
- {
722
- filename: join2(options.typesDir, "types.ts"),
723
- content: typesContent
724
- },
725
- {
726
- filename: join2(options.typesDir, "utility.ts"),
727
- content: utilityContent
728
- },
729
- {
730
- filename: join2(options.modulesDir, "index.ts"),
731
- content: printAutoload({ importExtension: options.importExtension }, modules)
732
- },
733
- {
734
- filename: join2(options.modulesDir, "types.ts"),
735
- content: printTypesTemplate({
736
- importExtension: options.importExtension,
737
- typesDir: options.typesDir,
738
- modulesDir: options.modulesDir
739
- }),
740
- options: {
741
- allowOverwrite: false,
742
- disableBiomeHeader: true,
743
- disableEslintHeader: true,
744
- disableGenerationNoticeHeader: true
745
- }
746
- },
747
- {
748
- filename: join2(options.modulesDir, "extensions.ts"),
749
- content: printExtensionsTemplate(),
750
- options: {
751
- allowOverwrite: false,
752
- disableBiomeHeader: true,
753
- disableEslintHeader: true,
754
- disableGenerationNoticeHeader: true
755
- }
756
- }
757
- ];
758
- for (const module of modules) {
759
- const sources2 = sourcesByModule.get(module);
760
- const documents = sources2?.map((s) => s.document).filter((el) => el != null) ?? [];
761
- if (documents.length === 0) continue;
762
- const document = concatAST(documents);
763
- const config2 = {
764
- typesDir: options.typesDir,
765
- fieldInfo,
766
- importExtension: options.importExtension,
767
- modulesDir: options.modulesDir,
768
- registry: createModuleRegistry(document)
769
- };
770
- files.push({
771
- filename: `src/modules/${module}/${options.moduleDefinitionName}`,
772
- content: [
773
- printModuleImports(config2, module),
774
- printModuleMetadata(module, document),
775
- printBaetaModuleTypes(config2),
776
- printModuleObjectTypeFields(config2),
777
- printModuleBuilder(config2, module)
778
- ].join("\n\n")
779
- });
780
- }
781
- return files;
588
+ const { outputSchema, outputSchemaAst } = await loadSchema$1(options.schemas, options.cwd, options.loaders);
589
+ const sources = getSourcesFromSchema(outputSchemaAst);
590
+ const sourcesByModule = groupSourcesByModule(sources, options.modulesDir);
591
+ const modules = Array.from(sourcesByModule.keys());
592
+ const globalDefinitions = createDefinitionsMapFromDocument(outputSchema);
593
+ const modulesDefinitions = createDefinitionsMapFromSources(sources);
594
+ const defaultScalars = [
595
+ "ID",
596
+ "Int",
597
+ "Float",
598
+ "String",
599
+ "Boolean"
600
+ ];
601
+ const config = {
602
+ globalDefinitions,
603
+ withMaybe: false,
604
+ withOptional: false,
605
+ defaultScalars,
606
+ importExtension: options.importExtension,
607
+ typesDir: options.typesDir,
608
+ modulesDir: options.modulesDir
609
+ };
610
+ const fieldInfo = createFieldInfoMap(globalDefinitions, defaultScalars);
611
+ const typesContent = [
612
+ printTypesHeaders(config),
613
+ printRootTypesFromMap(config, [
614
+ "Query",
615
+ "Mutation",
616
+ "Subscription"
617
+ ], globalDefinitions.objectTypeMap),
618
+ ...printEnumTypesFromMap(globalDefinitions.enumTypeMap),
619
+ ...printObjectTypeTypesFromMap(config, modulesDefinitions.objectTypeMap),
620
+ ...printObjectTypeFieldsArgsFromMap(config, globalDefinitions.objectTypeMap),
621
+ ...printInputObjectTypeTypesFromMap(config, globalDefinitions.inputObjectTypeMap),
622
+ ...printInterfaceTypesFromMap(config, globalDefinitions.interfaceTypeMap),
623
+ ...printUnionTypesFromMap(config, globalDefinitions.unionTypeMap)
624
+ ].join("\n\n");
625
+ const utilityContent = [
626
+ printUtilityTypes(),
627
+ printBaseScalars(config),
628
+ printBaseObjectTypes(config)
629
+ ].join("\n\n");
630
+ const files = [
631
+ {
632
+ filename: join(options.typesDir, "types.ts"),
633
+ content: typesContent
634
+ },
635
+ {
636
+ filename: join(options.typesDir, "utility.ts"),
637
+ content: utilityContent
638
+ },
639
+ {
640
+ filename: join(options.modulesDir, "index.ts"),
641
+ content: printAutoload({ importExtension: options.importExtension }, modules)
642
+ },
643
+ {
644
+ filename: join(options.modulesDir, "types.ts"),
645
+ content: printTypesTemplate({
646
+ importExtension: options.importExtension,
647
+ typesDir: options.typesDir,
648
+ modulesDir: options.modulesDir
649
+ }),
650
+ options: {
651
+ disableOverwrite: true,
652
+ disableBiomeV1Header: true,
653
+ disableBiomeV2Header: true,
654
+ disableEslintHeader: true,
655
+ disableGenerationNoticeHeader: true
656
+ }
657
+ },
658
+ {
659
+ filename: join(options.modulesDir, "extensions.ts"),
660
+ content: printExtensionsTemplate(),
661
+ options: {
662
+ disableOverwrite: true,
663
+ disableBiomeV1Header: true,
664
+ disableBiomeV2Header: true,
665
+ disableEslintHeader: true,
666
+ disableGenerationNoticeHeader: true
667
+ }
668
+ }
669
+ ];
670
+ for (const module of modules) {
671
+ const documents = sourcesByModule.get(module)?.map((s) => s.document).filter((el) => el != null) ?? [];
672
+ if (documents.length === 0) continue;
673
+ const document = concatAST(documents);
674
+ const config$1 = {
675
+ typesDir: options.typesDir,
676
+ fieldInfo,
677
+ importExtension: options.importExtension,
678
+ modulesDir: options.modulesDir,
679
+ registry: createModuleRegistry(document)
680
+ };
681
+ files.push({
682
+ filename: join(options.modulesDir, `/${module}/${options.moduleDefinitionName}`),
683
+ content: [
684
+ printModuleImports(config$1, module),
685
+ printModuleMetadata(module, document),
686
+ printBaetaModuleTypes(config$1),
687
+ printModuleObjectTypeFields(config$1),
688
+ printModuleBuilder(config$1, module)
689
+ ].join("\n\n")
690
+ });
691
+ }
692
+ return files;
782
693
  }
783
694
 
784
- // index.ts
695
+ //#endregion
696
+ //#region index.ts
785
697
  function graphqlPlugin() {
786
- return createPluginV1({
787
- name: "graphql",
788
- actionName: "GraphQL modules",
789
- watch: (options, watcher, reload) => {
790
- const handleChange = (file) => {
791
- if (isMatch(file.relativePath, options.schemas)) {
792
- reload(file);
793
- }
794
- };
795
- watcher.on("update", handleChange);
796
- watcher.on("delete", handleChange);
797
- },
798
- generate: async (ctx, next) => {
799
- const items = await generate(ctx.generatorOptions);
800
- for (const item of items) {
801
- ctx.fileManager.createAndAdd(item.filename, item.content, "graphql", item.options);
802
- }
803
- return next();
804
- }
805
- });
806
- }
807
- export {
808
- graphqlPlugin
809
- };
698
+ return createPluginV1({
699
+ name: "graphql",
700
+ actionName: "GraphQL modules",
701
+ watch: (options, watcher, reload) => {
702
+ const handleChange = (file) => {
703
+ if (isMatch(file.relativePath, options.schemas)) reload(file);
704
+ };
705
+ watcher.on("update", handleChange);
706
+ watcher.on("delete", handleChange);
707
+ },
708
+ generate: async (ctx, next) => {
709
+ const items = await generate(ctx.generatorOptions);
710
+ for (const item of items) ctx.fileManager.createAndAdd(item.filename, item.content, "graphql", item.options);
711
+ return next();
712
+ }
713
+ });
714
+ }
715
+
716
+ //#endregion
717
+ export { graphqlPlugin };
810
718
  //# sourceMappingURL=index.js.map