@graphql-codegen/cli 2.6.3 → 2.6.5-alpha-acacb9e7a.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/index.js CHANGED
@@ -26,16 +26,10 @@ function _interopNamespace(e) {
26
26
  const pluginHelpers = require('@graphql-codegen/plugin-helpers');
27
27
  const core = require('@graphql-codegen/core');
28
28
  const utils = require('@graphql-tools/utils');
29
- const chalk = _interopDefault(require('chalk'));
30
- const logSymbols = _interopDefault(require('log-symbols'));
31
- const ansiEscapes = _interopDefault(require('ansi-escapes'));
32
- const wrapAnsi = _interopDefault(require('wrap-ansi'));
33
- const commonTags = require('common-tags');
34
- const tsLog = require('ts-log');
35
- const UpdateRenderer = _interopDefault(require('listr-update-renderer'));
36
29
  const graphql = require('graphql');
37
30
  const path = require('path');
38
31
  const path__default = _interopDefault(path);
32
+ const tsLog = require('ts-log');
39
33
  const cosmiconfig = require('cosmiconfig');
40
34
  const stringEnvInterpolation = require('string-env-interpolation');
41
35
  const yargs = _interopDefault(require('yargs'));
@@ -55,202 +49,16 @@ const fs = require('fs');
55
49
  const fs__default = _interopDefault(fs);
56
50
  const crypto = require('crypto');
57
51
  const os = require('os');
58
- const Listr = _interopDefault(require('listr'));
52
+ const listr2 = require('listr2');
59
53
  const child_process = require('child_process');
60
54
  const isGlob = _interopDefault(require('is-glob'));
61
55
  const debounce = _interopDefault(require('debounce'));
56
+ const logSymbols = _interopDefault(require('log-symbols'));
62
57
  const mkdirp = _interopDefault(require('mkdirp'));
63
58
  const inquirer = _interopDefault(require('inquirer'));
59
+ const chalk = _interopDefault(require('chalk'));
64
60
  const detectIndent = _interopDefault(require('detect-indent'));
65
-
66
- /**
67
- Indent each line in a string.
68
- @param string - The string to indent.
69
- @param count - How many times you want `options.indent` repeated. Default: `1`.
70
- @example
71
- ```
72
- import indentString from 'indent-string';
73
- indentString('Unicorns\nRainbows', 4);
74
- //=> ' Unicorns\n Rainbows'
75
- indentString('Unicorns\nRainbows', 4, {indent: '♥'});
76
- //=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
77
- ```
78
- */
79
- function indentString(string, count = 1, options = {}) {
80
- const { indent = ' ', includeEmptyLines = false } = options;
81
- if (typeof string !== 'string') {
82
- throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);
83
- }
84
- if (typeof count !== 'number') {
85
- throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);
86
- }
87
- if (count < 0) {
88
- throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``);
89
- }
90
- if (typeof indent !== 'string') {
91
- throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
92
- }
93
- if (count === 0) {
94
- return string;
95
- }
96
- const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
97
- return string.replace(regex, indent.repeat(count));
98
- }
99
-
100
- let logger;
101
- function getLogger() {
102
- return logger || tsLog.dummyLogger;
103
- }
104
- useWinstonLogger();
105
- function useWinstonLogger() {
106
- if (logger && logger.levels) {
107
- return;
108
- }
109
- logger = console;
110
- }
111
-
112
- let queue = [];
113
- function debugLog(message, ...meta) {
114
- if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) {
115
- queue.push({
116
- message,
117
- meta,
118
- });
119
- }
120
- }
121
- function printLogs() {
122
- if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) {
123
- queue.forEach(log => {
124
- getLogger().info(log.message, ...log.meta);
125
- });
126
- resetLogs();
127
- }
128
- }
129
- function resetLogs() {
130
- queue = [];
131
- }
132
-
133
- class Renderer {
134
- constructor(tasks, options) {
135
- this.updateRenderer = new UpdateRenderer(tasks, options);
136
- }
137
- render() {
138
- return this.updateRenderer.render();
139
- }
140
- end(err) {
141
- this.updateRenderer.end(err);
142
- if (typeof err === 'undefined') {
143
- logUpdate.clear();
144
- return;
145
- }
146
- // persist the output
147
- logUpdate.done();
148
- // show errors
149
- if (err) {
150
- const errorCount = err.errors ? err.errors.length : 0;
151
- if (errorCount > 0) {
152
- const count = indentString(chalk.red.bold(`Found ${errorCount} error${errorCount > 1 ? 's' : ''}`), 1);
153
- const details = err.errors
154
- .map(error => {
155
- debugLog(`[CLI] Exited with an error`, error);
156
- return { msg: pluginHelpers.isDetailedError(error) ? error.details : null, rawError: error };
157
- })
158
- .map(({ msg, rawError }, i) => {
159
- const source = err.errors[i].source;
160
- msg = msg ? chalk.gray(indentString(commonTags.stripIndent(`${msg}`), 4)) : null;
161
- const stack = rawError.stack ? chalk.gray(indentString(commonTags.stripIndent(rawError.stack), 4)) : null;
162
- if (source) {
163
- const sourceOfError = typeof source === 'string' ? source : source.name;
164
- const title = indentString(`${logSymbols.error} ${sourceOfError}`, 2);
165
- return [title, msg, stack, stack].filter(Boolean).join('\n');
166
- }
167
- return [msg, stack].filter(Boolean).join('\n');
168
- })
169
- .join('\n\n');
170
- logUpdate.emit(['', count, details, ''].join('\n\n'));
171
- }
172
- else {
173
- const details = err.details ? err.details : '';
174
- logUpdate.emit(`${chalk.red.bold(`${indentString(err.message, 2)}`)}\n${details}\n${chalk.grey(err.stack)}`);
175
- }
176
- }
177
- logUpdate.done();
178
- printLogs();
179
- }
180
- }
181
- const render = tasks => {
182
- for (const task of tasks) {
183
- task.subscribe(event => {
184
- if (event.type === 'SUBTASKS') {
185
- render(task.subtasks);
186
- return;
187
- }
188
- if (event.type === 'DATA') {
189
- logUpdate.emit(chalk.dim(`${event.data}`));
190
- }
191
- logUpdate.done();
192
- }, err => {
193
- logUpdate.emit(err);
194
- logUpdate.done();
195
- });
196
- }
197
- };
198
- class ErrorRenderer {
199
- constructor(tasks, _options) {
200
- this.tasks = tasks;
201
- }
202
- render() {
203
- render(this.tasks);
204
- }
205
- static get nonTTY() {
206
- return true;
207
- }
208
- end() { }
209
- }
210
- class LogUpdate {
211
- constructor() {
212
- this.stream = process.stdout;
213
- // state
214
- this.previousLineCount = 0;
215
- this.previousOutput = '';
216
- this.previousWidth = this.getWidth();
217
- }
218
- emit(...args) {
219
- let output = args.join(' ') + '\n';
220
- const width = this.getWidth();
221
- if (output === this.previousOutput && this.previousWidth === width) {
222
- return;
223
- }
224
- this.previousOutput = output;
225
- this.previousWidth = width;
226
- output = wrapAnsi(output, width, {
227
- trim: false,
228
- hard: true,
229
- wordWrap: false,
230
- });
231
- this.stream.write(ansiEscapes.eraseLines(this.previousLineCount) + output);
232
- this.previousLineCount = output.split('\n').length;
233
- }
234
- clear() {
235
- this.stream.write(ansiEscapes.eraseLines(this.previousLineCount));
236
- this.previousOutput = '';
237
- this.previousWidth = this.getWidth();
238
- this.previousLineCount = 0;
239
- }
240
- done() {
241
- this.previousOutput = '';
242
- this.previousWidth = this.getWidth();
243
- this.previousLineCount = 0;
244
- }
245
- getWidth() {
246
- const { columns } = this.stream;
247
- if (!columns) {
248
- return 80;
249
- }
250
- return columns;
251
- }
252
- }
253
- const logUpdate = new LogUpdate();
61
+ const getLatestVersion = _interopDefault(require('latest-version'));
254
62
 
