@graphql-codegen/cli 2.6.5-alpha-d6416b45e.0 → 2.6.5-alpha-43974d1af.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/bin.js CHANGED
@@ -29,6 +29,12 @@ const path__default = _interopDefault(path);
29
29
  const pluginHelpers = require('@graphql-codegen/plugin-helpers');
30
30
  const core = require('@graphql-codegen/core');
31
31
  const utils = require('@graphql-tools/utils');
32
+ const chalk = _interopDefault(require('chalk'));
33
+ const logSymbols = _interopDefault(require('log-symbols'));
34
+ const ansiEscapes = _interopDefault(require('ansi-escapes'));
35
+ const wrapAnsi = _interopDefault(require('wrap-ansi'));
36
+ const commonTags = require('common-tags');
37
+ const UpdateRenderer = _interopDefault(require('listr-update-renderer'));
32
38
  const graphql = require('graphql');
33
39
  const cosmiconfig = require('cosmiconfig');
34
40
  const stringEnvInterpolation = require('string-env-interpolation');
@@ -49,13 +55,11 @@ const fs = require('fs');
49
55
  const fs__default = _interopDefault(fs);
50
56
  const crypto = require('crypto');
51
57
  const os = require('os');
52
- const listr2 = require('listr2');
58
+ const Listr = _interopDefault(require('listr'));
53
59
  const isGlob = _interopDefault(require('is-glob'));
54
60
  const debounce = _interopDefault(require('debounce'));
55
- const logSymbols = _interopDefault(require('log-symbols'));
56
61
  const mkdirp = _interopDefault(require('mkdirp'));
57
62
  const inquirer = _interopDefault(require('inquirer'));
58
- const chalk = _interopDefault(require('chalk'));
59
63
  const detectIndent = _interopDefault(require('detect-indent'));
60
64
  const getLatestVersion = _interopDefault(require('latest-version'));
61
65
 
@@ -71,8 +75,25 @@ function useWinstonLogger() {
71
75
  logger = console;
72
76
  }
73
77
 
78
+ let queue = [];
74
79
  function debugLog(message, ...meta) {
75
- if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) ;
80
+ if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) {
81
+ queue.push({
82
+ message,
83
+ meta,
84
+ });
85
+ }
86
+ }
87
+ function printLogs() {
88
+ if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) {
89
+ queue.forEach(log => {
90
+ getLogger().info(log.message, ...log.meta);
91
+ });
92
+ resetLogs();
93
+ }
94
+ }
95
+ function resetLogs() {
96
+ queue = [];
76
97
  }
77
98
 
78
99
  const DEFAULT_HOOKS = {
@@ -130,7 +151,7 @@ function execShellCommand(cmd) {
130
151
  });
131
152
  }
