-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathconfig.ts
506 lines (433 loc) · 13.9 KB
/
config.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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import { createHash, BinaryToTextEncoding } from 'crypto';
import { promises } from 'fs';
import { createRequire } from 'module';
import { resolve } from 'path';
import {
createNoopProfiler,
createProfiler,
getCachedDocumentNodeFromSchema,
Profiler,
Types,
} from '@graphql-codegen/plugin-helpers';
import { cosmiconfig, defaultLoaders } from 'cosmiconfig';
import jiti from 'jiti';
import { GraphQLSchema, GraphQLSchemaExtensions, print } from 'graphql';
import { GraphQLConfig } from 'graphql-config';
import { env } from 'string-env-interpolation';
import yaml from 'yaml';
import yargs from 'yargs';
import { findAndLoadGraphQLConfig } from './graphql-config.js';
import { defaultDocumentsLoadOptions, defaultSchemaLoadOptions, loadDocuments, loadSchema } from './load.js';
const { lstat } = promises;
export type CodegenConfig = Types.Config;
export type YamlCliFlags = {
config: string;
watch: boolean | string | string[];
require: string[];
overwrite: boolean;
project: string;
silent: boolean;
errorsOnly: boolean;
profile: boolean;
check?: boolean;
verbose?: boolean;
debug?: boolean;
ignoreNoDocuments?: boolean;
emitLegacyCommonJSImports?: boolean;
};
export function generateSearchPlaces(moduleName: string) {
const extensions = ['json', 'yaml', 'yml', 'js', 'ts', 'config.js'];
// gives codegen.json...
const regular = extensions.map(ext => `${moduleName}.${ext}`);
// gives .codegenrc.json... but no .codegenrc.config.js
const dot = extensions.filter(ext => ext !== 'config.js').map(ext => `.${moduleName}rc.${ext}`);
return [...regular.concat(dot), 'package.json'];
}
function customLoader(ext: 'json' | 'yaml' | 'js' | 'ts' | 'mts' | 'cts'): CodegenConfigLoader {
return async function loader(filepath, content) {
if (typeof process !== 'undefined' && 'env' in process) {
content = env(content);
}
if (ext === 'json') {
return defaultLoaders['.json'](filepath, content);
}
if (ext === 'yaml') {
try {
const result = yaml.parse(content, { prettyErrors: true, merge: true });
return result;
} catch (error) {
error.message = `YAML Error in ${filepath}:\n${error.message}`;
throw error;
}
}
if (ext === 'js') {
return defaultLoaders['.js'](filepath, content);
}
if (ext === 'ts') {
const jitiLoader = jiti('', { interopDefault: true });
return jitiLoader(filepath);
}
};
}
export type CodegenConfigLoader = (filepath: string, content: string) => Promise<Types.Config> | Types.Config;
export interface LoadCodegenConfigOptions {
/**
* The path to the config file or directory contains the config file.
* @default process.cwd()
*/
configFilePath?: string;
/**
* The name of the config file
* @default codegen
*/
moduleName?: string;
/**
* Additional search paths for the config file you want to check
*/
searchPlaces?: string[];
/**
* @default codegen
*/
packageProp?: string;
/**
* Overrides or extends the loaders for specific file extensions
*/
loaders?: Record<string, CodegenConfigLoader>;
}
export interface LoadCodegenConfigResult {
filepath: string;
config: Types.Config;
isEmpty?: boolean;
}
export async function loadCodegenConfig({
configFilePath,
moduleName,
searchPlaces: additionalSearchPlaces,
packageProp,
loaders: customLoaders,
}: LoadCodegenConfigOptions): Promise<LoadCodegenConfigResult> {
configFilePath ||= process.cwd();
moduleName ||= 'codegen';
packageProp ||= moduleName;
const cosmi = cosmiconfig(moduleName, {
searchPlaces: generateSearchPlaces(moduleName).concat(additionalSearchPlaces || []),
packageProp,
loaders: {
'.json': customLoader('json'),
'.yaml': customLoader('yaml'),
'.yml': customLoader('yaml'),
'.js': customLoader('js'),
'.ts': customLoader('ts'),
'.mts': customLoader('ts'),
'.cts': customLoader('ts'),
noExt: customLoader('yaml'),
...customLoaders,
},
});
const pathStats = await lstat(configFilePath);
return pathStats.isDirectory() ? cosmi.search(configFilePath) : cosmi.load(configFilePath);
}
export async function loadContext(configFilePath?: string): Promise<CodegenContext> | never {
const graphqlConfig = await findAndLoadGraphQLConfig(configFilePath);
if (graphqlConfig) {
return new CodegenContext({ graphqlConfig });
}
const result = await loadCodegenConfig({ configFilePath });
if (!result) {
if (configFilePath) {
throw new Error(
`
Config ${configFilePath} does not exist.
$ graphql-codegen --config ${configFilePath}
Please make sure the --config points to a correct file.
`
);
}
throw new Error(
`Unable to find Codegen config file! \n
Please make sure that you have a configuration file under the current directory!
`
);
}
if (result.isEmpty) {
throw new Error(
`Found Codegen config file but it was empty! \n
Please make sure that you have a valid configuration file under the current directory!
`
);
}
return new CodegenContext({
filepath: result.filepath,
config: result.config as Types.Config,
});
}
function getCustomConfigPath(cliFlags: YamlCliFlags): string | null | never {
const configFile = cliFlags.config;
return configFile ? resolve(process.cwd(), configFile) : null;
}
export function buildOptions() {
return {
c: {
alias: 'config',
type: 'string' as const,
describe: 'Path to GraphQL codegen YAML config file, defaults to "codegen.yml" on the current directory',
},
w: {
alias: 'watch',
describe:
'Watch for changes and execute generation automatically. You can also specify a glob expression for custom watch list.',
coerce(watch: any) {
if (watch === 'false') {
return false;
}
if (typeof watch === 'string' || Array.isArray(watch)) {
return watch;
}
return !!watch;
},
},
r: {
alias: 'require',
describe: 'Loads specific require.extensions before running the codegen and reading the configuration',
type: 'array' as const,
default: [],
},
o: {
alias: 'overwrite',
describe: 'Overwrites existing files',
type: 'boolean' as const,
},
s: {
alias: 'silent',
describe: 'Suppresses printing errors',
type: 'boolean' as const,
},
e: {
alias: 'errors-only',
describe: 'Only print errors',
type: 'boolean' as const,
},
profile: {
describe: 'Use profiler to measure performance',
type: 'boolean' as const,
},
p: {
alias: 'project',
describe: 'Name of a project in GraphQL Config',
type: 'string' as const,
},
v: {
alias: 'verbose',
describe: 'output more detailed information about performed tasks',
type: 'boolean' as const,
default: false,
},
d: {
alias: 'debug',
describe: 'Print debug logs to stdout',
type: 'boolean' as const,
default: false,
},
};
}
export function parseArgv(argv = process.argv): YamlCliFlags {
return yargs(argv).options(buildOptions()).parse(argv) as any;
}
export async function createContext(cliFlags: YamlCliFlags = parseArgv(process.argv)): Promise<CodegenContext> {
if (cliFlags.require && cliFlags.require.length > 0) {
const relativeRequire = createRequire(process.cwd());
await Promise.all(
cliFlags.require.map(
mod =>
import(
relativeRequire.resolve(mod, {
paths: [process.cwd()],
})
)
)
);
}
const customConfigPath = getCustomConfigPath(cliFlags);
const context = await loadContext(customConfigPath);
updateContextWithCliFlags(context, cliFlags);
return context;
}
export function updateContextWithCliFlags(context: CodegenContext, cliFlags: YamlCliFlags) {
const config: Partial<Types.Config & { configFilePath?: string }> = {
configFilePath: context.filepath,
};
if (cliFlags.watch !== undefined) {
config.watch = cliFlags.watch;
}
if (cliFlags.overwrite === true) {
config.overwrite = cliFlags.overwrite;
}
if (cliFlags.silent === true) {
config.silent = cliFlags.silent;
}
if (cliFlags.verbose === true || process.env.VERBOSE) {
config.verbose = true;
}
if (cliFlags.debug === true || process.env.DEBUG) {
config.debug = true;
}
if (cliFlags.errorsOnly === true) {
config.errorsOnly = cliFlags.errorsOnly;
}
if (cliFlags['ignore-no-documents'] !== undefined) {
// for some reason parsed value is `'false'` string so this ensure it always is a boolean.
config.ignoreNoDocuments = cliFlags['ignore-no-documents'] === true;
}
if (cliFlags['emit-legacy-common-js-imports'] !== undefined) {
// for some reason parsed value is `'false'` string so this ensure it always is a boolean.
config.emitLegacyCommonJSImports = cliFlags['emit-legacy-common-js-imports'] === true;
}
if (cliFlags.project) {
context.useProject(cliFlags.project);
}
if (cliFlags.profile === true) {
context.useProfiler();
}
if (cliFlags.check === true) {
context.enableCheckMode();
}
context.updateConfig(config);
}
export class CodegenContext {
private _config: Types.Config;
private _graphqlConfig?: GraphQLConfig;
private config: Types.Config;
private _project?: string;
private _checkMode = false;
private _pluginContext: { [key: string]: any } = {};
cwd: string;
filepath: string;
profiler: Profiler;
profilerOutput?: string;
checkModeStaleFiles = [];
constructor({
config,
graphqlConfig,
filepath,
}: {
config?: Types.Config;
graphqlConfig?: GraphQLConfig;
filepath?: string;
}) {
this._config = config;
this._graphqlConfig = graphqlConfig;
this.filepath = this._graphqlConfig ? this._graphqlConfig.filepath : filepath;
this.cwd = this._graphqlConfig ? this._graphqlConfig.dirpath : process.cwd();
this.profiler = createNoopProfiler();
}
useProject(name?: string) {
this._project = name;
}
getConfig<T>(extraConfig?: T): T & Types.Config {
if (!this.config) {
if (this._graphqlConfig) {
const project = this._graphqlConfig.getProject(this._project);
this.config = {
...project.extension('codegen'),
schema: project.schema,
documents: project.documents,
pluginContext: this._pluginContext,
};
} else {
this.config = { ...this._config, pluginContext: this._pluginContext };
}
}
return {
...extraConfig,
...this.config,
};
}
updateConfig(config: Partial<Types.Config>): void {
this.config = {
...this.getConfig(),
...config,
};
}
enableCheckMode() {
this._checkMode = true;
}
get checkMode() {
return this._checkMode;
}
useProfiler() {
this.profiler = createProfiler();
const now = new Date(); // 2011-10-05T14:48:00.000Z
const datetime = now.toISOString().split('.')[0]; // 2011-10-05T14:48:00
const datetimeNormalized = datetime.replace(/-|:/g, ''); // 20111005T144800
this.profilerOutput = `codegen-${datetimeNormalized}.json`;
}
getPluginContext(): { [key: string]: any } {
return this._pluginContext;
}
async loadSchema(pointer: Types.Schema): Promise<GraphQLSchema> {
const config = this.getConfig(defaultSchemaLoadOptions);
if (this._graphqlConfig) {
// TODO: SchemaWithLoader won't work here
return addHashToSchema(
this._graphqlConfig.getProject(this._project).loadSchema(pointer, 'GraphQLSchema', config)
);
}
return addHashToSchema(loadSchema(pointer, config));
}
async loadDocuments(pointer: Types.OperationDocument[]): Promise<Types.DocumentFile[]> {
const config = this.getConfig(defaultDocumentsLoadOptions);
if (this._graphqlConfig) {
// TODO: pointer won't work here
return addHashToDocumentFiles(this._graphqlConfig.getProject(this._project).loadDocuments(pointer, config));
}
return addHashToDocumentFiles(loadDocuments(pointer, config));
}
}
export function ensureContext(input: CodegenContext | Types.Config): CodegenContext {
return input instanceof CodegenContext ? input : new CodegenContext({ config: input });
}
function hashContent(content: string, encoding: BinaryToTextEncoding = 'hex'): string {
return createHash('sha256').update(content).digest(encoding);
}
function hashSchema(schema: GraphQLSchema): string {
return hashContent(print(getCachedDocumentNodeFromSchema(schema)));
}
function addHashToSchema(schemaPromise: Promise<GraphQLSchema>): Promise<GraphQLSchema> {
return schemaPromise.then(schema => {
// It's consumed later on. The general purpose is to use it for caching.
if (!schema.extensions) {
(schema.extensions as unknown as GraphQLSchemaExtensions) = {};
}
(schema.extensions as unknown as GraphQLSchemaExtensions)['hash'] = hashSchema(schema);
return schema;
});
}
function hashDocument(doc: Types.DocumentFile) {
if (doc.rawSDL) {
return hashContent(doc.rawSDL);
}
if (doc.document) {
return hashContent(print(doc.document));
}
return null;
}
function addHashToDocumentFiles(documentFilesPromise: Promise<Types.DocumentFile[]>): Promise<Types.DocumentFile[]> {
return documentFilesPromise.then(documentFiles =>
documentFiles.map(doc => {
doc.hash = hashDocument(doc);
return doc;
})
);
}
export function shouldEmitLegacyCommonJSImports(config: Types.Config): boolean {
const globalValue = config.emitLegacyCommonJSImports === undefined ? true : !!config.emitLegacyCommonJSImports;
// const outputConfig = config.generates[outputPath];
// if (!outputConfig) {
// debugLog(`Couldn't find a config of ${outputPath}`);
// return globalValue;
// }
// if (isConfiguredOutput(outputConfig) && typeof outputConfig.emitLegacyCommonJSImports === 'boolean') {
// return outputConfig.emitLegacyCommonJSImports;
// }
return globalValue;
}