1 | import { isEnumType, Kind, } from 'graphql';
|
2 | import { BaseVisitor } from './base-visitor.js';
|
3 | import { DEFAULT_SCALARS } from './scalars.js';
|
4 | import { normalizeDeclarationKind } from './declaration-kinds.js';
|
5 | import { transformComment, DeclarationBlock, indent, wrapWithSingleQuotes, getConfigValue, buildScalarsFromConfig, isOneOfInputObjectType, } from './utils.js';
|
6 | import { OperationVariablesToObject } from './variables-to-object.js';
|
7 | import { parseEnumValues } from './enum-values.js';
|
8 | import { transformDirectiveArgumentAndInputFieldMappings } from './mappers.js';
|
9 | export class BaseTypesVisitor extends BaseVisitor {
|
10 | constructor(_schema, rawConfig, additionalConfig, defaultScalars = DEFAULT_SCALARS) {
|
11 | var _a;
|
12 | super(rawConfig, {
|
13 | enumPrefix: getConfigValue(rawConfig.enumPrefix, true),
|
14 | onlyEnums: getConfigValue(rawConfig.onlyEnums, false),
|
15 | onlyOperationTypes: getConfigValue(rawConfig.onlyOperationTypes, false),
|
16 | addUnderscoreToArgsType: getConfigValue(rawConfig.addUnderscoreToArgsType, false),
|
17 | enumValues: parseEnumValues({
|
18 | schema: _schema,
|
19 | mapOrStr: rawConfig.enumValues,
|
20 | ignoreEnumValuesFromSchema: rawConfig.ignoreEnumValuesFromSchema,
|
21 | }),
|
22 | declarationKind: normalizeDeclarationKind(rawConfig.declarationKind),
|
23 | scalars: buildScalarsFromConfig(_schema, rawConfig, defaultScalars),
|
24 | fieldWrapperValue: getConfigValue(rawConfig.fieldWrapperValue, 'T'),
|
25 | wrapFieldDefinitions: getConfigValue(rawConfig.wrapFieldDefinitions, false),
|
26 | entireFieldWrapperValue: getConfigValue(rawConfig.entireFieldWrapperValue, 'T'),
|
27 | wrapEntireDefinitions: getConfigValue(rawConfig.wrapEntireFieldDefinitions, false),
|
28 | ignoreEnumValuesFromSchema: getConfigValue(rawConfig.ignoreEnumValuesFromSchema, false),
|
29 | directiveArgumentAndInputFieldMappings: transformDirectiveArgumentAndInputFieldMappings((_a = rawConfig.directiveArgumentAndInputFieldMappings) !== null && _a !== void 0 ? _a : {}, rawConfig.directiveArgumentAndInputFieldMappingTypeSuffix),
|
30 | ...additionalConfig,
|
31 | });
|
32 | this._schema = _schema;
|
33 |
|
34 | this._argumentsTransformer = new OperationVariablesToObject(this.scalars, this.convertName);
|
35 | }
|
36 | getExportPrefix() {
|
37 | return 'export ';
|
38 | }
|
39 | getFieldWrapperValue() {
|
40 | if (this.config.fieldWrapperValue) {
|
41 | return `${this.getExportPrefix()}type FieldWrapper<T> = ${this.config.fieldWrapperValue};`;
|
42 | }
|
43 | return '';
|
44 | }
|
45 | getEntireFieldWrapperValue() {
|
46 | if (this.config.entireFieldWrapperValue) {
|
47 | return `${this.getExportPrefix()}type EntireFieldWrapper<T> = ${this.config.entireFieldWrapperValue};`;
|
48 | }
|
49 | return '';
|
50 | }
|
51 | getScalarsImports() {
|
52 | return Object.keys(this.config.scalars)
|
53 | .map(enumName => {
|
54 | const mappedValue = this.config.scalars[enumName];
|
55 | if (mappedValue.isExternal) {
|
56 | return this._buildTypeImport(mappedValue.import, mappedValue.source, mappedValue.default);
|
57 | }
|
58 | return null;
|
59 | })
|
60 | .filter(a => a);
|
61 | }
|
62 | getDirectiveArgumentAndInputFieldMappingsImports() {
|
63 | return Object.keys(this.config.directiveArgumentAndInputFieldMappings)
|
64 | .map(directive => {
|
65 | const mappedValue = this.config.directiveArgumentAndInputFieldMappings[directive];
|
66 | if (mappedValue.isExternal) {
|
67 | return this._buildTypeImport(mappedValue.import, mappedValue.source, mappedValue.default);
|
68 | }
|
69 | return null;
|
70 | })
|
71 | .filter(a => a);
|
72 | }
|
73 | get scalarsDefinition() {
|
74 | if (this.config.onlyEnums)
|
75 | return '';
|
76 | const allScalars = Object.keys(this.config.scalars).map(scalarName => {
|
77 | const scalarValue = this.config.scalars[scalarName].type;
|
78 | const scalarType = this._schema.getType(scalarName);
|
79 | const comment = scalarType && scalarType.astNode && scalarType.description ? transformComment(scalarType.description, 1) : '';
|
80 | const { scalar } = this._parsedConfig.declarationKind;
|
81 | return comment + indent(`${scalarName}: ${scalarValue}${this.getPunctuation(scalar)}`);
|
82 | });
|
83 | return new DeclarationBlock(this._declarationBlockConfig)
|
84 | .export()
|
85 | .asKind(this._parsedConfig.declarationKind.scalar)
|
86 | .withName('Scalars')
|
87 | .withComment('All built-in and custom scalars, mapped to their actual values')
|
88 | .withBlock(allScalars.join('\n')).string;
|
89 | }
|
90 | get directiveArgumentAndInputFieldMappingsDefinition() {
|
91 | const directiveEntries = Object.entries(this.config.directiveArgumentAndInputFieldMappings);
|
92 | if (directiveEntries.length === 0) {
|
93 | return '';
|
94 | }
|
95 | const allDirectives = [];
|
96 | for (const [directiveName, parsedMapper] of directiveEntries) {
|
97 | const directiveType = this._schema.getDirective(directiveName);
|
98 | const comment = (directiveType === null || directiveType === void 0 ? void 0 : directiveType.astNode) && directiveType.description ? transformComment(directiveType.description, 1) : '';
|
99 | const { directive } = this._parsedConfig.declarationKind;
|
100 | allDirectives.push(comment + indent(`${directiveName}: ${parsedMapper.type}${this.getPunctuation(directive)}`));
|
101 | }
|
102 | return new DeclarationBlock(this._declarationBlockConfig)
|
103 | .export()
|
104 | .asKind(this._parsedConfig.declarationKind.directive)
|
105 | .withName('DirectiveArgumentAndInputFieldMappings')
|
106 | .withComment('Type overrides using directives')
|
107 | .withBlock(allDirectives.join('\n')).string;
|
108 | }
|
109 | setDeclarationBlockConfig(config) {
|
110 | this._declarationBlockConfig = config;
|
111 | }
|
112 | setArgumentsTransformer(argumentsTransfomer) {
|
113 | this._argumentsTransformer = argumentsTransfomer;
|
114 | }
|
115 | NonNullType(node) {
|
116 | const asString = node.type;
|
117 | return asString;
|
118 | }
|
119 | getInputObjectDeclarationBlock(node) {
|
120 | return new DeclarationBlock(this._declarationBlockConfig)
|
121 | .export()
|
122 | .asKind(this._parsedConfig.declarationKind.input)
|
123 | .withName(this.convertName(node))
|
124 | .withComment(node.description)
|
125 | .withBlock(node.fields.join('\n'));
|
126 | }
|
127 | getInputObjectOneOfDeclarationBlock(node) {
|
128 |
|
129 |
|
130 | const declarationKind = node.fields.length === 1 ? this._parsedConfig.declarationKind.input : 'type';
|
131 | return new DeclarationBlock(this._declarationBlockConfig)
|
132 | .export()
|
133 | .asKind(declarationKind)
|
134 | .withName(this.convertName(node))
|
135 | .withComment(node.description)
|
136 | .withContent(`\n` + node.fields.join('\n |'));
|
137 | }
|
138 | InputObjectTypeDefinition(node) {
|
139 | if (this.config.onlyEnums)
|
140 | return '';
|
141 |
|
142 | if (isOneOfInputObjectType(this._schema.getType(node.name))) {
|
143 | return this.getInputObjectOneOfDeclarationBlock(node).string;
|
144 | }
|
145 | return this.getInputObjectDeclarationBlock(node).string;
|
146 | }
|
147 | InputValueDefinition(node) {
|
148 | if (this.config.onlyEnums)
|
149 | return '';
|
150 | const comment = transformComment(node.description, 1);
|
151 | const { input } = this._parsedConfig.declarationKind;
|
152 | let type = node.type;
|
153 | if (node.directives && this.config.directiveArgumentAndInputFieldMappings) {
|
154 | type = this._getDirectiveOverrideType(node.directives) || type;
|
155 | }
|
156 | return comment + indent(`${node.name}: ${type}${this.getPunctuation(input)}`);
|
157 | }
|
158 | Name(node) {
|
159 | return node.value;
|
160 | }
|
161 | FieldDefinition(node) {
|
162 | if (this.config.onlyEnums)
|
163 | return '';
|
164 | const typeString = node.type;
|
165 | const { type } = this._parsedConfig.declarationKind;
|
166 | const comment = this.getNodeComment(node);
|
167 | return comment + indent(`${node.name}: ${typeString}${this.getPunctuation(type)}`);
|
168 | }
|
169 | UnionTypeDefinition(node, key, parent) {
|
170 | if (this.config.onlyOperationTypes || this.config.onlyEnums)
|
171 | return '';
|
172 | const originalNode = parent[key];
|
173 | const possibleTypes = originalNode.types
|
174 | .map(t => (this.scalars[t.name.value] ? this._getScalar(t.name.value) : this.convertName(t)))
|
175 | .join(' | ');
|
176 | return new DeclarationBlock(this._declarationBlockConfig)
|
177 | .export()
|
178 | .asKind('type')
|
179 | .withName(this.convertName(node))
|
180 | .withComment(node.description)
|
181 | .withContent(possibleTypes).string;
|
182 | }
|
183 | mergeInterfaces(interfaces, hasOtherFields) {
|
184 | return interfaces.join(' & ') + (interfaces.length && hasOtherFields ? ' & ' : '');
|
185 | }
|
186 | appendInterfacesAndFieldsToBlock(block, interfaces, fields) {
|
187 | block.withContent(this.mergeInterfaces(interfaces, fields.length > 0));
|
188 | block.withBlock(this.mergeAllFields(fields, interfaces.length > 0));
|
189 | }
|
190 | getObjectTypeDeclarationBlock(node, originalNode) {
|
191 | const optionalTypename = this.config.nonOptionalTypename ? '__typename' : '__typename?';
|
192 | const { type, interface: interfacesType } = this._parsedConfig.declarationKind;
|
193 | const allFields = [
|
194 | ...(this.config.addTypename
|
195 | ? [
|
196 | indent(`${this.config.immutableTypes ? 'readonly ' : ''}${optionalTypename}: '${node.name}'${this.getPunctuation(type)}`),
|
197 | ]
|
198 | : []),
|
199 | ...node.fields,
|
200 | ];
|
201 | const interfacesNames = originalNode.interfaces ? originalNode.interfaces.map(i => this.convertName(i)) : [];
|
202 | const declarationBlock = new DeclarationBlock(this._declarationBlockConfig)
|
203 | .export()
|
204 | .asKind(type)
|
205 | .withName(this.convertName(node))
|
206 | .withComment(node.description);
|
207 | if (type === 'interface' || type === 'class') {
|
208 | if (interfacesNames.length > 0) {
|
209 | const keyword = interfacesType === 'interface' && type === 'class' ? 'implements' : 'extends';
|
210 | declarationBlock.withContent(`${keyword} ` + interfacesNames.join(', ') + (allFields.length > 0 ? ' ' : ' {}'));
|
211 | }
|
212 | declarationBlock.withBlock(this.mergeAllFields(allFields, false));
|
213 | }
|
214 | else {
|
215 | this.appendInterfacesAndFieldsToBlock(declarationBlock, interfacesNames, allFields);
|
216 | }
|
217 | return declarationBlock;
|
218 | }
|
219 | mergeAllFields(allFields, _hasInterfaces) {
|
220 | return allFields.join('\n');
|
221 | }
|
222 | ObjectTypeDefinition(node, key, parent) {
|
223 | if (this.config.onlyOperationTypes || this.config.onlyEnums)
|
224 | return '';
|
225 | const originalNode = parent[key];
|
226 | return [this.getObjectTypeDeclarationBlock(node, originalNode).string, this.buildArgumentsBlock(originalNode)]
|
227 | .filter(f => f)
|
228 | .join('\n\n');
|
229 | }
|
230 | getInterfaceTypeDeclarationBlock(node, _originalNode) {
|
231 | const declarationBlock = new DeclarationBlock(this._declarationBlockConfig)
|
232 | .export()
|
233 | .asKind(this._parsedConfig.declarationKind.interface)
|
234 | .withName(this.convertName(node))
|
235 | .withComment(node.description);
|
236 | return declarationBlock.withBlock(node.fields.join('\n'));
|
237 | }
|
238 | InterfaceTypeDefinition(node, key, parent) {
|
239 | if (this.config.onlyOperationTypes || this.config.onlyEnums)
|
240 | return '';
|
241 | const originalNode = parent[key];
|
242 | return [this.getInterfaceTypeDeclarationBlock(node, originalNode).string, this.buildArgumentsBlock(originalNode)]
|
243 | .filter(f => f)
|
244 | .join('\n\n');
|
245 | }
|
246 | ScalarTypeDefinition(_node) {
|
247 |
|
248 | return '';
|
249 | }
|
250 | _buildTypeImport(identifier, source, asDefault = false) {
|
251 | const { useTypeImports } = this.config;
|
252 | if (asDefault) {
|
253 | if (useTypeImports) {
|
254 | return `import type { default as ${identifier} } from '${source}';`;
|
255 | }
|
256 | return `import ${identifier} from '${source}';`;
|
257 | }
|
258 | return `import${useTypeImports ? ' type' : ''} { ${identifier} } from '${source}';`;
|
259 | }
|
260 | handleEnumValueMapper(typeIdentifier, importIdentifier, sourceIdentifier, sourceFile) {
|
261 | const importStatement = this._buildTypeImport(importIdentifier || sourceIdentifier, sourceFile);
|
262 | if (importIdentifier !== sourceIdentifier || sourceIdentifier !== typeIdentifier) {
|
263 | return [importStatement, `import ${typeIdentifier} = ${sourceIdentifier};`];
|
264 | }
|
265 | return [importStatement];
|
266 | }
|
267 | getEnumsImports() {
|
268 | return Object.keys(this.config.enumValues)
|
269 | .flatMap(enumName => {
|
270 | const mappedValue = this.config.enumValues[enumName];
|
271 | if (mappedValue.sourceFile) {
|
272 | if (mappedValue.isDefault) {
|
273 | return [this._buildTypeImport(mappedValue.typeIdentifier, mappedValue.sourceFile, true)];
|
274 | }
|
275 | return this.handleEnumValueMapper(mappedValue.typeIdentifier, mappedValue.importIdentifier, mappedValue.sourceIdentifier, mappedValue.sourceFile);
|
276 | }
|
277 | return [];
|
278 | })
|
279 | .filter(Boolean);
|
280 | }
|
281 | EnumTypeDefinition(node) {
|
282 | const enumName = node.name;
|
283 |
|
284 | if (this.config.enumValues[enumName] && this.config.enumValues[enumName].sourceFile) {
|
285 | return null;
|
286 | }
|
287 | return new DeclarationBlock(this._declarationBlockConfig)
|
288 | .export()
|
289 | .asKind('enum')
|
290 | .withName(this.convertName(node, { useTypesPrefix: this.config.enumPrefix }))
|
291 | .withComment(node.description)
|
292 | .withBlock(this.buildEnumValuesBlock(enumName, node.values)).string;
|
293 | }
|
294 |
|
295 | StringValue(node) {
|
296 | return node.value;
|
297 | }
|
298 | makeValidEnumIdentifier(identifier) {
|
299 | if (/^[0-9]/.exec(identifier)) {
|
300 | return wrapWithSingleQuotes(identifier, true);
|
301 | }
|
302 | return identifier;
|
303 | }
|
304 | buildEnumValuesBlock(typeName, values) {
|
305 | const schemaEnumType = this._schema
|
306 | ? this._schema.getType(typeName)
|
307 | : undefined;
|
308 | return values
|
309 | .map(enumOption => {
|
310 | const optionName = this.makeValidEnumIdentifier(this.convertName(enumOption, {
|
311 | useTypesPrefix: false,
|
312 | transformUnderscore: true,
|
313 | }));
|
314 | const comment = this.getNodeComment(enumOption);
|
315 | const schemaEnumValue = schemaEnumType && !this.config.ignoreEnumValuesFromSchema
|
316 | ? schemaEnumType.getValue(enumOption.name).value
|
317 | : undefined;
|
318 | let enumValue = typeof schemaEnumValue !== 'undefined' ? schemaEnumValue : enumOption.name;
|
319 | if (this.config.enumValues[typeName] &&
|
320 | this.config.enumValues[typeName].mappedValues &&
|
321 | typeof this.config.enumValues[typeName].mappedValues[enumValue] !== 'undefined') {
|
322 | enumValue = this.config.enumValues[typeName].mappedValues[enumValue];
|
323 | }
|
324 | return (comment +
|
325 | indent(`${optionName}${this._declarationBlockConfig.enumNameValueSeparator} ${wrapWithSingleQuotes(enumValue, typeof schemaEnumValue !== 'undefined')}`));
|
326 | })
|
327 | .join(',\n');
|
328 | }
|
329 | DirectiveDefinition(_node) {
|
330 | return '';
|
331 | }
|
332 | getArgumentsObjectDeclarationBlock(node, name, field) {
|
333 | return new DeclarationBlock(this._declarationBlockConfig)
|
334 | .export()
|
335 | .asKind(this._parsedConfig.declarationKind.arguments)
|
336 | .withName(this.convertName(name))
|
337 | .withComment(node.description)
|
338 | .withBlock(this._argumentsTransformer.transform(field.arguments));
|
339 | }
|
340 | getArgumentsObjectTypeDefinition(node, name, field) {
|
341 | if (this.config.onlyEnums)
|
342 | return '';
|
343 | return this.getArgumentsObjectDeclarationBlock(node, name, field).string;
|
344 | }
|
345 | buildArgumentsBlock(node) {
|
346 | const fieldsWithArguments = node.fields.filter(field => field.arguments && field.arguments.length > 0) || [];
|
347 | return fieldsWithArguments
|
348 | .map(field => {
|
349 | const name = node.name.value +
|
350 | (this.config.addUnderscoreToArgsType ? '_' : '') +
|
351 | this.convertName(field, {
|
352 | useTypesPrefix: false,
|
353 | useTypesSuffix: false,
|
354 | }) +
|
355 | 'Args';
|
356 | return this.getArgumentsObjectTypeDefinition(node, name, field);
|
357 | })
|
358 | .join('\n\n');
|
359 | }
|
360 | _getScalar(name) {
|
361 | return `Scalars['${name}']`;
|
362 | }
|
363 | _getDirectiveArgumentNadInputFieldMapping(name) {
|
364 | return `DirectiveArgumentAndInputFieldMappings['${name}']`;
|
365 | }
|
366 | _getDirectiveOverrideType(directives) {
|
367 | const type = directives
|
368 | .map(directive => {
|
369 | const directiveName = directive.name;
|
370 | if (this.config.directiveArgumentAndInputFieldMappings[directiveName]) {
|
371 | return this._getDirectiveArgumentNadInputFieldMapping(directiveName);
|
372 | }
|
373 | return null;
|
374 | })
|
375 | .reverse()
|
376 | .find(a => !!a);
|
377 | return type || null;
|
378 | }
|
379 | _getTypeForNode(node) {
|
380 | const typeAsString = node.name;
|
381 | if (this.scalars[typeAsString]) {
|
382 | return this._getScalar(typeAsString);
|
383 | }
|
384 | if (this.config.enumValues[typeAsString]) {
|
385 | return this.config.enumValues[typeAsString].typeIdentifier;
|
386 | }
|
387 | const schemaType = this._schema.getType(node.name);
|
388 | if (schemaType && isEnumType(schemaType)) {
|
389 | return this.convertName(node, { useTypesPrefix: this.config.enumPrefix });
|
390 | }
|
391 | return this.convertName(node);
|
392 | }
|
393 | NamedType(node, key, parent, path, ancestors) {
|
394 | const currentVisitContext = this.getVisitorKindContextFromAncestors(ancestors);
|
395 | const isVisitingInputType = currentVisitContext.includes(Kind.INPUT_OBJECT_TYPE_DEFINITION);
|
396 | const typeToUse = this._getTypeForNode(node);
|
397 | if (!isVisitingInputType && this.config.fieldWrapperValue && this.config.wrapFieldDefinitions) {
|
398 | return `FieldWrapper<${typeToUse}>`;
|
399 | }
|
400 | return typeToUse;
|
401 | }
|
402 | ListType(node, key, parent, path, ancestors) {
|
403 | const asString = node.type;
|
404 | return this.wrapWithListType(asString);
|
405 | }
|
406 | SchemaDefinition() {
|
407 | return null;
|
408 | }
|
409 | getNodeComment(node) {
|
410 | let commentText = node.description;
|
411 | const deprecationDirective = node.directives.find((v) => v.name === 'deprecated');
|
412 | if (deprecationDirective) {
|
413 | const deprecationReason = this.getDeprecationReason(deprecationDirective);
|
414 | commentText = `${commentText ? `${commentText}\n` : ''}@deprecated ${deprecationReason}`;
|
415 | }
|
416 | const comment = transformComment(commentText, 1);
|
417 | return comment;
|
418 | }
|
419 | getDeprecationReason(directive) {
|
420 | if (directive.name === 'deprecated') {
|
421 | const hasArguments = directive.arguments.length > 0;
|
422 | let reason = 'Field no longer supported';
|
423 | if (hasArguments) {
|
424 | reason = directive.arguments[0].value;
|
425 | }
|
426 | return reason;
|
427 | }
|
428 | }
|
429 | wrapWithListType(str) {
|
430 | return `Array<${str}>`;
|
431 | }
|
432 | }
|