UNPKG

26.6 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 graphql_tools_1 = require("graphql-tools");
50var Listr = require("listr");
51var helpers_1 = require("./helpers");
52var validate_documents_1 = require("./loaders/documents/validate-documents");
53var prettier_1 = require("./utils/prettier");
54var listr_renderer_1 = require("./utils/listr-renderer");
55var errors_1 = require("./errors");
56var load_1 = require("./load");
57var merge_schemas_1 = require("./merge-schemas");
58var graphql_1 = require("graphql");
59function executeCodegen(config) {
60 return __awaiter(this, void 0, void 0, function () {
61 function wrapTask(task, source) {
62 var _this = this;
63 return function () { return __awaiter(_this, void 0, void 0, function () {
64 var error_1;
65 return __generator(this, function (_a) {
66 switch (_a.label) {
67 case 0:
68 _a.trys.push([0, 2, , 3]);
69 return [4 /*yield*/, task()];
70 case 1:
71 _a.sent();
72 return [3 /*break*/, 3];
73 case 2:
74 error_1 = _a.sent();
75 if (source && !(error_1 instanceof graphql_1.GraphQLError)) {
76 error_1.source = source;
77 }
78 throw error_1;
79 case 3: return [2 /*return*/];
80 }
81 });
82 }); };
83 }
84 function normalize() {
85 /* Load Require extensions */
86 var requireExtensions = helpers_1.normalizeInstanceOrArray(config.require);
87 requireExtensions.forEach(function (mod) { return require(mod); });
88 /* Root templates-config */
89 rootConfig = config.config || {};
90 /* Normalize root "schema" field */
91 schemas = helpers_1.normalizeInstanceOrArray(config.schema);
92 /* Normalize root "documents" field */
93 documents = helpers_1.normalizeInstanceOrArray(config.documents);
94 /* Normalize "generators" field */
95 var generateKeys = Object.keys(config.generates);
96 if (generateKeys.length === 0) {
97 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 ");
98 }
99 for (var _i = 0, generateKeys_1 = generateKeys; _i < generateKeys_1.length; _i++) {
100 var filename = generateKeys_1[_i];
101 generates[filename] = helpers_1.normalizeOutputParam(config.generates[filename]);
102 if (generates[filename].plugins.length === 0) {
103 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 ");
104 }
105 }
106 if (schemas.length === 0 && Object.keys(generates).some(function (filename) { return generates[filename].schema.length === 0; })) {
107 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 ");
108 }
109 }
110 function loadRootSchema() {
111 return __awaiter(this, void 0, void 0, function () {
112 var _a;
113 return __generator(this, function (_b) {
114 switch (_b.label) {
115 case 0:
116 if (!schemas.length) return [3 /*break*/, 3];
117 _a = merge_schemas_1.mergeSchemas;
118 return [4 /*yield*/, Promise.all(schemas.map(function (pointToScehma) { return load_1.loadSchema(pointToScehma, config); }))];
119 case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])];
120 case 2:
121 rootSchema = _b.sent();
122 _b.label = 3;
123 case 3: return [2 /*return*/];
124 }
125 });
126 });
127 }
128 function loadRootDocuments() {
129 return __awaiter(this, void 0, void 0, function () {
130 var _i, documents_1, docDef, documents_2, errors;
131 return __generator(this, function (_a) {
132 switch (_a.label) {
133 case 0:
134 if (!(documents.length > 0)) return [3 /*break*/, 5];
135 _i = 0, documents_1 = documents;
136 _a.label = 1;
137 case 1:
138 if (!(_i < documents_1.length)) return [3 /*break*/, 4];
139 docDef = documents_1[_i];
140 return [4 /*yield*/, load_1.loadDocuments(docDef, config)];
141 case 2:
142 documents_2 = _a.sent();
143 if (documents_2.length > 0) {
144 rootDocuments.push.apply(rootDocuments, documents_2);
145 }
146 _a.label = 3;
147 case 3:
148 _i++;
149 return [3 /*break*/, 1];
150 case 4:
151 if (rootSchema) {
152 errors = validate_documents_1.validateGraphQlDocuments(rootSchema, rootDocuments);
153 validate_documents_1.checkValidationErrors(errors);
154 }
155 _a.label = 5;
156 case 5: return [2 /*return*/];
157 }
158 });
159 });
160 }
161 var result, commonListrOptions, listr, rootConfig, schemas, documents, generates, rootSchema, rootDocuments;
162 return __generator(this, function (_a) {
163 switch (_a.label) {
164 case 0:
165 result = [];
166 commonListrOptions = {
167 exitOnError: true
168 };
169 if (process.env.VERBOSE) {
170 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'verbose', nonTTYRenderer: 'verbose' }));
171 }
172 else if (process.env.NODE_ENV === 'test') {
173 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'silent', nonTTYRenderer: 'silent' }));
174 }
175 else {
176 listr = new Listr(__assign({}, commonListrOptions, { renderer: config.silent ? 'silent' : listr_renderer_1.Renderer, nonTTYRenderer: config.silent ? 'silent' : 'default', collapse: true, clearOutput: false }));
177 }
178 rootConfig = {};
179 generates = {};
180 rootDocuments = [];
181 listr.add({
182 title: 'Parse configuration',
183 task: function (ctx) {
184 normalize();
185 ctx.hasSchemas = schemas.length > 0;
186 ctx.hasDocuments = documents.length > 0;
187 }
188 });
189 listr.add({
190 title: 'Load schema',
191 enabled: function (ctx) { return ctx.hasSchemas; },
192 task: wrapTask(loadRootSchema)
193 });
194 listr.add({
195 title: 'Load documents',
196 enabled: function (ctx) { return ctx.hasDocuments; },
197 task: wrapTask(loadRootDocuments)
198 });
199 listr.add({
200 title: 'Generate outputs',
201 task: function () {
202 return new Listr(Object.keys(generates).map(function (filename, i) { return ({
203 title: "Generate " + filename,
204 task: function () {
205 var outputConfig = generates[filename];
206 var outputFileTemplateConfig = outputConfig.config || {};
207 var outputSchema = rootSchema;
208 var outputDocuments = rootDocuments;
209 var outputSpecificSchemas = helpers_1.normalizeInstanceOrArray(outputConfig.schema);
210 var outputSpecificDocuments = helpers_1.normalizeInstanceOrArray(outputConfig.documents);
211 function addSchema() {
212 return __awaiter(this, void 0, void 0, function () {
213 var _a, _b, _c;
214 return __generator(this, function (_d) {
215 switch (_d.label) {
216 case 0:
217 _a = merge_schemas_1.mergeSchemas;
218 _c = (_b = [
219 rootSchema
220 ]).concat;
221 return [4 /*yield*/, Promise.all(outputSpecificSchemas.map(function (pointToScehma) { return load_1.loadSchema(pointToScehma, config); }))];
222 case 1: return [4 /*yield*/, _a.apply(void 0, [_c.apply(_b, [(_d.sent())])])];
223 case 2:
224 outputSchema = _d.sent();
225 return [2 /*return*/];
226 }
227 });
228 });
229 }
230 function addDocuments() {
231 return __awaiter(this, void 0, void 0, function () {
232 var additionalDocs, _i, outputSpecificDocuments_1, docDef, documents_3, errors;
233 return __generator(this, function (_a) {
234 switch (_a.label) {
235 case 0:
236 additionalDocs = [];
237 _i = 0, outputSpecificDocuments_1 = outputSpecificDocuments;
238 _a.label = 1;
239 case 1:
240 if (!(_i < outputSpecificDocuments_1.length)) return [3 /*break*/, 4];
241 docDef = outputSpecificDocuments_1[_i];
242 return [4 /*yield*/, load_1.loadDocuments(docDef, config)];
243 case 2:
244 documents_3 = _a.sent();
245 if (documents_3.length > 0) {
246 additionalDocs.push.apply(additionalDocs, documents_3);
247 }
248 _a.label = 3;
249 case 3:
250 _i++;
251 return [3 /*break*/, 1];
252 case 4:
253 if (outputSchema) {
254 errors = validate_documents_1.validateGraphQlDocuments(outputSchema, additionalDocs);
255 validate_documents_1.checkValidationErrors(errors);
256 }
257 outputDocuments = rootDocuments.concat(additionalDocs);
258 return [2 /*return*/];
259 }
260 });
261 });
262 }
263 function doGenerateOutput() {
264 return __awaiter(this, void 0, void 0, function () {
265 var normalizedPluginsArray, output;
266 return __generator(this, function (_a) {
267 switch (_a.label) {
268 case 0:
269 normalizedPluginsArray = helpers_1.normalizeConfig(outputConfig.plugins);
270 return [4 /*yield*/, generateOutput({
271 filename: filename,
272 plugins: normalizedPluginsArray,
273 schema: outputSchema,
274 documents: outputDocuments,
275 inheritedConfig: __assign({}, rootConfig, outputFileTemplateConfig),
276 pluginLoader: config.pluginLoader || require
277 })];
278 case 1:
279 output = _a.sent();
280 result.push(output);
281 return [2 /*return*/];
282 }
283 });
284 });
285 }
286 return new Listr([
287 {
288 title: 'Add related schemas',
289 enabled: function () { return outputSpecificSchemas.length > 0; },
290 task: wrapTask(addSchema, filename)
291 },
292 {
293 title: 'Add related documents',
294 enabled: function () { return outputSpecificDocuments.length > 0; },
295 task: wrapTask(addDocuments, filename)
296 },
297 {
298 title: 'Generate',
299 task: wrapTask(doGenerateOutput, filename)
300 }
301 ], {
302 // it stops when one of tasks failed
303 exitOnError: true
304 });
305 }
306 }); }), {
307 // it doesn't stop when one of tasks failed, to finish at least some of outputs
308 exitOnError: false,
309 // run 4 at once
310 concurrent: 4
311 });
312 }
313 });
314 return [4 /*yield*/, listr.run()];
315 case 1:
316 _a.sent();
317 return [2 /*return*/, result];
318 }
319 });
320 });
321}
322exports.executeCodegen = executeCodegen;
323function generateOutput(options) {
324 return __awaiter(this, void 0, void 0, function () {
325 var output, _i, _a, plugin, name_1, pluginConfig, result, _b;
326 return __generator(this, function (_c) {
327 switch (_c.label) {
328 case 0:
329 output = '';
330 _i = 0, _a = options.plugins;
331 _c.label = 1;
332 case 1:
333 if (!(_i < _a.length)) return [3 /*break*/, 4];
334 plugin = _a[_i];
335 name_1 = Object.keys(plugin)[0];
336 pluginConfig = plugin[name_1];
337 return [4 /*yield*/, executePlugin({
338 name: name_1,
339 config: typeof pluginConfig !== 'object'
340 ? pluginConfig
341 : __assign({}, options.inheritedConfig, pluginConfig),
342 schema: options.schema,
343 documents: options.documents,
344 outputFilename: options.filename,
345 allPlugins: options.plugins,
346 pluginLoader: options.pluginLoader
347 })];
348 case 2:
349 result = _c.sent();
350 output += result;
351 _c.label = 3;
352 case 3:
353 _i++;
354 return [3 /*break*/, 1];
355 case 4:
356 _b = { filename: options.filename };
357 return [4 /*yield*/, prettier_1.prettify(options.filename, output)];
358 case 5: return [2 /*return*/, (_b.content = _c.sent(), _b)];
359 }
360 });
361 });
362}
363exports.generateOutput = generateOutput;
364function getPluginByName(name, pluginLoader) {
365 return __awaiter(this, void 0, void 0, function () {
366 var possibleNames, _i, possibleNames_1, packageName, possibleNamesMsg;
367 return __generator(this, function (_a) {
368 possibleNames = [
369 "graphql-codegen-" + name,
370 "graphql-codegen-" + name + "-template",
371 "codegen-" + name,
372 "codegen-" + name + "-template",
373 name
374 ];
375 for (_i = 0, possibleNames_1 = possibleNames; _i < possibleNames_1.length; _i++) {
376 packageName = possibleNames_1[_i];
377 try {
378 return [2 /*return*/, pluginLoader(packageName)];
379 }
380 catch (err) {
381 if (err.message.indexOf("Cannot find module '" + packageName + "'") === -1) {
382 throw new errors_1.DetailedError("Unable to load template plugin matching " + name, "\n Unable to load template plugin matching '" + name + "'.\n Reason: \n " + err.message + "\n ");
383 }
384 }
385 }
386 possibleNamesMsg = possibleNames
387 .map(function (name) {
388 return ("\n - " + name + "\n ").trimRight();
389 })
390 .join('');
391 throw new errors_1.DetailedError("Unable to find template plugin matching " + name, "\n Unable to find template plugin matching '" + name + "'\n Install one of the following packages:\n \n " + possibleNamesMsg + "\n ");
392 });
393 });
394}
395exports.getPluginByName = getPluginByName;
396function executePlugin(options) {
397 return __awaiter(this, void 0, void 0, function () {
398 var pluginPackage, schema, _a, e_1;
399 return __generator(this, function (_b) {
400 switch (_b.label) {
401 case 0: return [4 /*yield*/, getPluginByName(options.name, options.pluginLoader)];
402 case 1:
403 pluginPackage = _b.sent();
404 if (!pluginPackage || !pluginPackage.plugin || typeof pluginPackage.plugin !== 'function') {
405 throw new errors_1.DetailedError("Invalid Custom Plugin \"" + options.name + "\"", "\n Plugin " + options.name + " does not export a valid JS object with \"plugin\" function.\n\n Make sure your custom plugin is written in the following form:\n\n module.exports = {\n plugin: (schema, documents, config) => {\n return 'my-custom-plugin-content';\n },\n };\n ");
406 }
407 if (!!pluginPackage.addToSchema) return [3 /*break*/, 2];
408 _a = options.schema;
409 return [3 /*break*/, 4];
410 case 2: return [4 /*yield*/, merge_schemas_1.mergeSchemas([
411 options.schema,
412 graphql_tools_1.makeExecutableSchema({
413 typeDefs: pluginPackage.addToSchema,
414 allowUndefinedInResolve: true,
415 resolverValidationOptions: {
416 requireResolversForResolveType: false,
417 requireResolversForAllFields: false,
418 requireResolversForNonScalar: false,
419 requireResolversForArgs: false
420 }
421 })
422 ])];
423 case 3:
424 _a = _b.sent();
425 _b.label = 4;
426 case 4:
427 schema = _a;
428 if (!(pluginPackage.validate && typeof pluginPackage.validate === 'function')) return [3 /*break*/, 8];
429 _b.label = 5;
430 case 5:
431 _b.trys.push([5, 7, , 8]);
432 return [4 /*yield*/, pluginPackage.validate(schema, options.documents, options.config, options.outputFilename, options.allPlugins)];
433 case 6:
434 _b.sent();
435 return [3 /*break*/, 8];
436 case 7:
437 e_1 = _b.sent();
438 throw new errors_1.DetailedError("Plugin \"" + options.name + "\" validation failed:", "\n " + e_1.message + "\n ");
439 case 8: return [2 /*return*/, pluginPackage.plugin(schema, options.documents, options.config)];
440 }
441 });
442 });
443}
444exports.executePlugin = executePlugin;
445//# sourceMappingURL=codegen.js.map
\No newline at end of file