-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
client-side-base-visitor.ts
367 lines (309 loc) · 13 KB
/
client-side-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
import { BaseVisitor, ParsedConfig, RawConfig } from './base-visitor';
import autoBind from 'auto-bind';
import { FragmentDefinitionNode, print, OperationDefinitionNode, visit, FragmentSpreadNode, GraphQLSchema } from 'graphql';
import { DepGraph } from 'dependency-graph';
import gqlTag from 'graphql-tag';
import { toPascalCase, Types } from '@graphql-codegen/plugin-helpers';
import { getConfigValue, buildScalars } from './utils';
import { LoadedFragment } from './types';
import { basename, extname } from 'path';
import { DEFAULT_SCALARS } from './scalars';
export enum DocumentMode {
graphQLTag = 'graphQLTag',
documentNode = 'documentNode',
external = 'external',
string = 'string',
}
const EXTENSIONS_TO_REMOVE = ['.ts', '.tsx', '.js', '.jsx'];
export interface RawClientSideBasePluginConfig extends RawConfig {
noGraphQLTag?: boolean;
gqlImport?: string;
noExport?: boolean;
dedupeOperationSuffix?: boolean;
operationResultSuffix?: string;
documentVariablePrefix?: string;
documentVariableSuffix?: string;
documentMode?: DocumentMode;
importOperationTypesFrom?: string;
importDocumentNodeExternallyFrom?: string;
}
export interface ClientSideBasePluginConfig extends ParsedConfig {
/**
* @name gqlImport
* @type string
* @default gql#graphql-tag
* @description Customize from which module will `gql` be imported from.
* This is useful if you want to use modules other than `graphql-tag`, e.g. `graphql.macro`.
*
* @example graphql.macro
* ```yml
* config:
* gqlImport: graphql.macro#gql
* ```
* @example Gatsby
* ```yml
* config:
* gqlImport: gatsby#graphql
* ```
*/
gqlImport: string;
/**
* @name operationResultSuffix
* @type string
* @default ""
* @description Adds a suffix to generated operation result type names
*/
operationResultSuffix: string;
/**
* @name dedupeOperationSuffix
* @type boolean
* @default false
* @description Set this configuration to `true` if you wish to make sure to remove duplicate operation name suffix.
*/
dedupeOperationSuffix: boolean;
noExport: boolean;
documentVariablePrefix: string;
documentVariableSuffix: string;
fragmentVariablePrefix: string;
fragmentVariableSuffix: string;
/**
* @name documentMode
* @type 'graphQLTag' | 'documentNode' | 'external'
* @default 'graphQLTag'
* @description Declares how DocumentNode are created:
* - `graphQLTag`: `graphql-tag` or other modules (check `gqlImport`) will be used to generate document nodes. If this is used, document nodes are generated on client side i.e. the module used to generate this will be shipped to the client
* - `documentNode`: document nodes will be generated as objects when we generate the templates.
* - `external`: document nodes are imported from an external file. To be used with `importDocumentNodeExternallyFrom`
*/
documentMode?: DocumentMode;
/**
* @name importDocumentNodeExternallyFrom
* @type string | 'near-operation-file'
* @default ''
* @description This config should be used if `documentMode` is `external`. This has 2 usage:
* - any string: This would be the path to import document nodes from. This can be used if we want to manually create the document nodes e.g. Use `graphql-tag` in a separate file and export the generated document
* - 'near-operation-file': This is a special mode that is intended to be used with `near-operation-file` preset to import document nodes from those files. If these files are `.graphql` files, we make use of webpack loader.
*
* @example
* ```yml
* config:
* documentMode: external
* importDocumentNodeExternallyFrom: path/to/document-node-file
* ```
*
* ```yml
* config:
* documentMode: external
* importDocumentNodeExternallyFrom: near-operation-file
* ```
*
*/
importDocumentNodeExternallyFrom?: string;
// The following are internal, and used by presets
importOperationTypesFrom?: string;
}
export class ClientSideBaseVisitor<TRawConfig extends RawClientSideBasePluginConfig = RawClientSideBasePluginConfig, TPluginConfig extends ClientSideBasePluginConfig = ClientSideBasePluginConfig> extends BaseVisitor<TRawConfig, TPluginConfig> {
protected _collectedOperations: OperationDefinitionNode[] = [];
protected _documents: Types.DocumentFile[] = [];
protected _additionalImports: string[] = [];
constructor(protected _schema: GraphQLSchema, protected _fragments: LoadedFragment[], rawConfig: TRawConfig, additionalConfig: Partial<TPluginConfig>, documents?: Types.DocumentFile[]) {
super(rawConfig, {
scalars: buildScalars(_schema, rawConfig.scalars, DEFAULT_SCALARS),
dedupeOperationSuffix: getConfigValue(rawConfig.dedupeOperationSuffix, false),
gqlImport: rawConfig.gqlImport || null,
noExport: !!rawConfig.noExport,
importOperationTypesFrom: getConfigValue(rawConfig.importOperationTypesFrom, null),
operationResultSuffix: getConfigValue(rawConfig.operationResultSuffix, ''),
documentVariablePrefix: getConfigValue(rawConfig.documentVariablePrefix, ''),
documentVariableSuffix: getConfigValue(rawConfig.documentVariableSuffix, 'Document'),
fragmentVariablePrefix: getConfigValue(rawConfig.documentVariablePrefix, ''),
fragmentVariableSuffix: getConfigValue(rawConfig.documentVariableSuffix, 'FragmentDoc'),
documentMode: ((rawConfig: RawClientSideBasePluginConfig) => {
if (typeof rawConfig.noGraphQLTag === 'boolean') {
return rawConfig.noGraphQLTag ? DocumentMode.documentNode : DocumentMode.graphQLTag;
}
return getConfigValue(rawConfig.documentMode, DocumentMode.graphQLTag);
})(rawConfig),
importDocumentNodeExternallyFrom: getConfigValue(rawConfig.importDocumentNodeExternallyFrom, ''),
...additionalConfig,
} as any);
this._documents = documents;
autoBind(this);
}
protected _getFragmentName(fragment: FragmentDefinitionNode | string): string {
return this.convertName(fragment, {
suffix: this.config.fragmentVariableSuffix,
prefix: this.config.fragmentVariablePrefix,
useTypesPrefix: false,
});
}
protected _extractFragments(document: FragmentDefinitionNode | OperationDefinitionNode): string[] {
if (!document) {
return [];
}
const names = [];
visit(document, {
enter: {
FragmentSpread: (node: FragmentSpreadNode) => {
names.push(node.name.value);
},
},
});
return names;
}
protected _transformFragments(document: FragmentDefinitionNode | OperationDefinitionNode): string[] {
return this._extractFragments(document).map(document => this._getFragmentName(document));
}
protected _includeFragments(fragments: string[]): string {
if (fragments && fragments.length > 0) {
if (this.config.documentMode === DocumentMode.documentNode) {
return `${fragments
.filter((name, i, all) => all.indexOf(name) === i)
.map(name => {
const found = this._fragments.find(f => `${f.name}FragmentDoc` === name);
if (found) {
return print(found.node);
}
return null;
})
.filter(a => a)
.join('\n')}`;
} else {
return `${fragments
.filter((name, i, all) => all.indexOf(name) === i)
.map(name => '${' + name + '}')
.join('\n')}`;
}
}
return '';
}
protected _prepareDocument(documentStr: string): string {
return documentStr;
}
protected _gql(node: FragmentDefinitionNode | OperationDefinitionNode): string {
const doc = this._prepareDocument(`
${
print(node)
.split('\\')
.join('\\\\') /* Re-escape escaped values in GraphQL syntax */
}
${this._includeFragments(this._transformFragments(node))}`);
if (this.config.documentMode === DocumentMode.documentNode) {
const gqlObj = gqlTag(doc);
if (gqlObj && gqlObj['loc']) {
delete gqlObj.loc;
}
return JSON.stringify(gqlObj);
} else if (this.config.documentMode === DocumentMode.string) {
return '`' + doc + '`';
}
return 'gql`' + doc + '`';
}
protected _generateFragment(fragmentDocument: FragmentDefinitionNode): string | void {
const name = this._getFragmentName(fragmentDocument);
return `export const ${name}${this.config.documentMode === DocumentMode.documentNode ? ': DocumentNode' : ''} = ${this._gql(fragmentDocument)};`;
}
private get fragmentsGraph(): DepGraph<LoadedFragment> {
const graph = new DepGraph<LoadedFragment>({ circular: true });
for (const fragment of this._fragments) {
if (graph.hasNode(fragment.name)) {
const cachedAsString = print(graph.getNodeData(fragment.name).node);
const asString = print(fragment.node);
if (cachedAsString !== asString) {
throw new Error(`Duplicated fragment called '${fragment.name}'!`);
}
}
graph.addNode(fragment.name, fragment);
}
this._fragments.forEach(fragment => {
const depends = this._extractFragments(fragment.node);
if (depends && depends.length > 0) {
depends.forEach(name => {
graph.addDependency(fragment.name, name);
});
}
});
return graph;
}
public get fragments(): string {
if (this._fragments.length === 0 || this.config.documentMode === DocumentMode.external) {
return '';
}
const graph = this.fragmentsGraph;
const orderedDeps = graph.overallOrder();
const localFragments = orderedDeps.filter(name => !graph.getNodeData(name).isExternal).map(name => this._generateFragment(graph.getNodeData(name).node));
return localFragments.join('\n');
}
protected _parseImport(importStr: string) {
const [moduleName, propName] = importStr.split('#');
return {
moduleName,
propName,
};
}
private clearExtension(path: string): string {
const extension = extname(path);
if (EXTENSIONS_TO_REMOVE.includes(extension)) {
return path.replace(/\.[^/.]+$/, '');
}
return path;
}
public getImports(): string[] {
let imports = [...this._additionalImports];
switch (this.config.documentMode) {
case DocumentMode.documentNode:
imports.push(`import { DocumentNode } from 'graphql';`);
break;
case DocumentMode.graphQLTag:
const gqlImport = this._parseImport(this.config.gqlImport || 'graphql-tag');
imports.push(`import ${gqlImport.propName ? `{ ${gqlImport.propName === 'gql' ? 'gql' : `${gqlImport.propName} as gql`} }` : 'gql'} from '${gqlImport.moduleName}';`);
break;
case DocumentMode.external:
if (this._collectedOperations.length > 0) {
if (this.config.importDocumentNodeExternallyFrom === 'near-operation-file' && this._documents.length === 1) {
imports.push(`import * as Operations from './${this.clearExtension(basename(this._documents[0].filePath))}';`);
} else {
imports.push(`import * as Operations from '${this.clearExtension(this.config.importDocumentNodeExternallyFrom)}';`);
}
}
break;
default:
break;
}
if (this.config.documentMode === DocumentMode.graphQLTag) {
(this._fragments || []).filter(f => f.isExternal && f.importFrom && (!f['level'] || (f['level'] !== undefined && f['level'] === 0))).forEach(externalFragment => {
const identifierName = this._getFragmentName(externalFragment.name);
imports.push(`import { ${identifierName} } from '${externalFragment.importFrom}';`);
});
}
return imports;
}
protected buildOperation(node: OperationDefinitionNode, documentVariableName: string, operationType: string, operationResultType: string, operationVariablesTypes: string): string {
return null;
}
public OperationDefinition(node: OperationDefinitionNode): string {
if (!node.name || !node.name.value) {
return null;
}
this._collectedOperations.push(node);
const documentVariableName = this.convertName(node, {
suffix: this.config.documentVariableSuffix,
prefix: this.config.documentVariablePrefix,
useTypesPrefix: false,
});
let documentString = '';
if (this.config.documentMode !== DocumentMode.external) {
documentString = `${this.config.noExport ? '' : 'export'} const ${documentVariableName}${this.config.documentMode === DocumentMode.documentNode ? ': DocumentNode' : ''} = ${this._gql(node)};`;
}
const operationType: string = toPascalCase(node.operation);
const operationTypeSuffix: string = this.config.dedupeOperationSuffix && node.name.value.toLowerCase().endsWith(node.operation) ? '' : operationType;
const operationResultType: string = this.convertName(node, {
suffix: operationTypeSuffix + this._parsedConfig.operationResultSuffix,
});
const operationVariablesTypes: string = this.convertName(node, {
suffix: operationTypeSuffix + 'Variables',
});
const additional = this.buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes);
return [documentString, additional].filter(a => a).join('\n');
}
}