@graphql-codegen/cli 2.7.0 → 2.8.0-alpha-c108f8a9c.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.
Files changed (79) hide show
  1. package/cjs/bin.js +13 -0
  2. package/cjs/cli.js +60 -0
  3. package/cjs/codegen.js +332 -0
  4. package/cjs/config.js +303 -0
  5. package/cjs/generate-and-save.js +110 -0
  6. package/cjs/graphql-config.js +69 -0
  7. package/cjs/hooks.js +87 -0
  8. package/cjs/index.js +13 -0
  9. package/cjs/init/helpers.js +64 -0
  10. package/cjs/init/index.js +60 -0
  11. package/cjs/init/plugins.js +163 -0
  12. package/cjs/init/questions.js +147 -0
  13. package/cjs/init/targets.js +44 -0
  14. package/cjs/init/types.js +14 -0
  15. package/cjs/load.js +93 -0
  16. package/cjs/package.json +1 -0
  17. package/cjs/plugins.js +45 -0
  18. package/cjs/presets.js +46 -0
  19. package/cjs/utils/cli-error.js +25 -0
  20. package/cjs/utils/debugging.js +27 -0
  21. package/cjs/utils/file-system.js +26 -0
  22. package/cjs/utils/indentString.js +37 -0
  23. package/cjs/utils/listr-renderer.js +136 -0
  24. package/cjs/utils/logger.js +25 -0
  25. package/cjs/utils/watcher.js +140 -0
  26. package/esm/bin.js +11 -0
  27. package/esm/cli.js +32 -0
  28. package/esm/codegen.js +327 -0
  29. package/esm/config.js +290 -0
  30. package/esm/generate-and-save.js +105 -0
  31. package/esm/graphql-config.js +64 -0
  32. package/esm/hooks.js +83 -0
  33. package/esm/index.js +7 -0
  34. package/esm/init/helpers.js +55 -0
  35. package/esm/init/index.js +55 -0
  36. package/esm/init/plugins.js +160 -0
  37. package/esm/init/questions.js +140 -0
  38. package/esm/init/targets.js +40 -0
  39. package/esm/init/types.js +11 -0
  40. package/esm/load.js +88 -0
  41. package/esm/plugins.js +41 -0
  42. package/esm/presets.js +42 -0
  43. package/esm/utils/cli-error.js +20 -0
  44. package/esm/utils/debugging.js +21 -0
  45. package/esm/utils/file-system.js +19 -0
  46. package/esm/utils/indentString.js +33 -0
  47. package/esm/utils/listr-renderer.js +130 -0
  48. package/esm/utils/logger.js +18 -0
  49. package/esm/utils/watcher.js +135 -0
  50. package/package.json +31 -23
  51. package/typings/bin.d.ts +2 -0
  52. package/{cli.d.ts → typings/cli.d.ts} +0 -0
  53. package/{codegen.d.ts → typings/codegen.d.ts} +1 -1
  54. package/{config.d.ts → typings/config.d.ts} +0 -0
  55. package/{generate-and-save.d.ts → typings/generate-and-save.d.ts} +1 -1
  56. package/{graphql-config.d.ts → typings/graphql-config.d.ts} +0 -0
  57. package/{hooks.d.ts → typings/hooks.d.ts} +0 -0
  58. package/typings/index.d.ts +7 -0
  59. package/{init → typings/init}/helpers.d.ts +1 -1
  60. package/{init → typings/init}/index.d.ts +0 -0
  61. package/{init → typings/init}/plugins.d.ts +1 -1
  62. package/{init → typings/init}/questions.d.ts +1 -1
  63. package/{init → typings/init}/targets.d.ts +1 -1
  64. package/{init → typings/init}/types.d.ts +0 -0
  65. package/{load.d.ts → typings/load.d.ts} +0 -0
  66. package/{plugins.d.ts → typings/plugins.d.ts} +0 -0
  67. package/{presets.d.ts → typings/presets.d.ts} +0 -0
  68. package/{utils → typings/utils}/cli-error.d.ts +0 -0
  69. package/{utils → typings/utils}/debugging.d.ts +0 -0
  70. package/{utils → typings/utils}/file-system.d.ts +0 -0
  71. package/{utils → typings/utils}/indentString.d.ts +0 -0
  72. package/{utils → typings/utils}/listr-renderer.d.ts +0 -0
  73. package/{utils → typings/utils}/logger.d.ts +0 -0
  74. package/{utils → typings/utils}/watcher.d.ts +1 -1
  75. package/bin.d.ts +0 -1
  76. package/bin.js +0 -1891
  77. package/index.d.ts +0 -7
  78. package/index.js +0 -1902
  79. package/index.mjs +0 -1858
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.unlinkFile = exports.fileExists = exports.readFile = exports.writeFile = void 0;
4
+ const fs_1 = require("fs");
5
+ const { writeFile: fsWriteFile, readFile: fsReadFile, stat: fsStat } = fs_1.promises;
6
+ function writeFile(filepath, content) {
7
+ return fsWriteFile(filepath, content);
8
+ }
9
+ exports.writeFile = writeFile;
10
+ function readFile(filepath) {
11
+ return fsReadFile(filepath, 'utf-8');
12
+ }
13
+ exports.readFile = readFile;
14
+ async function fileExists(filePath) {
15
+ try {
16
+ return (await fsStat(filePath)).isFile();
17
+ }
18
+ catch (err) {
19
+ return false;
20
+ }
21
+ }
22
+ exports.fileExists = fileExists;
23
+ function unlinkFile(filePath, cb) {
24
+ (0, fs_1.unlink)(filePath, cb);
25
+ }
26
+ exports.unlinkFile = unlinkFile;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.indentString = void 0;
4
+ /**
5
+ Indent each line in a string.
6
+ @param string - The string to indent.
7
+ @param count - How many times you want `options.indent` repeated. Default: `1`.
8
+ @example
9
+ ```
10
+ import indentString from 'indent-string';
11
+ indentString('Unicorns\nRainbows', 4);
12
+ //=> ' Unicorns\n Rainbows'
13
+ indentString('Unicorns\nRainbows', 4, {indent: '♥'});
14
+ //=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
15
+ ```
16
+ */
17
+ function indentString(string, count = 1, options = {}) {
18
+ const { indent = ' ', includeEmptyLines = false } = options;
19
+ if (typeof string !== 'string') {
20
+ throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);
21
+ }
22
+ if (typeof count !== 'number') {
23
+ throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);
24
+ }
25
+ if (count < 0) {
26
+ throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``);
27
+ }
28
+ if (typeof indent !== 'string') {
29
+ throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
30
+ }
31
+ if (count === 0) {
32
+ return string;
33
+ }
34
+ const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
35
+ return string.replace(regex, indent.repeat(count));
36
+ }
37
+ exports.indentString = indentString;
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ErrorRenderer = exports.Renderer = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
6
+ const indentString_js_1 = require("./indentString.js");
7
+ const log_symbols_1 = tslib_1.__importDefault(require("log-symbols"));
8
+ const ansi_escapes_1 = tslib_1.__importDefault(require("ansi-escapes"));
9
+ const wrap_ansi_1 = tslib_1.__importDefault(require("wrap-ansi"));
10
+ const common_tags_1 = require("common-tags");
11
+ const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
12
+ const debugging_js_1 = require("./debugging.js");
13
+ const listr_update_renderer_1 = tslib_1.__importDefault(require("listr-update-renderer"));
14
+ class Renderer {
15
+ constructor(tasks, options) {
16
+ this.updateRenderer = new listr_update_renderer_1.default(tasks, options);
17
+ }
18
+ render() {
19
+ return this.updateRenderer.render();
20
+ }
21
+ end(err) {
22
+ this.updateRenderer.end(err);
23
+ if (typeof err === 'undefined') {
24
+ logUpdate.clear();
25
+ return;
26
+ }
27
+ // persist the output
28
+ logUpdate.done();
29
+ // show errors
30
+ if (err) {
31
+ const errorCount = err.errors ? err.errors.length : 0;
32
+ if (errorCount > 0) {
33
+ const count = (0, indentString_js_1.indentString)(chalk_1.default.red.bold(`Found ${errorCount} error${errorCount > 1 ? 's' : ''}`), 1);
34
+ const details = err.errors
35
+ .map(error => {
36
+ (0, debugging_js_1.debugLog)(`[CLI] Exited with an error`, error);
37
+ return { msg: (0, plugin_helpers_1.isDetailedError)(error) ? error.details : null, rawError: error };
38
+ })
39
+ .map(({ msg, rawError }, i) => {
40
+ const source = err.errors[i].source;
41
+ msg = msg ? chalk_1.default.gray((0, indentString_js_1.indentString)((0, common_tags_1.stripIndent)(`${msg}`), 4)) : null;
42
+ const stack = rawError.stack ? chalk_1.default.gray((0, indentString_js_1.indentString)((0, common_tags_1.stripIndent)(rawError.stack), 4)) : null;
43
+ if (source) {
44
+ const sourceOfError = typeof source === 'string' ? source : source.name;
45
+ const title = (0, indentString_js_1.indentString)(`${log_symbols_1.default.error} ${sourceOfError}`, 2);
46
+ return [title, msg, stack, stack].filter(Boolean).join('\n');
47
+ }
48
+ return [msg, stack].filter(Boolean).join('\n');
49
+ })
50
+ .join('\n\n');
51
+ logUpdate.emit(['', count, details, ''].join('\n\n'));
52
+ }
53
+ else {
54
+ const details = err.details ? err.details : '';
55
+ logUpdate.emit(`${chalk_1.default.red.bold(`${(0, indentString_js_1.indentString)(err.message, 2)}`)}\n${details}\n${chalk_1.default.grey(err.stack)}`);
56
+ }
57
+ }
58
+ logUpdate.done();
59
+ (0, debugging_js_1.printLogs)();
60
+ }
61
+ }
62
+ exports.Renderer = Renderer;
63
+ const render = tasks => {
64
+ for (const task of tasks) {
65
+ task.subscribe(event => {
66
+ if (event.type === 'SUBTASKS') {
67
+ render(task.subtasks);
68
+ return;
69
+ }
70
+ if (event.type === 'DATA') {
71
+ logUpdate.emit(chalk_1.default.dim(`${event.data}`));
72
+ }
73
+ logUpdate.done();
74
+ }, err => {
75
+ logUpdate.emit(err);
76
+ logUpdate.done();
77
+ });
78
+ }
79
+ };
80
+ class ErrorRenderer {
81
+ constructor(tasks, _options) {
82
+ this.tasks = tasks;
83
+ }
84
+ render() {
85
+ render(this.tasks);
86
+ }
87
+ static get nonTTY() {
88
+ return true;
89
+ }
90
+ end() { }
91
+ }
92
+ exports.ErrorRenderer = ErrorRenderer;
93
+ class LogUpdate {
94
+ constructor() {
95
+ this.stream = process.stdout;
96
+ // state
97
+ this.previousLineCount = 0;
98
+ this.previousOutput = '';
99
+ this.previousWidth = this.getWidth();
100
+ }
101
+ emit(...args) {
102
+ let output = args.join(' ') + '\n';
103
+ const width = this.getWidth();
104
+ if (output === this.previousOutput && this.previousWidth === width) {
105
+ return;
106
+ }
107
+ this.previousOutput = output;
108
+ this.previousWidth = width;
109
+ output = (0, wrap_ansi_1.default)(output, width, {
110
+ trim: false,
111
+ hard: true,
112
+ wordWrap: false,
113
+ });
114
+ this.stream.write(ansi_escapes_1.default.eraseLines(this.previousLineCount) + output);
115
+ this.previousLineCount = output.split('\n').length;
116
+ }
117
+ clear() {
118
+ this.stream.write(ansi_escapes_1.default.eraseLines(this.previousLineCount));
119
+ this.previousOutput = '';
120
+ this.previousWidth = this.getWidth();
121
+ this.previousLineCount = 0;
122
+ }
123
+ done() {
124
+ this.previousOutput = '';
125
+ this.previousWidth = this.getWidth();
126
+ this.previousLineCount = 0;
127
+ }
128
+ getWidth() {
129
+ const { columns } = this.stream;
130
+ if (!columns) {
131
+ return 80;
132
+ }
133
+ return columns;
134
+ }
135
+ }
136
+ const logUpdate = new LogUpdate();
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useWinstonLogger = exports.setSilentLogger = exports.setLogger = exports.getLogger = void 0;
4
+ const ts_log_1 = require("ts-log");
5
+ let logger;
6
+ function getLogger() {
7
+ return logger || ts_log_1.dummyLogger;
8
+ }
9
+ exports.getLogger = getLogger;
10
+ useWinstonLogger();
11
+ function setLogger(newLogger) {
12
+ logger = newLogger;
13
+ }
14
+ exports.setLogger = setLogger;
15
+ function setSilentLogger() {
16
+ logger = ts_log_1.dummyLogger;
17
+ }
18
+ exports.setSilentLogger = setSilentLogger;
19
+ function useWinstonLogger() {
20
+ if (logger && logger.levels) {
21
+ return;
22
+ }
23
+ logger = console;
24
+ }
25
+ exports.useWinstonLogger = useWinstonLogger;
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createWatcher = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const codegen_js_1 = require("../codegen.js");
6
+ const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
7
+ const is_glob_1 = tslib_1.__importDefault(require("is-glob"));
8
+ const debounce_1 = tslib_1.__importDefault(require("debounce"));
9
+ const log_symbols_1 = tslib_1.__importDefault(require("log-symbols"));
10
+ const debugging_js_1 = require("./debugging.js");
11
+ const logger_js_1 = require("./logger.js");
12
+ const path_1 = require("path");
13
+ const hooks_js_1 = require("../hooks.js");
14
+ const config_js_1 = require("../config.js");
15
+ const utils_1 = require("@graphql-tools/utils");
16
+ function log(msg) {
17
+ // double spaces to inline the message with Listr
18
+ (0, logger_js_1.getLogger)().info(` ${msg}`);
19
+ }
20
+ function emitWatching() {
21
+ log(`${log_symbols_1.default.info} Watching for changes...`);
22
+ }
23
+ const createWatcher = (initalContext, onNext) => {
24
+ (0, debugging_js_1.debugLog)(`[Watcher] Starting watcher...`);
25
+ let config = initalContext.getConfig();
26
+ const files = [initalContext.filepath].filter(a => a);
27
+ const documents = (0, plugin_helpers_1.normalizeInstanceOrArray)(config.documents);
28
+ const schemas = (0, plugin_helpers_1.normalizeInstanceOrArray)(config.schema);
29
+ // Add schemas and documents from "generates"
30
+ Object.keys(config.generates)
31
+ .map(filename => (0, plugin_helpers_1.normalizeOutputParam)(config.generates[filename]))
32
+ .forEach(conf => {
33
+ schemas.push(...(0, plugin_helpers_1.normalizeInstanceOrArray)(conf.schema));
34
+ documents.push(...(0, plugin_helpers_1.normalizeInstanceOrArray)(conf.documents));
35
+ });
36
+ if (documents) {
37
+ documents.forEach(doc => {
38
+ if (typeof doc === 'string') {
39
+ files.push(doc);
40
+ }
41
+ else {
42
+ files.push(...Object.keys(doc));
43
+ }
44
+ });
45
+ }
46
+ schemas.forEach((schema) => {
47
+ if ((0, is_glob_1.default)(schema) || (0, utils_1.isValidPath)(schema)) {
48
+ files.push(schema);
49
+ }
50
+ });
51
+ if (typeof config.watch !== 'boolean') {
52
+ files.push(...(0, plugin_helpers_1.normalizeInstanceOrArray)(config.watch));
53
+ }
54
+ let watcher;
55
+ const runWatcher = async () => {
56
+ var _a, _b;
57
+ const chokidar = await Promise.resolve().then(() => tslib_1.__importStar(require('chokidar')));
58
+ let isShutdown = false;
59
+ const debouncedExec = (0, debounce_1.default)(() => {
60
+ if (!isShutdown) {
61
+ (0, codegen_js_1.executeCodegen)(initalContext)
62
+ .then(onNext, () => Promise.resolve())
63
+ .then(() => emitWatching());
64
+ }
65
+ }, 100);
66
+ emitWatching();
67
+ const ignored = [];
68
+ Object.keys(config.generates)
69
+ .map(filename => ({ filename, config: (0, plugin_helpers_1.normalizeOutputParam)(config.generates[filename]) }))
70
+ .forEach(entry => {
71
+ if (entry.config.preset) {
72
+ const extension = entry.config.presetConfig && entry.config.presetConfig.extension;
73
+ if (extension) {
74
+ ignored.push((0, path_1.join)(entry.filename, '**', '*' + extension));
75
+ }
76
+ }
77
+ else {
78
+ ignored.push(entry.filename);
79
+ }
80
+ });
81
+ watcher = chokidar.watch(files, {
82
+ persistent: true,
83
+ ignoreInitial: true,
84
+ followSymlinks: true,
85
+ cwd: process.cwd(),
86
+ disableGlobbing: false,
87
+ usePolling: (_a = config.watchConfig) === null || _a === void 0 ? void 0 : _a.usePolling,
88
+ interval: (_b = config.watchConfig) === null || _b === void 0 ? void 0 : _b.interval,
89
+ depth: 99,
90
+ awaitWriteFinish: true,
91
+ ignorePermissionErrors: false,
92
+ atomic: true,
93
+ ignored,
94
+ });
95
+ (0, debugging_js_1.debugLog)(`[Watcher] Started`);
96
+ const shutdown = () => {
97
+ isShutdown = true;
98
+ (0, debugging_js_1.debugLog)(`[Watcher] Shutting down`);
99
+ log(`Shutting down watch...`);
100
+ watcher.close();
101
+ (0, hooks_js_1.lifecycleHooks)(config.hooks).beforeDone();
102
+ };
103
+ // it doesn't matter what has changed, need to run whole process anyway
104
+ watcher.on('all', async (eventName, path) => {
105
+ (0, hooks_js_1.lifecycleHooks)(config.hooks).onWatchTriggered(eventName, path);
106
+ (0, debugging_js_1.debugLog)(`[Watcher] triggered due to a file ${eventName} event: ${path}`);
107
+ const fullPath = (0, path_1.join)(process.cwd(), path);
108
+ // In ESM require is not defined
109
+ try {
110
+ delete require.cache[fullPath];
111
+ }
112
+ catch (err) { }
113
+ if (eventName === 'change' && config.configFilePath && fullPath === config.configFilePath) {
114
+ log(`${log_symbols_1.default.info} Config file has changed, reloading...`);
115
+ const context = await (0, config_js_1.loadContext)(config.configFilePath);
116
+ const newParsedConfig = context.getConfig();
117
+ newParsedConfig.watch = config.watch;
118
+ newParsedConfig.silent = config.silent;
119
+ newParsedConfig.overwrite = config.overwrite;
120
+ newParsedConfig.configFilePath = config.configFilePath;
121
+ config = newParsedConfig;
122
+ initalContext.updateConfig(config);
123
+ }
124
+ debouncedExec();
125
+ });
126
+ process.once('SIGINT', shutdown);
127
+ process.once('SIGTERM', shutdown);
128
+ };
129
+ // the promise never resolves to keep process running
130
+ return new Promise((resolve, reject) => {
131
+ (0, codegen_js_1.executeCodegen)(initalContext)
132
+ .then(onNext, () => Promise.resolve())
133
+ .then(runWatcher)
134
+ .catch(err => {
135
+ watcher.close();
136
+ reject(err);
137
+ });
138
+ });
139
+ };
140
+ exports.createWatcher = createWatcher;
package/esm/bin.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from './cli.js';
3
+ import { cliError } from './utils/cli-error.js';
4
+ const [, , cmd] = process.argv;
5
+ runCli(cmd)
6
+ .then(() => {
7
+ process.exit(0);
8
+ })
9
+ .catch(error => {
10
+ cliError(error);
11
+ });
package/esm/cli.js ADDED
@@ -0,0 +1,32 @@
1
+ import { generate } from './generate-and-save.js';
2
+ import { init } from './init/index.js';
3
+ import { createContext } from './config.js';
4
+ import { lifecycleHooks } from './hooks.js';
5
+ import { DetailedError } from '@graphql-codegen/plugin-helpers';
6
+ export async function runCli(cmd) {
7
+ await ensureGraphQlPackage();
8
+ if (cmd === 'init') {
9
+ return init();
10
+ }
11
+ const context = await createContext();
12
+ try {
13
+ return await generate(context);
14
+ }
15
+ catch (error) {
16
+ await lifecycleHooks(context.getConfig().hooks).onError(error.toString());
17
+ throw error;
18
+ }
19
+ }
20
+ export async function ensureGraphQlPackage() {
21
+ try {
22
+ await import('graphql');
23
+ }
24
+ catch (e) {
25
+ throw new DetailedError(`Unable to load "graphql" package. Please make sure to install "graphql" as a dependency!`, `
26
+ To install "graphql", run:
27
+ yarn add graphql
28
+ Or, with NPM:
29
+ npm install --save graphql
30
+ `);
31
+ }
32
+ }