-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
base-visitor.ts
485 lines (460 loc) · 14 KB
/
base-visitor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import autoBind from 'auto-bind';
import { ASTNode, FragmentDefinitionNode, OperationDefinitionNode } from 'graphql';
import { FragmentImport, ImportDeclaration } from './imports.js';
import { convertFactory } from './naming.js';
import {
ConvertFn,
ConvertOptions,
DeclarationKind,
LoadedFragment,
NamingConvention,
NormalizedScalarsMap,
ParsedScalarsMap,
ScalarsMap,
} from './types.js';
import { DeclarationBlockConfig } from './utils.js';
export interface BaseVisitorConvertOptions {
useTypesPrefix?: boolean;
useTypesSuffix?: boolean;
}
export type InlineFragmentTypeOptions = 'inline' | 'combine' | 'mask';
export interface ParsedConfig {
scalars: ParsedScalarsMap;
convert: ConvertFn;
typesPrefix: string;
typesSuffix: string;
addTypename: boolean;
nonOptionalTypename: boolean;
externalFragments: LoadedFragment[];
fragmentImports: ImportDeclaration<FragmentImport>[];
immutableTypes: boolean;
useTypeImports: boolean;
dedupeFragments: boolean;
allowEnumStringTypes: boolean;
inlineFragmentTypes: InlineFragmentTypeOptions;
emitLegacyCommonJSImports: boolean;
}
export interface RawConfig {
/**
* @description Makes scalars strict.
*
* If scalars are found in the schema that are not defined in `scalars`
* an error will be thrown during codegen.
* @default false
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* strictScalars: true,
* },
* },
* },
* };
* export default config;
* ```
*/
strictScalars?: boolean;
/**
* @description Allows you to override the type that unknown scalars will have.
* @default any
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* defaultScalarType: 'unknown'
* },
* },
* },
* };
* export default config;
* ```
*/
defaultScalarType?: string;
/**
* @description Extends or overrides the built-in scalars and custom GraphQL scalars to a custom type.
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* scalars: {
* DateTime: 'Date',
* JSON: '{ [key: string]: any }',
* }
* },
* },
* },
* };
* export default config;
* ```
*/
scalars?: ScalarsMap;
/**
* @default change-case-all#pascalCase
* @description Allow you to override the naming convention of the output.
* You can either override all namings, or specify an object with specific custom naming convention per output.
* The format of the converter must be a valid `module#method`.
* Allowed values for specific output are: `typeNames`, `enumValues`.
* You can also use "keep" to keep all GraphQL names as-is.
* Additionally, you can set `transformUnderscore` to `true` if you want to override the default behavior,
* which is to preserve underscores.
*
* Available case functions in `change-case-all` are `camelCase`, `capitalCase`, `constantCase`, `dotCase`, `headerCase`, `noCase`, `paramCase`, `pascalCase`, `pathCase`, `sentenceCase`, `snakeCase`, `lowerCase`, `localeLowerCase`, `lowerCaseFirst`, `spongeCase`, `titleCase`, `upperCase`, `localeUpperCase` and `upperCaseFirst`
* [See more](https://github.com/btxtiger/change-case-all)
*
* @exampleMarkdown
* ## Override All Names
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* namingConvention: 'change-case-all#lowerCase',
* },
* },
* },
* };
* export default config;
* ```
*
* ## Upper-case enum values
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* namingConvention: {
* typeNames: 'change-case-all#pascalCase',
* enumValues: 'change-case-all#upperCase',
* }
* },
* },
* },
* };
* export default config;
* ```
*
* ## Keep names as is
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* namingConvention: 'keep',
* },
* },
* },
* };
* export default config;
* ```
*
* ## Remove Underscores
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* namingConvention: {
* typeNames: 'change-case-all#pascalCase',
* transformUnderscore: true
* }
* },
* },
* },
* };
* export default config;
* ```
*/
namingConvention?: NamingConvention;
/**
* @default ""
* @description Prefixes all the generated types.
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* typesPrefix: 'I',
* },
* },
* },
* };
* export default config;
* ```
*/
typesPrefix?: string;
/**
* @default ""
* @description Suffixes all the generated types.
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* typesSuffix: 'I',
* },
* },
* },
* };
* export default config;
* ```
*/
typesSuffix?: string;
/**
* @default false
* @description Does not add `__typename` to the generated types, unless it was specified in the selection set.
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* skipTypename: true
* },
* },
* },
* };
* export default config;
* ```
*/
skipTypename?: boolean;
/**
* @default false
* @description Automatically adds `__typename` field to the generated types, even when they are not specified
* in the selection set, and makes it non-optional
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* nonOptionalTypename: true
* },
* },
* },
* };
* export default config;
* ```
*/
nonOptionalTypename?: boolean;
/**
* @name useTypeImports
* @type boolean
* @default false
* @description Will use `import type {}` rather than `import {}` when importing only types. This gives
* compatibility with TypeScript's "importsNotUsedAsValues": "error" option
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* useTypeImports: true
* },
* },
* },
* };
* export default config;
* ```
*/
useTypeImports?: boolean;
/* The following configuration are for preset configuration and should not be set manually (for most use cases...) */
/**
* @ignore
*/
externalFragments?: LoadedFragment[];
/**
* @ignore
*/
fragmentImports?: ImportDeclaration<FragmentImport>[];
/**
* @ignore
*/
globalNamespace?: boolean;
/**
* @description Removes fragment duplicates for reducing data transfer.
* It is done by removing sub-fragments imports from fragment definition
* Instead - all of them are imported to the Operation node.
* @type boolean
* @default false
* @deprecated This option is no longer needed. It will be removed in the next major version.
*/
dedupeFragments?: boolean;
/**
* @ignore
*/
allowEnumStringTypes?: boolean;
/**
* @description Whether fragment types should be inlined into other operations.
* "inline" is the default behavior and will perform deep inlining fragment types within operation type definitions.
* "combine" is the previous behavior that uses fragment type references without inlining the types (and might cause issues with deeply nested fragment that uses list types).
*
* @type string
* @default inline
*/
inlineFragmentTypes?: InlineFragmentTypeOptions;
/**
* @default true
* @description Emit legacy common js imports.
* Default it will be `true` this way it ensure that generated code works with [non-compliant bundlers](https://github.com/dotansimha/graphql-code-generator/issues/8065).
*/
emitLegacyCommonJSImports?: boolean;
}
export class BaseVisitor<TRawConfig extends RawConfig = RawConfig, TPluginConfig extends ParsedConfig = ParsedConfig> {
protected _parsedConfig: TPluginConfig;
protected _declarationBlockConfig: DeclarationBlockConfig = {};
public readonly scalars: NormalizedScalarsMap;
constructor(rawConfig: TRawConfig, additionalConfig: Partial<TPluginConfig>) {
this._parsedConfig = {
convert: convertFactory(rawConfig),
typesPrefix: rawConfig.typesPrefix || '',
typesSuffix: rawConfig.typesSuffix || '',
externalFragments: rawConfig.externalFragments || [],
fragmentImports: rawConfig.fragmentImports || [],
addTypename: !rawConfig.skipTypename,
nonOptionalTypename: !!rawConfig.nonOptionalTypename,
useTypeImports: !!rawConfig.useTypeImports,
dedupeFragments: !!rawConfig.dedupeFragments,
allowEnumStringTypes: !!rawConfig.allowEnumStringTypes,
inlineFragmentTypes: rawConfig.inlineFragmentTypes ?? 'inline',
emitLegacyCommonJSImports:
rawConfig.emitLegacyCommonJSImports === undefined ? true : !!rawConfig.emitLegacyCommonJSImports,
...((additionalConfig || {}) as any),
};
this.scalars = {};
Object.keys(this.config.scalars || {}).forEach(key => {
this.scalars[key] = this.config.scalars[key].type;
});
autoBind(this);
}
protected getVisitorKindContextFromAncestors(ancestors: ASTNode[]): string[] {
if (!ancestors) {
return [];
}
return ancestors.map(t => t.kind).filter(Boolean);
}
get config(): TPluginConfig {
return this._parsedConfig;
}
public convertName(node: ASTNode | string, options?: BaseVisitorConvertOptions & ConvertOptions): string {
const useTypesPrefix = typeof options?.useTypesPrefix === 'boolean' ? options.useTypesPrefix : true;
const useTypesSuffix = typeof options?.useTypesSuffix === 'boolean' ? options.useTypesSuffix : true;
let convertedName = '';
if (useTypesPrefix) {
convertedName += this.config.typesPrefix;
}
convertedName += this.config.convert(node, options);
if (useTypesSuffix) {
convertedName += this.config.typesSuffix;
}
return convertedName;
}
public getOperationSuffix(
node: FragmentDefinitionNode | OperationDefinitionNode | string,
operationType: string
): string {
const { omitOperationSuffix = false, dedupeOperationSuffix = false } = this.config as { [key: string]: any };
const operationName = typeof node === 'string' ? node : node.name ? node.name.value : '';
return omitOperationSuffix
? ''
: dedupeOperationSuffix && operationName.toLowerCase().endsWith(operationType.toLowerCase())
? ''
: operationType;
}
public getFragmentSuffix(node: FragmentDefinitionNode | string): string {
return this.getOperationSuffix(node, 'Fragment');
}
public getFragmentName(node: FragmentDefinitionNode | string): string {
return this.convertName(node, {
suffix: this.getFragmentSuffix(node),
useTypesPrefix: false,
});
}
public getFragmentVariableName(node: FragmentDefinitionNode | string): string {
const {
omitOperationSuffix = false,
dedupeOperationSuffix = false,
fragmentVariableSuffix = 'FragmentDoc',
fragmentVariablePrefix = '',
} = this.config as { [key: string]: any };
const fragmentName = typeof node === 'string' ? node : node.name.value;
const suffix = omitOperationSuffix
? ''
: dedupeOperationSuffix &&
fragmentName.toLowerCase().endsWith('fragment') &&
fragmentVariableSuffix.toLowerCase().startsWith('fragment')
? fragmentVariableSuffix.substring('fragment'.length)
: fragmentVariableSuffix;
return this.convertName(node, {
prefix: fragmentVariablePrefix,
suffix,
useTypesPrefix: false,
});
}
protected getPunctuation(_declarationKind: DeclarationKind): string {
return '';
}
}