UNPKG

19.9 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14 return new (P || (P = Promise))(function (resolve, reject) {
15 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
18 step((generator = generator.apply(thisArg, _arguments || [])).next());
19 });
20};
21var __generator = (this && this.__generator) || function (thisArg, body) {
22 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
23 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
24 function verb(n) { return function (v) { return step([n, v]); }; }
25 function step(op) {
26 if (f) throw new TypeError("Generator is already executing.");
27 while (_) try {
28 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
29 if (y = 0, t) op = [op[0] & 2, t.value];
30 switch (op[0]) {
31 case 0: case 1: t = op; break;
32 case 4: _.label++; return { value: op[1], done: false };
33 case 5: _.label++; y = op[1]; op = [0]; continue;
34 case 7: op = _.ops.pop(); _.trys.pop(); continue;
35 default:
36 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
37 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
38 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
39 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
40 if (t[2]) _.ops.pop();
41 _.trys.pop(); continue;
42 }
43 op = body.call(thisArg, _);
44 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
45 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46 }
47};
48Object.defineProperty(exports, "__esModule", { value: true });
49var Listr = require("listr");
50var helpers_1 = require("./helpers");
51var prettier_1 = require("./utils/prettier");
52var listr_renderer_1 = require("./utils/listr-renderer");
53var errors_1 = require("./errors");
54var load_1 = require("./load");
55var merge_schemas_1 = require("./merge-schemas");
56var graphql_1 = require("graphql");
57var execute_plugin_1 = require("./execute-plugin");
58function executeCodegen(config) {
59 return __awaiter(this, void 0, void 0, function () {
60 function wrapTask(task, source) {
61 var _this = this;
62 return function () { return __awaiter(_this, void 0, void 0, function () {
63 var error_1;
64 return __generator(this, function (_a) {
65 switch (_a.label) {
66 case 0:
67 _a.trys.push([0, 2, , 3]);
68 return [4 /*yield*/, task()];
69 case 1:
70 _a.sent();
71 return [3 /*break*/, 3];
72 case 2:
73 error_1 = _a.sent();
74 if (source && !(error_1 instanceof graphql_1.GraphQLError)) {
75 error_1.source = source;
76 }
77 throw error_1;
78 case 3: return [2 /*return*/];
79 }
80 });
81 }); };
82 }
83 function normalize() {
84 /* Load Require extensions */
85 var requireExtensions = helpers_1.normalizeInstanceOrArray(config.require);
86 requireExtensions.forEach(function (mod) { return require(mod); });
87 /* Root templates-config */
88 rootConfig = config.config || {};
89 /* Normalize root "schema" field */
90 rootSchemas = helpers_1.normalizeInstanceOrArray(config.schema);
91 /* Normalize root "documents" field */
92 rootDocuments = helpers_1.normalizeInstanceOrArray(config.documents);
93 /* Normalize "generators" field */
94 var generateKeys = Object.keys(config.generates);
95 if (generateKeys.length === 0) {
96 throw new errors_1.DetailedError('Invalid Codegen Configuration!', "\n Please make sure that your codegen config file contains the \"generates\" field, with a specification for the plugins you need.\n \n It should looks like that:\n\n schema:\n - my-schema.graphql\n generates:\n my-file.ts:\n - plugin1\n - plugin2\n - plugin3\n ");
97 }
98 for (var _i = 0, generateKeys_1 = generateKeys; _i < generateKeys_1.length; _i++) {
99 var filename = generateKeys_1[_i];
100 generates[filename] = helpers_1.normalizeOutputParam(config.generates[filename]);
101 if (generates[filename].plugins.length === 0) {
102 throw new errors_1.DetailedError('Invalid Codegen Configuration!', "\n Please make sure that your codegen config file has defined plugins list for output \"" + filename + "\".\n \n It should looks like that:\n \n schema:\n - my-schema.graphql\n generates:\n my-file.ts:\n - plugin1\n - plugin2\n - plugin3\n ");
103 }
104 }
105 if (rootSchemas.length === 0 && Object.keys(generates).some(function (filename) { return generates[filename].schema.length === 0; })) {
106 throw new errors_1.DetailedError('Invalid Codegen Configuration!', "\n Please make sure that your codegen config file contains either the \"schema\" field \n or every generated file has its own \"schema\" field.\n \n It should looks like that:\n schema:\n - my-schema.graphql\n\n or:\n generates:\n path/to/output:\n schema: my-schema.graphql\n ");
107 }
108 }
109 var result, commonListrOptions, listr, rootConfig, rootSchemas, rootDocuments, generates;
110 var _this = this;
111 return __generator(this, function (_a) {
112 switch (_a.label) {
113 case 0:
114 result = [];
115 commonListrOptions = {
116 exitOnError: true
117 };
118 if (process.env.VERBOSE) {
119 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'verbose', nonTTYRenderer: 'verbose' }));
120 }
121 else if (process.env.NODE_ENV === 'test') {
122 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'silent', nonTTYRenderer: 'silent' }));
123 }
124 else {
125 listr = new Listr(__assign({}, commonListrOptions, { renderer: config.silent ? 'silent' : listr_renderer_1.Renderer, nonTTYRenderer: config.silent ? 'silent' : 'default', collapse: true, clearOutput: false }));
126 }
127 rootConfig = {};
128 generates = {};
129 listr.add({
130 title: 'Parse configuration',
131 task: function () { return normalize(); }
132 });
133 listr.add({
134 title: 'Generate outputs',
135 task: function () {
136 return new Listr(Object.keys(generates).map(function (filename, i) { return ({
137 title: "Generate " + filename,
138 task: function () {
139 var outputConfig = generates[filename];
140 var outputFileTemplateConfig = outputConfig.config || {};
141 var outputDocuments = [];
142 var outputSchema;
143 var outputSpecificSchemas = helpers_1.normalizeInstanceOrArray(outputConfig.schema);
144 var outputSpecificDocuments = helpers_1.normalizeInstanceOrArray(outputConfig.documents);
145 return new Listr([
146 {
147 title: 'Load GraphQL schemas',
148 task: wrapTask(function () { return __awaiter(_this, void 0, void 0, function () {
149 var allSchemas, _a;
150 return __generator(this, function (_b) {
151 switch (_b.label) {
152 case 0:
153 allSchemas = rootSchemas.map(function (pointToScehma) { return load_1.loadSchema(pointToScehma, config); }).concat(outputSpecificSchemas.map(function (pointToScehma) { return load_1.loadSchema(pointToScehma, config); }));
154 if (!(allSchemas.length > 0)) return [3 /*break*/, 3];
155 _a = merge_schemas_1.mergeSchemas;
156 return [4 /*yield*/, Promise.all(allSchemas)];
157 case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])];
158 case 2:
159 outputSchema = _b.sent();
160 _b.label = 3;
161 case 3: return [2 /*return*/];
162 }
163 });
164 }); }, filename)
165 },
166 {
167 title: 'Load GraphQL documents',
168 task: wrapTask(function () { return __awaiter(_this, void 0, void 0, function () {
169 var allDocuments, _i, allDocuments_1, docDef, documents;
170 return __generator(this, function (_a) {
171 switch (_a.label) {
172 case 0:
173 allDocuments = rootDocuments.concat(outputSpecificDocuments);
174 _i = 0, allDocuments_1 = allDocuments;
175 _a.label = 1;
176 case 1:
177 if (!(_i < allDocuments_1.length)) return [3 /*break*/, 4];
178 docDef = allDocuments_1[_i];
179 return [4 /*yield*/, load_1.loadDocuments(docDef, config)];
180 case 2:
181 documents = _a.sent();
182 if (documents.length > 0) {
183 outputDocuments.push.apply(outputDocuments, documents);
184 }
185 _a.label = 3;
186 case 3:
187 _i++;
188 return [3 /*break*/, 1];
189 case 4: return [2 /*return*/];
190 }
191 });
192 }); }, filename)
193 },
194 {
195 title: 'Generate',
196 task: wrapTask(function () { return __awaiter(_this, void 0, void 0, function () {
197 var normalizedPluginsArray, output;
198 return __generator(this, function (_a) {
199 switch (_a.label) {
200 case 0:
201 normalizedPluginsArray = helpers_1.normalizeConfig(outputConfig.plugins);
202 return [4 /*yield*/, generateOutput({
203 filename: filename,
204 plugins: normalizedPluginsArray,
205 schema: outputSchema,
206 documents: outputDocuments,
207 inheritedConfig: __assign({}, rootConfig, outputFileTemplateConfig),
208 pluginLoader: config.pluginLoader || require
209 })];
210 case 1:
211 output = _a.sent();
212 result.push(output);
213 return [2 /*return*/];
214 }
215 });
216 }); }, filename)
217 }
218 ], {
219 // it stops when one of tasks failed
220 exitOnError: true
221 });
222 }
223 }); }), {
224 // it doesn't stop when one of tasks failed, to finish at least some of outputs
225 exitOnError: false,
226 // run 4 at once
227 concurrent: 4
228 });
229 }
230 });
231 return [4 /*yield*/, listr.run()];
232 case 1:
233 _a.sent();
234 return [2 /*return*/, result];
235 }
236 });
237 });
238}
239exports.executeCodegen = executeCodegen;
240function validateDocuments(schema, files) {
241 // duplicated names
242 var operationMap = {};
243 files.forEach(function (file) {
244 graphql_1.visit(file.content, {
245 OperationDefinition: function (node) {
246 if (typeof node.name !== 'undefined') {
247 if (!operationMap[node.name.value]) {
248 operationMap[node.name.value] = [];
249 }
250 operationMap[node.name.value].push(file.filePath);
251 }
252 }
253 });
254 });
255 var names = Object.keys(operationMap);
256 if (names.length) {
257 var duplicated = names.filter(function (name) { return operationMap[name].length > 1; });
258 if (!duplicated.length) {
259 return;
260 }
261 var list = duplicated
262 .map(function (name) {
263 return ("\n * " + name + " found in:\n " + operationMap[name]
264 .map(function (filepath) {
265 return ("\n - " + filepath + "\n ").trimRight();
266 })
267 .join('') + "\n ").trimRight();
268 })
269 .join('');
270 throw new errors_1.DetailedError("Not all operations have an unique name: " + duplicated.join(', '), "\n Not all operations have an unique name\n\n " + list + "\n ");
271 }
272}
273function generateOutput(options) {
274 return __awaiter(this, void 0, void 0, function () {
275 var output, pluginsPackages, schema, i, plugin, pluginPackage, name_1, pluginConfig, result, _a;
276 return __generator(this, function (_b) {
277 switch (_b.label) {
278 case 0:
279 output = '';
280 validateDocuments(options.schema, options.documents);
281 return [4 /*yield*/, Promise.all(options.plugins.map(function (plugin) { return execute_plugin_1.getPluginByName(Object.keys(plugin)[0], options.pluginLoader); }))];
282 case 1:
283 pluginsPackages = _b.sent();
284 schema = pluginsPackages.reduce(function (schema, plugin) {
285 return !plugin.addToSchema ? schema : merge_schemas_1.mergeSchemas([schema, plugin.addToSchema]);
286 }, options.schema);
287 i = 0;
288 _b.label = 2;
289 case 2:
290 if (!(i < options.plugins.length)) return [3 /*break*/, 5];
291 plugin = options.plugins[i];
292 pluginPackage = pluginsPackages[i];
293 name_1 = Object.keys(plugin)[0];
294 pluginConfig = plugin[name_1];
295 return [4 /*yield*/, execute_plugin_1.executePlugin({
296 name: name_1,
297 config: typeof pluginConfig !== 'object'
298 ? pluginConfig
299 : __assign({}, options.inheritedConfig, pluginConfig),
300 schema: schema,
301 documents: options.documents,
302 outputFilename: options.filename,
303 allPlugins: options.plugins
304 }, pluginPackage)];
305 case 3:
306 result = _b.sent();
307 output += result;
308 _b.label = 4;
309 case 4:
310 i++;
311 return [3 /*break*/, 2];
312 case 5:
313 _a = { filename: options.filename };
314 return [4 /*yield*/, prettier_1.prettify(options.filename, output)];
315 case 6: return [2 /*return*/, (_a.content = _b.sent(), _a)];
316 }
317 });
318 });
319}
320exports.generateOutput = generateOutput;
321//# sourceMappingURL=codegen.js.map
\No newline at end of file