132
153
  async function executeHooks(hookName, scripts = [], args = []) {
133
- debugLog();
154
+ debugLog(`Running lifecycle hook "${hookName}" scripts...`);
134
155
  for (const script of scripts) {
135
156
  if (typeof script === 'string') {
136
157
  debugLog(`Running lifecycle hook "${hookName}" script: ${script} with args: ${args.join(' ')}...`);
@@ -156,6 +177,162 @@ const lifecycleHooks = (_hooks = {}) => {
156
177
  };
157
178
  };
158
179
 
180
+ /**
181
+ Indent each line in a string.
182
+ @param string - The string to indent.
183
+ @param count - How many times you want `options.indent` repeated. Default: `1`.
184
+ @example
185
+ ```
186
+ import indentString from 'indent-string';
187
+ indentString('Unicorns\nRainbows', 4);
188
+ //=> ' Unicorns\n Rainbows'
189
+ indentString('Unicorns\nRainbows', 4, {indent: '♥'});
190
+ //=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
191
+ ```
192
+ */
193
+ function indentString(string, count = 1, options = {}) {
194
+ const { indent = ' ', includeEmptyLines = false } = options;
195
+ if (typeof string !== 'string') {
196
+ throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);
197
+ }
198
+ if (typeof count !== 'number') {
199
+ throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);
200
+ }
201
+ if (count < 0) {
202
+ throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``);
203
+ }
204
+ if (typeof indent !== 'string') {
205
+ throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
206
+ }
207
+ if (count === 0) {
208
+ return string;
209
+ }
210
+ const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
211
+ return string.replace(regex, indent.repeat(count));
212
+ }
213
+
214
+ class Renderer {
215
+ constructor(tasks, options) {
216
+ this.updateRenderer = new UpdateRenderer(tasks, options);
217
+ }
218
+ render() {
219
+ return this.updateRenderer.render();
220
+ }
221
+ end(err) {
222
+ this.updateRenderer.end(err);
223
+ if (typeof err === 'undefined') {
224
+ logUpdate.clear();
225
+ return;
226
+ }
227
+ // persist the output
228
+ logUpdate.done();
229
+ // show errors
230
+ if (err) {
231
+ const errorCount = err.errors ? err.errors.length : 0;
232
+ if (errorCount > 0) {
233
+ const count = indentString(chalk.red.bold(`Found ${errorCount} error${errorCount > 1 ? 's' : ''}`), 1);
234
+ const details = err.errors
235
+ .map(error => {
236
+ debugLog(`[CLI] Exited with an error`, error);
237
+ return { msg: pluginHelpers.isDetailedError(error) ? error.details : null, rawError: error };
238
+ })
239
+ .map(({ msg, rawError }, i) => {
240
+ const source = err.errors[i].source;
241
+ msg = msg ? chalk.gray(indentString(commonTags.stripIndent(`${msg}`), 4)) : null;
242
+ const stack = rawError.stack ? chalk.gray(indentString(commonTags.stripIndent(rawError.stack), 4)) : null;
243
+ if (source) {
244
+ const sourceOfError = typeof source === 'string' ? source : source.name;
245
+ const title = indentString(`${logSymbols.error} ${sourceOfError}`, 2);
246
+ return [title, msg, stack, stack].filter(Boolean).join('\n');
247
+ }
248
+ return [msg, stack].filter(Boolean).join('\n');
249
+ })
250
+ .join('\n\n');
251
+ logUpdate.emit(['', count, details, ''].join('\n\n'));
252
+ }
253
+ else {
254
+ const details = err.details ? err.details : '';
255
+ logUpdate.emit(`${chalk.red.bold(`${indentString(err.message, 2)}`)}\n${details}\n${chalk.grey(err.stack)}`);
256
+ }
257
+ }
258
+ logUpdate.done();
259
+ printLogs();
260
+ }
261
+ }
262
+ const render = tasks => {
263
+ for (const task of tasks) {
264
+ task.subscribe(event => {
265
+ if (event.type === 'SUBTASKS') {
266
+ render(task.subtasks);
267
+ return;
268
+ }
269
+ if (event.type === 'DATA') {
270
+ logUpdate.emit(chalk.dim(`${event.data}`));
271
+ }
272
+ logUpdate.done();
273
+ }, err => {
274
+ logUpdate.emit(err);
275
+ logUpdate.done();
276
+ });
277
+ }
278
+ };
279
+ class ErrorRenderer {
280
+ constructor(tasks, _options) {
281
+ this.tasks = tasks;
282
+ }
283
+ render() {
284
+ render(this.tasks);
285
+ }
286
+ static get nonTTY() {
287
+ return true;
288
+ }
289
+ end() { }
290
+ }
291
+ class LogUpdate {
292
+ constructor() {
293
+ this.stream = process.stdout;
294
+ // state
295
+ this.previousLineCount = 0;
296
+ this.previousOutput = '';
297
+ this.previousWidth = this.getWidth();
298
+ }
299
+ emit(...args) {
300
+ let output = args.join(' ') + '\n';
301
+ const width = this.getWidth();
302
+ if (output === this.previousOutput && this.previousWidth === width) {
303
+ return;
304
+ }
305
+ this.previousOutput = output;
306
+ this.previousWidth = width;
307
+ output = wrapAnsi(output, width, {
308
+ trim: false,
309
+ hard: true,
310
+ wordWrap: false,
311
+ });
312
+ this.stream.write(ansiEscapes.eraseLines(this.previousLineCount) + output);
313
+ this.previousLineCount = output.split('\n').length;
314
+ }
315
+ clear() {
316
+ this.stream.write(ansiEscapes.eraseLines(this.previousLineCount));
317
+ this.previousOutput = '';
318
+ this.previousWidth = this.getWidth();
319
+ this.previousLineCount = 0;
320
+ }
321
+ done() {
322
+ this.previousOutput = '';
323
+ this.previousWidth = this.getWidth();
324
+ this.previousLineCount = 0;
325
+ }
326
+ getWidth() {
327
+ const { columns } = this.stream;
328
+ if (!columns) {
329
+ return 80;
330
+ }
331
+ return columns;
332
+ }
333
+ }
334
+ const logUpdate = new LogUpdate();
335
+
159
336
  async function getPluginByName(name, pluginLoader) {
160
337
  const possibleNames = [
161
338
  `@graphql-codegen/${name}`,
@@ -653,6 +830,27 @@ function addHashToDocumentFiles(documentFilesPromise) {
653
830
  }));