255
63
  async function getPluginByName(name, pluginLoader) {
256
64
  const possibleNames = [
@@ -333,6 +141,22 @@ async function getPresetByName(name, loader) {
333
141
  `);
334
142
  }
335
143
 
144
+ let logger;
145
+ function getLogger() {
146
+ return logger || tsLog.dummyLogger;
147
+ }
148
+ useWinstonLogger();
149
+ function useWinstonLogger() {
150
+ if (logger && logger.levels) {
151
+ return;
152
+ }
153
+ logger = console;
154
+ }
155
+
156
+ function debugLog(message, ...meta) {
157
+ if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) ;
158
+ }
159
+
336
160
  const CodegenExtension = (api) => {
337
161
  // Schema
338
162
  api.loaders.schema.register(new codeFileLoader.CodeFileLoader({
@@ -749,33 +573,6 @@ function addHashToDocumentFiles(documentFilesPromise) {
749
573
  }));
750
574
  }
751
575
 
752
- const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
753
- const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
754
-
755
- function isListrError(err) {
756
- return err.name === 'ListrError' && Array.isArray(err.errors) && err.errors.length > 0;
757
- }
758
- function cliError(err, exitOnError = true) {
759
- let msg;
760
- if (err instanceof Error) {
761
- msg = err.message || err.toString();
762
- }
763
- else if (typeof err === 'string') {
764
- msg = err;
765
- }
766
- else {
767
- msg = JSON.stringify(err);
768
- }
769
- // eslint-disable-next-line no-console
770
- console.error(msg);
771
- if (exitOnError && isNode) {
772
- process.exit(1);
773
- }
774
- else if (exitOnError && isBrowser) {
775
- throw err;
776
- }
777
- }
778
-
779
576
  const makeDefaultLoader = (from) => {
780
577
  if (fs__default.statSync(from).isDirectory()) {
781
578
  from = path__default.join(from, '__fake.js');
@@ -803,39 +600,12 @@ async function executeCodegen(input) {
803
600
  const config = context.getConfig();
804
601
  const pluginContext = context.getPluginContext();
805
602
  const result = [];
806
- const commonListrOptions = {
807
- exitOnError: true,
808
- };
809
- let listr;
810
- if (process.env.VERBOSE) {
811
- listr = new Listr({
812
- ...commonListrOptions,
813
- renderer: 'verbose',
814
- nonTTYRenderer: 'verbose',
815
- });
816
- }
817
- else if (process.env.NODE_ENV === 'test') {
818
- listr = new Listr({
819
- ...commonListrOptions,
820
- renderer: 'silent',
821
- nonTTYRenderer: 'silent',
822
- });
823
- }
824
- else {
825
- listr = new Listr({
826
- ...commonListrOptions,
827
- renderer: config.silent ? 'silent' : config.errorsOnly ? ErrorRenderer : Renderer,
828
- nonTTYRenderer: config.silent ? 'silent' : 'default',
829
- collapse: true,
830
- clearOutput: false,
831
- });
832
- }
833
603
  let rootConfig = {};
834
604
  let rootSchemas;
835
605
  let rootDocuments;
836
606
  const generates = {};
837
607
  const cache = createCache();
838
- function wrapTask(task, source, taskName) {
608
+ function wrapTask(task, source, taskName, ctx) {
839
609
  return () => {
840
610
  return context.profiler.run(async () => {
841
611
  try {
@@ -845,6 +615,7 @@ async function executeCodegen(input) {
845
615
  if (source && !(error instanceof graphql.GraphQLError)) {
846
616
  error.source = source;
847
617
  }
618
+ ctx.errors.push(error);
848
619
  throw error;
849
620
  }
850
621
  }, taskName);
@@ -915,119 +686,109 @@ async function executeCodegen(input) {
915
686
  `);
916
687
  }
917
688
  }
