@graphql-codegen/cli 2.8.0-alpha-bd464a586.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cjs/codegen.js CHANGED
@@ -5,7 +5,6 @@ const tslib_1 = require("tslib");
5
5
  const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
6
6
  const core_1 = require("@graphql-codegen/core");
7
7
  const utils_1 = require("@graphql-tools/utils");
8
- const listr_renderer_js_1 = require("./utils/listr-renderer.js");
9
8
  const graphql_1 = require("graphql");
10
9
  const plugins_js_1 = require("./plugins.js");
11
10
  const presets_js_1 = require("./presets.js");
@@ -15,8 +14,7 @@ const fs_1 = tslib_1.__importDefault(require("fs"));
15
14
  const path_1 = tslib_1.__importDefault(require("path"));
16
15
  const os_1 = require("os");
17
16
  const module_1 = require("module");
18
- const listr_1 = tslib_1.__importDefault(require("listr"));
19
- const cli_error_js_1 = require("./utils/cli-error.js");
17
+ const listr2_1 = require("listr2");
20
18
  /**
21
19
  * Poor mans ESM detection.
22
20
  * Looking at this and you have a better method?
@@ -57,39 +55,12 @@ async function executeCodegen(input) {
57
55
  const config = context.getConfig();
58
56
  const pluginContext = context.getPluginContext();
59
57
  const result = [];
60
- const commonListrOptions = {
61
- exitOnError: true,
62
- };
63
- let listr;
64
- if (process.env.VERBOSE) {
65
- listr = new listr_1.default({
66
- ...commonListrOptions,
67
- renderer: 'verbose',
68
- nonTTYRenderer: 'verbose',
69
- });
70
- }
71
- else if (process.env.NODE_ENV === 'test') {
72
- listr = new listr_1.default({
73
- ...commonListrOptions,
74
- renderer: 'silent',
75
- nonTTYRenderer: 'silent',
76
- });
77
- }
78
- else {
79
- listr = new listr_1.default({
80
- ...commonListrOptions,
81
- renderer: config.silent ? 'silent' : config.errorsOnly ? listr_renderer_js_1.ErrorRenderer : listr_renderer_js_1.Renderer,
82
- nonTTYRenderer: config.silent ? 'silent' : 'default',
83
- collapse: true,
84
- clearOutput: false,
85
- });
86
- }
87
58
  let rootConfig = {};
88
59
  let rootSchemas;
89
60
  let rootDocuments;
90
61
  const generates = {};
91
62
  const cache = createCache();
92
- function wrapTask(task, source, taskName) {
63
+ function wrapTask(task, source, taskName, ctx) {
93
64
  return () => {
94
65
  return context.profiler.run(async () => {
95
66
  try {
@@ -99,6 +70,7 @@ async function executeCodegen(input) {
99
70
  if (source && !(error instanceof graphql_1.GraphQLError)) {
100
71
  error.source = source;
101
72
  }
73
+ ctx.errors.push(error);
102
74
  throw error;
103
75
  }
104
76
  }, taskName);
@@ -169,123 +141,109 @@ async function executeCodegen(input) {
169
141
  `);
170
142
  }
171
143
  }
172
- listr.add({
173
- title: 'Parse configuration',
174
- task: () => normalize(),
175
- });
176
- listr.add({
177
- title: 'Generate outputs',
178
- task: () => {
179
- return new listr_1.default(Object.keys(generates).map(filename => {
180
- const outputConfig = generates[filename];
181
- const hasPreset = !!outputConfig.preset;
182
- return {
183
- title: hasPreset
144
+ const isTest = process.env.NODE_ENV === 'test';
145
+ const tasks = new listr2_1.Listr([
146
+ {
147
+ title: 'Parse Configuration',
148
+ task: () => normalize(),
149
+ },
150
+ {
151
+ title: 'Generate outputs',
152
+ task: (ctx, task) => {
153
+ const generateTasks = Object.keys(generates).map(filename => {
154
+ const outputConfig = generates[filename];
155
+ const hasPreset = !!outputConfig.preset;
156
+ const title = hasPreset
184
157
  ? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
185
- : `Generate ${filename}`,
186
- task: () => {
187
- let outputSchemaAst;
188
- let outputSchema;
189
- const outputFileTemplateConfig = outputConfig.config || {};
190
- let outputDocuments = [];
191
- const outputSpecificSchemas = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.schema);
192
- const outputSpecificDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.documents);
193
- return new listr_1.default([
194
- {
195
- title: 'Load GraphQL schemas',
196
- task: wrapTask(async () => {
197
- (0, debugging_js_1.debugLog)(`[CLI] Loading Schemas`);
198
- const schemaPointerMap = {};
199
- const allSchemaUnnormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
200
- for (const unnormalizedPtr of allSchemaUnnormalizedPointers) {
201
- if (typeof unnormalizedPtr === 'string') {
202
- schemaPointerMap[unnormalizedPtr] = {};
203
- }
204
- else if (typeof unnormalizedPtr === 'object') {
205
- Object.assign(schemaPointerMap, unnormalizedPtr);
206
- }
207
- }
208
- const hash = JSON.stringify(schemaPointerMap);
209
- const result = await cache('schema', hash, async () => {
210
- const outputSchemaAst = await context.loadSchema(schemaPointerMap);
211
- const outputSchema = (0, plugin_helpers_1.getCachedDocumentNodeFromSchema)(outputSchemaAst);
212
- return {
213
- outputSchemaAst,
214
- outputSchema,
215
- };
216
- });
217
- outputSchemaAst = await result.outputSchemaAst;
218
- outputSchema = result.outputSchema;
219
- }, filename, `Load GraphQL schemas: ${filename}`),
220
- },
221
- {
222
- title: 'Load GraphQL documents',
223
- task: wrapTask(async () => {
224
- (0, debugging_js_1.debugLog)(`[CLI] Loading Documents`);
225
- // get different cache for shared docs and output specific docs
226
- const documentPointerMap = {};
227
- const allDocumentsUnnormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
228
- for (const unnormalizedPtr of allDocumentsUnnormalizedPointers) {
229
- if (typeof unnormalizedPtr === 'string') {
230
- documentPointerMap[unnormalizedPtr] = {};
158
+ : `Generate ${filename}`;
159
+ return {
160
+ title,
161
+ task: (_, subTask) => {
162
+ let outputSchemaAst;
163
+ let outputSchema;
164
+ const outputFileTemplateConfig = outputConfig.config || {};
165
+ let outputDocuments = [];
166
+ const outputSpecificSchemas = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.schema);
167
+ const outputSpecificDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.documents);
168
+ return subTask.newListr([
169
+ {
170
+ title: 'Load GraphQL schemas',
171
+ task: wrapTask(async () => {
172
+ (0, debugging_js_1.debugLog)(`[CLI] Loading Schemas`);
173
+ const schemaPointerMap = {};
174
+ const allSchemaDenormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
175
+ for (const denormalizedPtr of allSchemaDenormalizedPointers) {
176
+ if (typeof denormalizedPtr === 'string') {
177
+ schemaPointerMap[denormalizedPtr] = {};
178
+ }
179
+ else if (typeof denormalizedPtr === 'object') {
180
+ Object.assign(schemaPointerMap, denormalizedPtr);
181
+ }
231
182
  }
232
- else if (typeof unnormalizedPtr === 'object') {
233
- Object.assign(documentPointerMap, unnormalizedPtr);
183
+ const hash = JSON.stringify(schemaPointerMap);
184
+ const result = await cache('schema', hash, async () => {
185
+ const outputSchemaAst = await context.loadSchema(schemaPointerMap);
186
+ const outputSchema = (0, plugin_helpers_1.getCachedDocumentNodeFromSchema)(outputSchemaAst);
187
+ return {
188
+ outputSchemaAst,
189
+ outputSchema,
190
+ };
191
+ });
192
+ outputSchemaAst = result.outputSchemaAst;
193
+ outputSchema = result.outputSchema;
194
+ }, filename, `Load GraphQL schemas: ${filename}`, ctx),
195
+ },
196
+ {
197
+ title: 'Load GraphQL documents',
198
+ task: wrapTask(async () => {
199
+ (0, debugging_js_1.debugLog)(`[CLI] Loading Documents`);
200
+ const documentPointerMap = {};
201
+ const allDocumentsDenormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
202
+ for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
203
+ if (typeof denormalizedPtr === 'string') {
204
+ documentPointerMap[denormalizedPtr] = {};
205
+ }
206
+ else if (typeof denormalizedPtr === 'object') {
207
+ Object.assign(documentPointerMap, denormalizedPtr);
208
+ }
234
209
  }
235
- }
236
- const hash = JSON.stringify(documentPointerMap);
237
- const result = await cache('documents', hash, async () => {
238
- const documents = await context.loadDocuments(documentPointerMap);
239
- return {
240
- documents,
210
+ const hash = JSON.stringify(documentPointerMap);
211
+ const result = await cache('documents', hash, async () => {
212
+ const documents = await context.loadDocuments(documentPointerMap);
213
+ return {
214
+ documents,
215
+ };
216
+ });
217
+ outputDocuments = result.documents;
218
+ }, filename, `Load GraphQL documents: ${filename}`, ctx),
219
+ },
220
+ {
221
+ title: 'Generate',
222
+ task: wrapTask(async () => {
223
+ (0, debugging_js_1.debugLog)(`[CLI] Generating output`);
224
+ const normalizedPluginsArray = (0, plugin_helpers_1.normalizeConfig)(outputConfig.plugins);
225
+ const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
226
+ const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => (0, plugins_js_1.getPluginByName)(Object.keys(plugin)[0], pluginLoader)));
227
+ const preset = hasPreset
228
+ ? typeof outputConfig.preset === 'string'
229
+ ? await (0, presets_js_1.getPresetByName)(outputConfig.preset, makeDefaultLoader(context.cwd))
230
+ : outputConfig.preset
231
+ : null;
232
+ const pluginMap = Object.fromEntries(pluginPackages.map((pkg, i) => {
233
+ const plugin = normalizedPluginsArray[i];
234
+ const name = Object.keys(plugin)[0];
235
+ return [name, pkg];
236
+ }));
237
+ const mergedConfig = {
238
+ ...rootConfig,
239
+ ...(typeof outputFileTemplateConfig === 'string'
240
+ ? { value: outputFileTemplateConfig }
241
+ : outputFileTemplateConfig),
241
242
  };
242
- });
243
- outputDocuments = await result.documents;
244
- }, filename, `Load GraphQL documents: ${filename}`),
245
- },
246
- {
247
- title: 'Generate',
248
- task: wrapTask(async () => {
249
- (0, debugging_js_1.debugLog)(`[CLI] Generating output`);
250
- const normalizedPluginsArray = (0, plugin_helpers_1.normalizeConfig)(outputConfig.plugins);
251
- const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
252
- const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => (0, plugins_js_1.getPluginByName)(Object.keys(plugin)[0], pluginLoader)));
253
- const pluginMap = {};
254
- const preset = hasPreset
255
- ? typeof outputConfig.preset === 'string'
256
- ? await (0, presets_js_1.getPresetByName)(outputConfig.preset, makeDefaultLoader(context.cwd))
257
- : outputConfig.preset
258
- : null;
259
- pluginPackages.forEach((pluginPackage, i) => {
260
- const plugin = normalizedPluginsArray[i];
261
- const name = Object.keys(plugin)[0];
262
- pluginMap[name] = pluginPackage;
263
- });
264
- const mergedConfig = {
265
- ...rootConfig,
266
- ...(typeof outputFileTemplateConfig === 'string'
267
- ? { value: outputFileTemplateConfig }
268
- : outputFileTemplateConfig),
269
- };
270
- let outputs = [];
271
- if (hasPreset) {
272
- outputs = await context.profiler.run(async () => preset.buildGeneratesSection({
273
- baseOutputDir: filename,
274
- presetConfig: outputConfig.presetConfig || {},
275
- plugins: normalizedPluginsArray,
276
- schema: outputSchema,
277
- schemaAst: outputSchemaAst,
278
- documents: outputDocuments,
279
- config: mergedConfig,
280
- pluginMap,
281
- pluginContext,
282
- profiler: context.profiler,
283
- }), `Build Generates Section: ${filename}`);
284
- }
285
- else {
286
- outputs = [
287
- {
288
- filename,
243
+ const outputs = hasPreset
244
+ ? await context.profiler.run(async () => preset.buildGeneratesSection({
245
+ baseOutputDir: filename,
246
+ presetConfig: outputConfig.presetConfig || {},
289
247
  plugins: normalizedPluginsArray,
290
248
  schema: outputSchema,
291
249
  schemaAst: outputSchemaAst,
@@ -294,50 +252,67 @@ async function executeCodegen(input) {
294
252
  pluginMap,
295
253
  pluginContext,
296
254
  profiler: context.profiler,
297
- },
298
- ];
299
- }
300
- const process = async (outputArgs) => {
301
- const output = await (0, core_1.codegen)({
302
- ...outputArgs,
303
- cache,
304
- });
305
- result.push({
306
- filename: outputArgs.filename,
307
- content: output,
308
- hooks: outputConfig.hooks || {},
309
- });
310
- };
311
- await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
312
- }, filename, `Generate: ${filename}`),
313
- },
314
- ], {
315
- // it stops when one of tasks failed
316
- exitOnError: true,
317
- });
318
- },
319
- };
320
- }), {
321
- // it doesn't stop when one of tasks failed, to finish at least some of outputs
322
- exitOnError: false,
323
- concurrent: (0, os_1.cpus)().length,
324
- });
255
+ }), `Build Generates Section: ${filename}`)
256
+ : [
257
+ {
258
+ filename,
259
+ plugins: normalizedPluginsArray,
260
+ schema: outputSchema,
261
+ schemaAst: outputSchemaAst,
262
+ documents: outputDocuments,
263
+ config: mergedConfig,
264
+ pluginMap,
265
+ pluginContext,
266
+ profiler: context.profiler,
267
+ },
268
+ ];
269
+ const process = async (outputArgs) => {
270
+ const output = await (0, core_1.codegen)({
271
+ ...outputArgs,
272
+ cache,
273
+ });
274
+ result.push({
275
+ filename: outputArgs.filename,
276
+ content: output,
277
+ hooks: outputConfig.hooks || {},
278
+ });
279
+ };
280
+ await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
281
+ }, filename, `Generate: ${filename}`, ctx),
282
+ },
283
+ ], {
284
+ // it stops when of the tasks failed
285
+ exitOnError: true,
286
+ });
287
+ },
288
+ // It doesn't stop when one of tasks failed, to finish at least some of outputs
289
+ exitOnError: false,
290
+ concurrent: (0, os_1.cpus)().length,
291
+ };
292
+ });
293
+ return task.newListr(generateTasks);
294
+ },
325
295
  },
296
+ ], {
297
+ rendererOptions: {
298
+ clearOutput: false,
299
+ collapse: true,
300
+ },
301
+ ctx: { errors: [] },
302
+ rendererSilent: isTest || config.silent,
303
+ exitOnError: true,
326
304
  });
327
- try {
328
- await listr.run();
329
- }
330
- catch (err) {
331
- if ((0, cli_error_js_1.isListrError)(err)) {
332
- const allErrs = err.errors.map(subErr => (0, plugin_helpers_1.isDetailedError)(subErr)
333
- ? `${subErr.message} for "${subErr.source}"${subErr.details}`
334
- : subErr.message || subErr.toString());
335
- const newErr = new utils_1.AggregateError(err.errors, `${err.message} ${allErrs.join('\n\n')}`);
336
- // Best-effort to all stack traces for debugging
337
- newErr.stack = `${newErr.stack}\n\n${err.errors.map(subErr => subErr.stack).join('\n\n')}`;
338
- throw newErr;
339
- }
340
- throw err;
305
+ // All the errors throw in `listr2` are collected in context
306
+ // Running tasks doesn't throw anything
307
+ const executedContext = await tasks.run();
308
+ if (executedContext.errors.length > 0) {
309
+ const errors = executedContext.errors.map(subErr => (0, plugin_helpers_1.isDetailedError)(subErr)
310
+ ? `${subErr.message} for "${subErr.source}"${subErr.details}`
311
+ : subErr.message || subErr.toString());
312
+ const newErr = new utils_1.AggregateError(executedContext.errors, `${errors.join('\n\n')}`);
313
+ // Best-effort to all stack traces for debugging
314
+ newErr.stack = `${newErr.stack}\n\n${executedContext.errors.map(subErr => subErr.stack).join('\n\n')}`;
315
+ throw newErr;
341
316
  }
342
317
  return result;
343
318
  }
package/cjs/config.js CHANGED
@@ -179,7 +179,7 @@ function updateContextWithCliFlags(context, cliFlags) {
179
179
  const config = {
180
180
  configFilePath: context.filepath,
181
181
  };
182
- if (cliFlags.watch) {
182
+ if (cliFlags.watch !== undefined) {
183
183
  config.watch = cliFlags.watch;
184
184
  }
185
185
  if (cliFlags.overwrite === true) {
@@ -191,6 +191,10 @@ function updateContextWithCliFlags(context, cliFlags) {
191
191
  if (cliFlags.errorsOnly === true) {
192
192
  config.errorsOnly = cliFlags.errorsOnly;
193
193
  }
194
+ if (cliFlags['ignore-no-documents'] !== undefined) {
195
+ // for some reason parsed value is `'false'` string so this ensure it always is a boolean.
196
+ config.ignoreNoDocuments = cliFlags['ignore-no-documents'] === true;
197
+ }
194
198
  if (cliFlags.project) {
195
199
  context.useProject(cliFlags.project);
196
200
  }
@@ -6,7 +6,7 @@ const chalk_1 = tslib_1.__importDefault(require("chalk"));
6
6
  const path_1 = require("path");
7
7
  const fs_1 = require("fs");
8
8
  const detect_indent_1 = tslib_1.__importDefault(require("detect-indent"));
9
- const latest_version_1 = tslib_1.__importDefault(require("latest-version"));
9
+ const get_latest_version_js_1 = require("../utils/get-latest-version.js");
10
10
  // Parses config and writes it to a file
11
11
  async function writeConfig(answers, config) {
12
12
  const YAML = await Promise.resolve().then(() => tslib_1.__importStar(require('json-to-pretty-yaml'))).then(m => ('default' in m ? m.default : m));
@@ -41,12 +41,12 @@ async function writePackage(answers, configLocation) {
41
41
  pkg.devDependencies = {};
42
42
  }
43
43
  await Promise.all(answers.plugins.map(async (plugin) => {
44
- pkg.devDependencies[plugin.package] = await (0, latest_version_1.default)(plugin.package);
44
+ pkg.devDependencies[plugin.package] = await (0, get_latest_version_js_1.getLatestVersion)(plugin.package);
45
45
  }));
46
46
  if (answers.introspection) {
47
- pkg.devDependencies['@graphql-codegen/introspection'] = await (0, latest_version_1.default)('@graphql-codegen/introspection');
47
+ pkg.devDependencies['@graphql-codegen/introspection'] = await (0, get_latest_version_js_1.getLatestVersion)('@graphql-codegen/introspection');
48
48
  }
49
- pkg.devDependencies['@graphql-codegen/cli'] = await (0, latest_version_1.default)('@graphql-codegen/cli');
49
+ pkg.devDependencies['@graphql-codegen/cli'] = await (0, get_latest_version_js_1.getLatestVersion)('@graphql-codegen/cli');
50
50
  (0, fs_1.writeFileSync)(pkgPath, JSON.stringify(pkg, null, indent));
51
51
  }
52
52
  exports.writePackage = writePackage;
package/cjs/load.js CHANGED
@@ -48,16 +48,16 @@ async function loadSchema(schemaPointers, config) {
48
48
 
49
49
  ${e.message || e}
50
50
  ${e.stack || ''}
51
-
51
+
52
52
  GraphQL Code Generator supports:
53
53
  - ES Modules and CommonJS exports (export as default or named export "schema")
54
54
  - Introspection JSON File
55
55
  - URL of GraphQL endpoint
56
56
  - Multiple files with type definitions (glob expression)
57
57
  - String in config file
58
-
58
+
59
59
  Try to use one of above options and run codegen again.
60
-
60
+
61
61
  `);
62
62
  }
63
63
  }
@@ -81,13 +81,20 @@ async function loadDocuments(documentPointers, config) {
81
81
  }
82
82
  ignore.push((0, path_1.join)(process.cwd(), generatePath));
83
83
  }
84
- const loadedFromToolkit = await (0, load_1.loadDocuments)(documentPointers, {
85
- ...exports.defaultDocumentsLoadOptions,
86
- ignore,
87
- loaders,
88
- ...config,
89
- ...config.config,
90
- });
91
- return loadedFromToolkit;
84
+ try {
85
+ const loadedFromToolkit = await (0, load_1.loadDocuments)(documentPointers, {
86
+ ...exports.defaultDocumentsLoadOptions,
87
+ ignore,
88
+ loaders,
89
+ ...config,
90
+ ...config.config,
91
+ });
92
+ return loadedFromToolkit;
93
+ }
94
+ catch (error) {
95
+ if (config.ignoreNoDocuments)
96
+ return [];
97
+ throw error;
98
+ }
92
99
  }
93
100
  exports.loadDocuments = loadDocuments;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLatestVersion = void 0;
4
+ const cross_undici_fetch_1 = require("cross-undici-fetch");
5
+ /**
6
+ * Fetches the version directly from the registry instead of depending on
7
+ * an ESM only module as latest-version does.
8
+ * @param packageName
9
+ */
10
+ async function getLatestVersion(packageName) {
11
+ return (0, cross_undici_fetch_1.fetch)(`https://unpkg.com/${packageName}/package.json`)
12
+ .then(res => res.json())
13
+ .then(pkg => pkg.version);
14
+ }
15
+ exports.getLatestVersion = getLatestVersion;