654
831
  }
655
832
 
833
+ function isListrError(err) {
834
+ return err.name === 'ListrError' && Array.isArray(err.errors) && err.errors.length > 0;
835
+ }
836
+ function cliError(err, exitOnError = true) {
837
+ let msg;
838
+ if (err instanceof Error) {
839
+ msg = err.message || err.toString();
840
+ }
841
+ else if (typeof err === 'string') {
842
+ msg = err;
843
+ }
844
+ else {
845
+ msg = JSON.stringify(err);
846
+ }
847
+ // eslint-disable-next-line no-console
848
+ console.error(msg);
849
+ if (exitOnError) {
850
+ process.exit(1);
851
+ }
852
+ }
853
+
656
854
  const makeDefaultLoader = (from) => {
657
855
  if (fs__default.statSync(from).isDirectory()) {
658
856
  from = path__default.join(from, '__fake.js');
@@ -680,12 +878,39 @@ async function executeCodegen(input) {
680
878
  const config = context.getConfig();
681
879
  const pluginContext = context.getPluginContext();
682
880
  const result = [];
881
+ const commonListrOptions = {
882
+ exitOnError: true,
883
+ };
884
+ let listr;
885
+ if (process.env.VERBOSE) {
886
+ listr = new Listr({
887
+ ...commonListrOptions,
888
+ renderer: 'verbose',
889
+ nonTTYRenderer: 'verbose',
890
+ });
891
+ }
892
+ else if (process.env.NODE_ENV === 'test') {
893
+ listr = new Listr({
894
+ ...commonListrOptions,
895
+ renderer: 'silent',
896
+ nonTTYRenderer: 'silent',
897
+ });
898
+ }
899
+ else {
900
+ listr = new Listr({
901
+ ...commonListrOptions,
902
+ renderer: config.silent ? 'silent' : config.errorsOnly ? ErrorRenderer : Renderer,
903
+ nonTTYRenderer: config.silent ? 'silent' : 'default',
904
+ collapse: true,
905
+ clearOutput: false,
906
+ });
907
+ }
683
908
  let rootConfig = {};
684
909
  let rootSchemas;
685
910
  let rootDocuments;
686
911
  const generates = {};
687
912
  const cache = createCache();
688
- function wrapTask(task, source, taskName, ctx) {
913
+ function wrapTask(task, source, taskName) {
689
914
  return () => {
690
915
  return context.profiler.run(async () => {
691
916
  try {
@@ -695,7 +920,6 @@ async function executeCodegen(input) {
695
920
  if (source && !(error instanceof graphql.GraphQLError)) {
696
921
  error.source = source;
697
922
  }
698
- ctx.errors.push(error);
699
923
  throw error;
700
924
  }
701
925
  }, taskName);
@@ -766,109 +990,123 @@ async function executeCodegen(input) {
766
990
  `);
767
991
  }
768
992
  }
769
- const isTest = process.env.NODE_ENV === 'test';
770
- const tasks = new listr2.Listr([
771
- {
772
- title: 'Parse Configuration',
773
- task: () => normalize(),
774
- },
775
- {
776
- title: 'Generate outputs',
777
- task: (ctx, task) => {
778
- const generateTasks = Object.keys(generates).map(filename => {
779
- const outputConfig = generates[filename];
780
- const hasPreset = !!outputConfig.preset;
781
- const title = hasPreset
993
+ listr.add({
994
+ title: 'Parse configuration',
995
+ task: () => normalize(),
996
+ });
997
+ listr.add({
998
+ title: 'Generate outputs',
999
+ task: () => {
1000
+ return new Listr(Object.keys(generates).map(filename => {
1001
+ const outputConfig = generates[filename];
1002
+ const hasPreset = !!outputConfig.preset;
1003
+ return {
1004
+ title: hasPreset
782
1005
  ? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
783
- : `Generate ${filename}`;
784
- return {
785
- title,
786
- task: (_, subTask) => {
787
- let outputSchemaAst;
788
- let outputSchema;
789
- const outputFileTemplateConfig = outputConfig.config || {};
790
- let outputDocuments = [];
791
- const outputSpecificSchemas = pluginHelpers.normalizeInstanceOrArray(outputConfig.schema);
792
- const outputSpecificDocuments = pluginHelpers.normalizeInstanceOrArray(outputConfig.documents);
793
- return subTask.newListr([
794
- {
795
- title: 'Load GraphQL schemas',
796
- task: wrapTask(async () => {
797
- debugLog(`[CLI] Loading Schemas`);
798
- const schemaPointerMap = {};
799
- const allSchemaDenormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
800
- for (const denormalizedPtr of allSchemaDenormalizedPointers) {
801
- if (typeof denormalizedPtr === 'string') {
802
- schemaPointerMap[denormalizedPtr] = {};
803
- }
804
- else if (typeof denormalizedPtr === 'object') {
805
- Object.assign(schemaPointerMap, denormalizedPtr);
806
- }
1006
+ : `Generate ${filename}`,
1007
+ task: () => {
1008
+ let outputSchemaAst;
1009
+ let outputSchema;
1010
+ const outputFileTemplateConfig = outputConfig.config || {};
1011
+ let outputDocuments = [];
1012
+ const outputSpecificSchemas = pluginHelpers.normalizeInstanceOrArray(outputConfig.schema);
1013
+ const outputSpecificDocuments = pluginHelpers.normalizeInstanceOrArray(outputConfig.documents);
1014
+ return new Listr([
1015
+ {
1016
+ title: 'Load GraphQL schemas',
1017
+ task: wrapTask(async () => {
1018
+ debugLog(`[CLI] Loading Schemas`);
1019
+ const schemaPointerMap = {};
1020
+ const allSchemaUnnormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
1021
+ for (const unnormalizedPtr of allSchemaUnnormalizedPointers) {
1022
+ if (typeof unnormalizedPtr === 'string') {
1023
+ schemaPointerMap[unnormalizedPtr] = {};
807
1024
  }
808
- const hash = JSON.stringify(schemaPointerMap);
809
- const result = await cache('schema', hash, async () => {
810
- const outputSchemaAst = await context.loadSchema(schemaPointerMap);
811
- const outputSchema = pluginHelpers.getCachedDocumentNodeFromSchema(outputSchemaAst);
812
- return {
813
- outputSchemaAst,
814
- outputSchema,
815
- };
816
- });
817
- outputSchemaAst = result.outputSchemaAst;
818
- outputSchema = result.outputSchema;
819
- }, filename, `Load GraphQL schemas: ${filename}`, ctx),
820
- },
821
- {
822
- title: 'Load GraphQL documents',
823
- task: wrapTask(async () => {
824
- debugLog(`[CLI] Loading Documents`);
825
- const documentPointerMap = {};
826
- const allDocumentsDenormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
827
- for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
828
- if (typeof denormalizedPtr === 'string') {
829
- documentPointerMap[denormalizedPtr] = {};
830
- }
831
- else if (typeof denormalizedPtr === 'object') {
832
- Object.assign(documentPointerMap, denormalizedPtr);
833
- }
1025
+ else if (typeof unnormalizedPtr === 'object') {
1026
+ Object.assign(schemaPointerMap, unnormalizedPtr);
834
1027
  }
835
- const hash = JSON.stringify(documentPointerMap);
836
- const result = await cache('documents', hash, async () => {
837
- const documents = await context.loadDocuments(documentPointerMap);
838
- return {
839
- documents,
840
- };
841
- });
842
- outputDocuments = result.documents;
843
- }, filename, `Load GraphQL documents: ${filename}`, ctx),
844
- },
845
- {
846
- title: 'Generate',
847
- task: wrapTask(async () => {
848
- debugLog(`[CLI] Generating output`);
849
- const normalizedPluginsArray = pluginHelpers.normalizeConfig(outputConfig.plugins);
850
- const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
851
- const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader)));
852
- const preset = hasPreset
853
- ? typeof outputConfig.preset === 'string'
854
- ? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
855
- : outputConfig.preset
856
- : null;
857
- const pluginMap = Object.fromEntries(pluginPackages.map((pkg, i) => {
858
- const plugin = normalizedPluginsArray[i];
859
- const name = Object.keys(plugin)[0];
860
- return [name, pkg];
861
- }));
862
- const mergedConfig = {
863
- ...rootConfig,
864
- ...(typeof outputFileTemplateConfig === 'string'
865
- ? { value: outputFileTemplateConfig }
866
- : outputFileTemplateConfig),
1028
+ }
1029
+ const hash = JSON.stringify(schemaPointerMap);
1030
+ const result = await cache('schema', hash, async () => {
1031
+ const outputSchemaAst = await context.loadSchema(schemaPointerMap);
1032
+ const outputSchema = pluginHelpers.getCachedDocumentNodeFromSchema(outputSchemaAst);
1033
+ return {
1034
+ outputSchemaAst,
1035
+ outputSchema,
867
1036
  };
868
- const outputs = hasPreset
869
- ? await context.profiler.run(async () => preset.buildGeneratesSection({
870
- baseOutputDir: filename,
871
- presetConfig: outputConfig.presetConfig || {},
1037
+ });
1038
+ outputSchemaAst = await result.outputSchemaAst;
1039
+ outputSchema = result.outputSchema;
1040
+ }, filename, `Load GraphQL schemas: ${filename}`),
1041
+ },
1042
+ {
1043
+ title: 'Load GraphQL documents',
1044
+ task: wrapTask(async () => {
1045
+ debugLog(`[CLI] Loading Documents`);
1046
+ // get different cache for shared docs and output specific docs
1047
+ const documentPointerMap = {};
1048
+ const allDocumentsUnnormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
1049
+ for (const unnormalizedPtr of allDocumentsUnnormalizedPointers) {
1050
+ if (typeof unnormalizedPtr === 'string') {
1051
+ documentPointerMap[unnormalizedPtr] = {};
1052
+ }
1053
+ else if (typeof unnormalizedPtr === 'object') {
1054
+ Object.assign(documentPointerMap, unnormalizedPtr);
1055
+ }
1056
+ }
1057
+ const hash = JSON.stringify(documentPointerMap);
1058
+ const result = await cache('documents', hash, async () => {
1059
+ const documents = await context.loadDocuments(documentPointerMap);
1060
+ return {
1061
+ documents,
1062
+ };
1063
+ });
1064
+ outputDocuments = await result.documents;
1065
+ }, filename, `Load GraphQL documents: ${filename}`),
1066
+ },
1067
+ {
1068
+ title: 'Generate',
1069
+ task: wrapTask(async () => {
1070
+ debugLog(`[CLI] Generating output`);
1071
+ const normalizedPluginsArray = pluginHelpers.normalizeConfig(outputConfig.plugins);
1072
+ const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
1073
+ const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader)));
1074
+ const pluginMap = {};
1075
+ const preset = hasPreset
1076
+ ? typeof outputConfig.preset === 'string'
1077
+ ? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
1078
+ : outputConfig.preset
1079
+ : null;
1080
+ pluginPackages.forEach((pluginPackage, i) => {
1081
+ const plugin = normalizedPluginsArray[i];
1082
+ const name = Object.keys(plugin)[0];
1083
+ pluginMap[name] = pluginPackage;
1084
+ });
1085
+ const mergedConfig = {
1086
+ ...rootConfig,
1087
+ ...(typeof outputFileTemplateConfig === 'string'
1088
+ ? { value: outputFileTemplateConfig }
1089
+ : outputFileTemplateConfig),
1090
+ };
1091
+ let outputs = [];
1092
+ if (hasPreset) {
1093
+ outputs = await context.profiler.run(async () => preset.buildGeneratesSection({
1094
+ baseOutputDir: filename,
1095
+ presetConfig: outputConfig.presetConfig || {},
1096
+ plugins: normalizedPluginsArray,
1097
+ schema: outputSchema,
1098
+ schemaAst: outputSchemaAst,
1099
+ documents: outputDocuments,
1100
+ config: mergedConfig,
1101
+ pluginMap,
1102
+ pluginContext,
1103
+ profiler: context.profiler,
1104
+ }), `Build Generates Section: ${filename}`);
1105
+ }
1106
+ else {
1107
+ outputs = [
1108
+ {
1109
+ filename,
872
1110
  plugins: normalizedPluginsArray,
873
1111
  schema: outputSchema,
874
1112
  schemaAst: outputSchemaAst,
@@ -877,67 +1115,50 @@ async function executeCodegen(input) {
877
1115
  pluginMap,
878
1116
  pluginContext,
879
1117
  profiler: context.profiler,
880
- }), `Build Generates Section: ${filename}`)
881
- : [
882
- {
883
- filename,
884
- plugins: normalizedPluginsArray,
885
- schema: outputSchema,
886
- schemaAst: outputSchemaAst,
887
- documents: outputDocuments,
888
- config: mergedConfig,
889
- pluginMap,
890
- pluginContext,
891
- profiler: context.profiler,
892
- },
893
- ];
894
- const process = async (outputArgs) => {
895
- const output = await core.codegen({
896
- ...outputArgs,
897
- cache,
898
- });
899
- result.push({
900
- filename: outputArgs.filename,
901
- content: output,
902
- hooks: outputConfig.hooks || {},
903
- });
904
- };
905
- await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
906
- }, filename, `Generate: ${filename}`, ctx),
907
- },
908
- ], {
909
- // it stops when of the tasks failed
910
- exitOnError: true,
911
- });
912
- },
913
- // It doesn't stop when one of tasks failed, to finish at least some of outputs
914
- exitOnError: false,
915
- concurrent: os.cpus().length,
916
- };
917
- });
918
- return task.newListr(generateTasks);
919
- },
920
- },
921
- ], {
922
- rendererOptions: {
923
- clearOutput: false,
924
- collapse: true,
1118
+ },
1119
+ ];
1120
+ }
1121
+ const process = async (outputArgs) => {
1122
+ const output = await core.codegen({
1123
+ ...outputArgs,
1124
+ cache,
1125
+ });
1126
+ result.push({
1127
+ filename: outputArgs.filename,
1128
+ content: output,
1129
+ hooks: outputConfig.hooks || {},
1130
+ });
1131
+ };
1132
+ await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
1133
+ }, filename, `Generate: ${filename}`),
1134
+ },
1135
+ ], {
1136
+ // it stops when one of tasks failed
1137
+ exitOnError: true,
1138
+ });
1139
+ },
1140
+ };
1141
+ }), {
1142
+ // it doesn't stop when one of tasks failed, to finish at least some of outputs
1143
+ exitOnError: false,
1144
+ concurrent: os.cpus().length,
1145
+ });
925
1146
  },
926
- ctx: { errors: [] },
927
- rendererSilent: isTest || config.silent,
928
- exitOnError: true,
929
1147
  });
930
- // All the errors throw in `listr2` are collected in context
931
- // Running tasks doesn't throw anything
932
- const executedContext = await tasks.run();
933
- if (executedContext.errors.length > 0) {
934
- const errors = executedContext.errors.map(subErr => pluginHelpers.isDetailedError(subErr)
935
- ? `${subErr.message} for "${subErr.source}"${subErr.details}`
936
- : subErr.message || subErr.toString());
937
- const newErr = new utils.AggregateError(executedContext.errors, `${errors.join('\n\n')}`);
938
- // Best-effort to all stack traces for debugging
939
- newErr.stack = `${newErr.stack}\n\n${executedContext.errors.map(subErr => subErr.stack).join('\n\n')}`;
940
- throw newErr;
1148
+ try {
1149
+ await listr.run();
1150
+ }
1151
+ catch (err) {
1152
+ if (isListrError(err)) {
1153
+ const allErrs = err.errors.map(subErr => pluginHelpers.isDetailedError(subErr)
1154
+ ? `${subErr.message} for "${subErr.source}"${subErr.details}`
1155
+ : subErr.message || subErr.toString());
1156
+ const newErr = new utils.AggregateError(err.errors, `${err.message} ${allErrs.join('\n\n')}`);
1157
+ // Best-effort to all stack traces for debugging
1158
+ newErr.stack = `${newErr.stack}\n\n${err.errors.map(subErr => subErr.stack).join('\n\n')}`;
1159
+ throw newErr;
1160
+ }
1161
+ throw err;
941
1162
  }
942
1163
  return result;
943
1164
  }
@@ -950,7 +1171,7 @@ function emitWatching() {
950
1171
  log(`${logSymbols.info} Watching for changes...`);
951
1172
  }
952
1173
  const createWatcher = (initalContext, onNext) => {
953
- debugLog();
1174
+ debugLog(`[Watcher] Starting watcher...`);
954
1175
  let config = initalContext.getConfig();
955
1176
  const files = [initalContext.filepath].filter(a => a);
956
1177
  const documents = pluginHelpers.normalizeInstanceOrArray(config.documents);
@@ -1021,10 +1242,10 @@ const createWatcher = (initalContext, onNext) => {
1021
1242
  atomic: true,
1022
1243
  ignored,
1023
1244
  });
1024
- debugLog();
1245
+ debugLog(`[Watcher] Started`);
1025
1246
  const shutdown = () => {
1026
1247
  isShutdown = true;
1027
- debugLog();
1248
+ debugLog(`[Watcher] Shutting down`);
1028
1249
  log(`Shutting down watch...`);
1029
1250
  watcher.close();
1030
1251
  lifecycleHooks(config.hooks).beforeDone();
@@ -1032,7 +1253,7 @@ const createWatcher = (initalContext, onNext) => {
1032
1253
  // it doesn't matter what has changed, need to run whole process anyway
1033
1254
  watcher.on('all', async (eventName, path$1) => {
1034
1255
  lifecycleHooks(config.hooks).onWatchTriggered(eventName, path$1);
1035
- debugLog();
1256
+ debugLog(`[Watcher] triggered due to a file ${eventName} event: ${path$1}`);
1036
1257
  const fullPath = path.join(process.cwd(), path$1);
1037
1258
  // In ESM require is not defined
1038
1259
  try {
@@ -1101,10 +1322,10 @@ async function generate(input, saveToFile = true) {
1101
1322
  return unlinkFile(filename, err => {
1102
1323
  const prettyFilename = filename.replace(`${input.cwd || process.cwd()}/`, '');
1103
1324
  if (err) {
1104
- debugLog();
1325
+ debugLog(`Cannot remove stale file: ${prettyFilename}\n${err}`);
1105
1326
  }
1106
1327
  else {
1107
- debugLog();
1328
+ debugLog(`Removed stale file: ${prettyFilename}`);
1108
1329
  }
1109
1330
  });
1110
1331
  }
@@ -1171,7 +1392,7 @@ function shouldOverwrite(config, outputPath) {
1171
1392
  const globalValue = config.overwrite === undefined ? true : !!config.overwrite;
1172
1393
  const outputConfig = config.generates[outputPath];
1173
1394
  if (!outputConfig) {
1174
- debugLog();
1395
+ debugLog(`Couldn't find a config of ${outputPath}`);
1175
1396
  return globalValue;
1176
1397
  }
1177
1398
  if (isConfiguredOutput(outputConfig) && typeof outputConfig.overwrite === 'boolean') {
@@ -1661,24 +1882,6 @@ async function ensureGraphQlPackage() {
1661
1882
  }
1662
1883
  }
1663
1884
 
1664
- function cliError(err, exitOnError = true) {
1665
- let msg;
1666
- if (err instanceof Error) {
1667
- msg = err.message || err.toString();
1668
- }
1669
- else if (typeof err === 'string') {
1670
- msg = err;
1671
- }
1672
- else {
1673
- msg = JSON.stringify(err);
1674
- }
1675
- // eslint-disable-next-line no-console
1676
- console.error(msg);
1677
- if (exitOnError) {
1678
- process.exit(1);
1679
- }
1680
- }
1681
-
1682
1885
  const [, , cmd] = process.argv;
1683
1886
  runCli(cmd)
1684
1887
  .then(() => {