918
- listr.add({
919
- title: 'Parse configuration',
920
- task: () => normalize(),
921
- });
922
- listr.add({
923
- title: 'Generate outputs',
924
- task: () => {
925
- return new Listr(Object.keys(generates).map(filename => {
926
- const outputConfig = generates[filename];
927
- const hasPreset = !!outputConfig.preset;
928
- return {
929
- title: hasPreset
689
+ const isTest = process.env.NODE_ENV === 'test';
690
+ const tasks = new listr2.Listr([
691
+ {
692
+ title: 'Parse Configuration',
693
+ task: () => normalize(),
694
+ },
695
+ {
696
+ title: 'Generate outputs',
697
+ task: (ctx, task) => {
698
+ const generateTasks = Object.keys(generates).map(filename => {
699
+ const outputConfig = generates[filename];
700
+ const hasPreset = !!outputConfig.preset;
701
+ const title = hasPreset
930
702
  ? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
931
- : `Generate ${filename}`,
932
- task: () => {
933
- let outputSchemaAst;
934
- let outputSchema;
935
- const outputFileTemplateConfig = outputConfig.config || {};
936
- const outputDocuments = [];
937
- const outputSpecificSchemas = pluginHelpers.normalizeInstanceOrArray(outputConfig.schema);
938
- const outputSpecificDocuments = pluginHelpers.normalizeInstanceOrArray(outputConfig.documents);
939
- return new Listr([
940
- {
941
- title: 'Load GraphQL schemas',
942
- task: wrapTask(async () => {
943
- debugLog(`[CLI] Loading Schemas`);
944
- const schemaPointerMap = {};
945
- const allSchemaUnnormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
946
- for (const unnormalizedPtr of allSchemaUnnormalizedPointers) {
947
- if (typeof unnormalizedPtr === 'string') {
948
- schemaPointerMap[unnormalizedPtr] = {};
703
+ : `Generate ${filename}`;
704
+ return {
705
+ title,
706
+ task: (_, subTask) => {
707
+ let outputSchemaAst;
708
+ let outputSchema;
709
+ const outputFileTemplateConfig = outputConfig.config || {};
710
+ let outputDocuments = [];
711
+ const outputSpecificSchemas = pluginHelpers.normalizeInstanceOrArray(outputConfig.schema);
712
+ const outputSpecificDocuments = pluginHelpers.normalizeInstanceOrArray(outputConfig.documents);
713
+ return subTask.newListr([
714
+ {
715
+ title: 'Load GraphQL schemas',
716
+ task: wrapTask(async () => {
717
+ debugLog(`[CLI] Loading Schemas`);
718
+ const schemaPointerMap = {};
719
+ const allSchemaDenormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
720
+ for (const denormalizedPtr of allSchemaDenormalizedPointers) {
721
+ if (typeof denormalizedPtr === 'string') {
722
+ schemaPointerMap[denormalizedPtr] = {};
723
+ }
724
+ else if (typeof denormalizedPtr === 'object') {
725
+ Object.assign(schemaPointerMap, denormalizedPtr);
726
+ }
949
727
  }
950
- else if (typeof unnormalizedPtr === 'object') {
951
- Object.assign(schemaPointerMap, unnormalizedPtr);
728
+ const hash = JSON.stringify(schemaPointerMap);
729
+ const result = await cache('schema', hash, async () => {
730
+ const outputSchemaAst = await context.loadSchema(schemaPointerMap);
731
+ const outputSchema = pluginHelpers.getCachedDocumentNodeFromSchema(outputSchemaAst);
732
+ return {
733
+ outputSchemaAst,
734
+ outputSchema,
735
+ };
736
+ });
737
+ outputSchemaAst = result.outputSchemaAst;
738
+ outputSchema = result.outputSchema;
739
+ }, filename, `Load GraphQL schemas: ${filename}`, ctx),
740
+ },
741
+ {
742
+ title: 'Load GraphQL documents',
743
+ task: wrapTask(async () => {
744
+ debugLog(`[CLI] Loading Documents`);
745
+ const documentPointerMap = {};
746
+ const allDocumentsDenormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
747
+ for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
748
+ if (typeof denormalizedPtr === 'string') {
749
+ documentPointerMap[denormalizedPtr] = {};
750
+ }
751
+ else if (typeof denormalizedPtr === 'object') {
752
+ Object.assign(documentPointerMap, denormalizedPtr);
753
+ }
952
754
  }
953
- }
954
- const hash = JSON.stringify(schemaPointerMap);
955
- const result = await cache('schema', hash, async () => {
956
- const outputSchemaAst = await context.loadSchema(schemaPointerMap);
957
- const outputSchema = pluginHelpers.getCachedDocumentNodeFromSchema(outputSchemaAst);
958
- return {
959
- outputSchemaAst,
960
- outputSchema,
961
- };
962
- });
963
- outputSchemaAst = await result.outputSchemaAst;
964
- outputSchema = result.outputSchema;
965
- }, filename, `Load GraphQL schemas: ${filename}`),
966
- },
967
- {
968
- title: 'Load GraphQL documents',
969
- task: wrapTask(async () => {
970
- debugLog(`[CLI] Loading Documents`);
971
- // get different cache for shared docs and output specific docs
972
- const results = await Promise.all([rootDocuments, outputSpecificDocuments].map(docs => {
973
- const hash = JSON.stringify(docs);
974
- return cache('documents', hash, async () => {
975
- const documents = await context.loadDocuments(docs);
755
+ const hash = JSON.stringify(documentPointerMap);
756
+ const result = await cache('documents', hash, async () => {
757
+ const documents = await context.loadDocuments(documentPointerMap);
976
758
  return {
977
759
  documents,
978
760
  };
979
761
  });
980
- }));
981
- const documents = [];
982
- results.forEach(source => documents.push(...source.documents));
983
- if (documents.length > 0) {
984
- outputDocuments.push(...documents);
985
- }
986
- }, filename, `Load GraphQL documents: ${filename}`),
987
- },
988
- {
989
- title: 'Generate',
990
- task: wrapTask(async () => {
991
- debugLog(`[CLI] Generating output`);
992
- const normalizedPluginsArray = pluginHelpers.normalizeConfig(outputConfig.plugins);
993
- const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
994
- const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader)));
995
- const pluginMap = {};
996
- const preset = hasPreset
997
- ? typeof outputConfig.preset === 'string'
998
- ? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
999
- : outputConfig.preset
1000
- : null;
1001
- pluginPackages.forEach((pluginPackage, i) => {
1002
- const plugin = normalizedPluginsArray[i];
1003
- const name = Object.keys(plugin)[0];
1004
- pluginMap[name] = pluginPackage;
1005
- });
1006
- const mergedConfig = {
1007
- ...rootConfig,
1008
- ...(typeof outputFileTemplateConfig === 'string'
1009
- ? { value: outputFileTemplateConfig }
1010
- : outputFileTemplateConfig),
1011
- };
1012
- let outputs = [];
1013
- if (hasPreset) {
1014
- outputs = await context.profiler.run(async () => preset.buildGeneratesSection({
1015
- baseOutputDir: filename,
1016
- presetConfig: outputConfig.presetConfig || {},
1017
- plugins: normalizedPluginsArray,
1018
- schema: outputSchema,
1019
- schemaAst: outputSchemaAst,
1020
- documents: outputDocuments,
1021
- config: mergedConfig,
1022
- pluginMap,
1023
- pluginContext,
1024
- profiler: context.profiler,
1025
- }), `Build Generates Section: ${filename}`);
1026
- }
1027
- else {
1028
- outputs = [
1029
- {
1030
- filename,
762
+ outputDocuments = result.documents;
763
+ }, filename, `Load GraphQL documents: ${filename}`, ctx),
764
+ },
765
+ {
766
+ title: 'Generate',
767
+ task: wrapTask(async () => {
768
+ debugLog(`[CLI] Generating output`);
769
+ const normalizedPluginsArray = pluginHelpers.normalizeConfig(outputConfig.plugins);
770
+ const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
771
+ const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader)));
772
+ const preset = hasPreset
773
+ ? typeof outputConfig.preset === 'string'
774
+ ? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
775
+ : outputConfig.preset
776
+ : null;
777
+ const pluginMap = Object.fromEntries(pluginPackages.map((pkg, i) => {
778
+ const plugin = normalizedPluginsArray[i];
779
+ const name = Object.keys(plugin)[0];
780
+ return [name, pkg];
781
+ }));
782
+ const mergedConfig = {
783
+ ...rootConfig,
784
+ ...(typeof outputFileTemplateConfig === 'string'
785
+ ? { value: outputFileTemplateConfig }
786
+ : outputFileTemplateConfig),
787
+ };
788
+ const outputs = hasPreset
789
+ ? await context.profiler.run(async () => preset.buildGeneratesSection({
790
+ baseOutputDir: filename,
791
+ presetConfig: outputConfig.presetConfig || {},
1031
792
  plugins: normalizedPluginsArray,
1032
793
  schema: outputSchema,
1033
794
  schemaAst: outputSchemaAst,
@@ -1036,50 +797,67 @@ async function executeCodegen(input) {
1036
797
  pluginMap,
1037
798
  pluginContext,
1038
799
  profiler: context.profiler,
1039
- },
1040
- ];
1041
- }
1042
- const process = async (outputArgs) => {
1043
- const output = await core.codegen({
1044
- ...outputArgs,
1045
- cache,
1046
- });
1047
- result.push({
1048
- filename: outputArgs.filename,
1049
- content: output,
1050
- hooks: outputConfig.hooks || {},
1051
- });
1052
- };
1053
- await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
1054
- }, filename, `Generate: ${filename}`),
1055
- },
1056
- ], {
1057
- // it stops when one of tasks failed
1058
- exitOnError: true,
1059
- });
1060
- },
1061
- };
1062
- }), {
1063
- // it doesn't stop when one of tasks failed, to finish at least some of outputs
1064
- exitOnError: false,
1065
- concurrent: os.cpus().length,
1066
- });
800
+ }), `Build Generates Section: ${filename}`)
801
+ : [
802
+ {
803
+ filename,
804
+ plugins: normalizedPluginsArray,
805
+ schema: outputSchema,
806
+ schemaAst: outputSchemaAst,
807
+ documents: outputDocuments,
808
+ config: mergedConfig,
809
+ pluginMap,
810
+ pluginContext,
811
+ profiler: context.profiler,
812
+ },
813
+ ];
814
+ const process = async (outputArgs) => {
815
+ const output = await core.codegen({
816
+ ...outputArgs,
817
+ cache,
818
+ });
819
+ result.push({
820
+ filename: outputArgs.filename,
821
+ content: output,
822
+ hooks: outputConfig.hooks || {},
823
+ });
824
+ };
825
+ await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
826
+ }, filename, `Generate: ${filename}`, ctx),
827
+ },
828
+ ], {
829
+ // it stops when of the tasks failed
830
+ exitOnError: true,
831
+ });
832
+ },
833
+ // It doesn't stop when one of tasks failed, to finish at least some of outputs
834
+ exitOnError: false,
835
+ concurrent: os.cpus().length,
836
+ };
837
+ });
838
+ return task.newListr(generateTasks);
839
+ },
1067
840
  },
841
+ ], {
842
+ rendererOptions: {
843
+ clearOutput: false,
844
+ collapse: true,
845
+ },
846
+ ctx: { errors: [] },
847
+ rendererSilent: isTest || config.silent,
848
+ exitOnError: true,
1068
849
  });
1069
- try {
1070
- await listr.run();
1071
- }
1072
- catch (err) {
1073
- if (isListrError(err)) {
1074
- const allErrs = err.errors.map(subErr => pluginHelpers.isDetailedError(subErr)
1075
- ? `${subErr.message} for "${subErr.source}"${subErr.details}`
1076
- : subErr.message || subErr.toString());
1077
- const newErr = new utils.AggregateError(err.errors, `${err.message} ${allErrs.join('\n\n')}`);
1078
- // Best-effort to all stack traces for debugging
1079
- newErr.stack = `${newErr.stack}\n\n${err.errors.map(subErr => subErr.stack).join('\n\n')}`;
1080
- throw newErr;
1081
- }
1082
- throw err;
850
+ // All the errors throw in `listr2` are collected in context
851
+ // Running tasks doesn't throw anything
852
+ const executedContext = await tasks.run();
853
+ if (executedContext.errors.length > 0) {
854
+ const errors = executedContext.errors.map(subErr => pluginHelpers.isDetailedError(subErr)
855
+ ? `${subErr.message} for "${subErr.source}"${subErr.details}`
856
+ : subErr.message || subErr.toString());
857
+ const newErr = new utils.AggregateError(executedContext.errors, `${errors.join('\n\n')}`);
858
+ // Best-effort to all stack traces for debugging
859
+ newErr.stack = `${newErr.stack}\n\n${executedContext.errors.map(subErr => subErr.stack).join('\n\n')}`;
860
+ throw newErr;
1083
861
  }
1084
862
  return result;
1085
863
  }
@@ -1139,7 +917,7 @@ function execShellCommand(cmd) {
1139
917
  });
