-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
config.ts
386 lines (334 loc) · 10.5 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
import { cosmiconfig, defaultLoaders } from 'cosmiconfig';
import { resolve } from 'path';
import { DetailedError, Types, Profiler, createProfiler, createNoopProfiler } from '@graphql-codegen/plugin-helpers';
import { env } from 'string-env-interpolation';
import yargs from 'yargs';
import { GraphQLConfig } from 'graphql-config';
import { findAndLoadGraphQLConfig } from './graphql-config';
import { loadSchema, loadDocuments, defaultSchemaLoadOptions, defaultDocumentsLoadOptions } from './load';
import { GraphQLSchema } from 'graphql';
import yaml from 'yaml';
import { createRequire } from 'module';
import { promises } from 'fs';
const { lstat } = promises;
export type YamlCliFlags = {
config: string;
watch: boolean | string | string[];
require: string[];
overwrite: boolean;
project: string;
silent: boolean;
errorsOnly: boolean;
profile: boolean;
};
export function generateSearchPlaces(moduleName: string) {
const extensions = ['json', 'yaml', 'yml', 'js', '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') {
function loader(filepath: string, content: string) {
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);
}
}
return loader;
}
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, (filepath: string, content: string) => Promise<Types.Config> | Types.Config>;
}
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 = configFilePath || process.cwd();
moduleName = moduleName || 'codegen';
packageProp = 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'),
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 DetailedError(
`Config ${configFilePath} does not exist`,
`
Config ${configFilePath} does not exist.
$ graphql-codegen --config ${configFilePath}
Please make sure the --config points to a correct file.
`
);
}
throw new DetailedError(
`Unable to find Codegen config file!`,
`
Please make sure that you have a configuration file under the current directory!
`
);
}
if (result.isEmpty) {
throw new DetailedError(
`Found Codegen config file but it was empty!`,
`
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 expreession 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,
},
};
}
export function parseArgv(argv = process.argv): YamlCliFlags {
return yargs.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) {
config.watch = cliFlags.watch;
}
if (cliFlags.overwrite === true) {
config.overwrite = cliFlags.overwrite;
}
if (cliFlags.silent === true) {
config.silent = cliFlags.silent;
}
if (cliFlags.errorsOnly === true) {
config.errorsOnly = cliFlags.errorsOnly;
}
if (cliFlags.project) {
context.useProject(cliFlags.project);
}
if (cliFlags.profile === true) {
context.useProfiler();
}
context.updateConfig(config);
}
export class CodegenContext {
private _config: Types.Config;
private _graphqlConfig?: GraphQLConfig;
private config: Types.Config;
private _project?: string;
private _pluginContext: { [key: string]: any } = {};
cwd: string;
filepath: string;
profiler: Profiler;
profilerOutput?: string;
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,
};
}
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 this._graphqlConfig.getProject(this._project).loadSchema(pointer, 'GraphQLSchema', config);
}
return 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
const documents = await this._graphqlConfig.getProject(this._project).loadDocuments(pointer, config);
return documents;
}
return loadDocuments(pointer, config);
}
}
export function ensureContext(input: CodegenContext | Types.Config): CodegenContext {
return input instanceof CodegenContext ? input : new CodegenContext({ config: input });
}