UNPKG

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