1140
918
  }
1141
919
  async function executeHooks(hookName, scripts = [], args = []) {
1142
- debugLog(`Running lifecycle hook "${hookName}" scripts...`);
920
+ debugLog();
1143
921
  for (const script of scripts) {
1144
922
  if (typeof script === 'string') {
1145
923
  debugLog(`Running lifecycle hook "${hookName}" script: ${script} with args: ${args.join(' ')}...`);
@@ -1173,7 +951,7 @@ function emitWatching() {
1173
951
  log(`${logSymbols.info} Watching for changes...`);
1174
952
  }
1175
953
  const createWatcher = (initalContext, onNext) => {
1176
- debugLog(`[Watcher] Starting watcher...`);
954
+ debugLog();
1177
955
  let config = initalContext.getConfig();
1178
956
  const files = [initalContext.filepath].filter(a => a);
1179
957
  const documents = pluginHelpers.normalizeInstanceOrArray(config.documents);
@@ -1244,10 +1022,10 @@ const createWatcher = (initalContext, onNext) => {
1244
1022
  atomic: true,
1245
1023
  ignored,
1246
1024
  });
1247
- debugLog(`[Watcher] Started`);
1025
+ debugLog();
1248
1026
  const shutdown = () => {
1249
1027
  isShutdown = true;
1250
- debugLog(`[Watcher] Shutting down`);
1028
+ debugLog();
1251
1029
  log(`Shutting down watch...`);
1252
1030
  watcher.close();
1253
1031
  lifecycleHooks(config.hooks).beforeDone();
@@ -1255,7 +1033,7 @@ const createWatcher = (initalContext, onNext) => {
1255
1033
  // it doesn't matter what has changed, need to run whole process anyway
1256
1034
  watcher.on('all', async (eventName, path$1) => {
1257
1035
  lifecycleHooks(config.hooks).onWatchTriggered(eventName, path$1);
1258
- debugLog(`[Watcher] triggered due to a file ${eventName} event: ${path$1}`);
1036
+ debugLog();
1259
1037
  const fullPath = path.join(process.cwd(), path$1);
1260
1038
  // In ESM require is not defined
1261
1039
  try {
@@ -1324,10 +1102,10 @@ async function generate(input, saveToFile = true) {
1324
1102
  return unlinkFile(filename, err => {
1325
1103
  const prettyFilename = filename.replace(`${input.cwd || process.cwd()}/`, '');
1326
1104
  if (err) {
1327
- debugLog(`Cannot remove stale file: ${prettyFilename}\n${err}`);
1105
+ debugLog();
1328
1106
  }
1329
1107
  else {
1330
- debugLog(`Removed stale file: ${prettyFilename}`);
1108
+ debugLog();
1331
1109
  }
1332
1110
  });
1333
1111
  }
@@ -1394,7 +1172,7 @@ function shouldOverwrite(config, outputPath) {
1394
1172
  const globalValue = config.overwrite === undefined ? true : !!config.overwrite;
1395
1173
  const outputConfig = config.generates[outputPath];
1396
1174
  if (!outputConfig) {
1397
- debugLog(`Couldn't find a config of ${outputPath}`);
1175
+ debugLog();
1398
1176
  return globalValue;
1399
1177
  }
1400
1178
  if (isConfiguredOutput(outputConfig) && typeof outputConfig.overwrite === 'boolean') {
@@ -1423,8 +1201,6 @@ async function writeConfig(answers, config) {
1423
1201
  }
1424
1202
  // Updates package.json (script and plugins as dependencies)
1425
1203
  async function writePackage(answers, configLocation) {
1426
- // dynamic import because latest-version is pure ESM
1427
- const getLatestVersion = (await new Promise(function (resolve) { resolve(_interopNamespace(require('latest-version'))); })).default;
1428
1204
  // script
1429
1205
  const pkgPath = path.resolve(process.cwd(), 'package.json');
1430
1206
  const pkgContent = fs.readFileSync(pkgPath, {
@@ -1857,6 +1633,27 @@ function addIntrospection(config) {
1857
1633
  };
1858
1634
  }
1859
1635
 
1636
+ function isListrError(err) {
1637
+ return err.name === 'ListrError' && Array.isArray(err.errors) && err.errors.length > 0;
1638
+ }
1639
+ function cliError(err, exitOnError = true) {
1640
+ let msg;
1641
+ if (err instanceof Error) {
1642
+ msg = err.message || err.toString();
1643
+ }
1644
+ else if (typeof err === 'string') {
1645
+ msg = err;
1646
+ }
1647
+ else {
1648
+ msg = JSON.stringify(err);
1649
+ }
1650
+ // eslint-disable-next-line no-console
1651
+ console.error(msg);
1652
+ if (exitOnError) {
1653
+ process.exit(1);
1654
+ }
1655
+ }
1656
+
1860
1657
  async function runCli(cmd) {
1861
1658
  await ensureGraphQlPackage();
1862
1659
  switch (cmd) {