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