UNPKG

30.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};
48var _this = this;
49Object.defineProperty(exports, "__esModule", { value: true });
50var document_from_string_1 = require("./loaders/documents/document-from-string");
51var schema_from_string_1 = require("./loaders/schema/schema-from-string");
52var graphql_tools_1 = require("graphql-tools");
53var Listr = require("listr");
54var helpers_1 = require("./helpers");
55var introspection_from_url_1 = require("./loaders/schema/introspection-from-url");
56var introspection_from_file_1 = require("./loaders/schema/introspection-from-file");
57var schema_from_typedefs_1 = require("./loaders/schema/schema-from-typedefs");
58var schema_from_export_1 = require("./loaders/schema/schema-from-export");
59var validate_documents_1 = require("./loaders/documents/validate-documents");
60var prettier_1 = require("./utils/prettier");
61var listr_renderer_1 = require("./utils/listr-renderer");
62var errors_1 = require("./errors");
63var documents_from_glob_1 = require("./loaders/documents/documents-from-glob");
64var epoxy_1 = require("@graphql-modules/epoxy");
65var documentsHandlers = [new document_from_string_1.DocumentFromString(), new documents_from_glob_1.DocumentsFromGlob()];
66var schemaHandlers = [
67 new introspection_from_url_1.IntrospectionFromUrlLoader(),
68 new introspection_from_file_1.IntrospectionFromFileLoader(),
69 new schema_from_string_1.SchemaFromString(),
70 new schema_from_typedefs_1.SchemaFromTypedefs(),
71 new schema_from_export_1.SchemaFromExport()
72];
73var loadDocuments = function (documentDef, config) { return __awaiter(_this, void 0, void 0, function () {
74 var _i, documentsHandlers_1, handler;
75 return __generator(this, function (_a) {
76 switch (_a.label) {
77 case 0:
78 _i = 0, documentsHandlers_1 = documentsHandlers;
79 _a.label = 1;
80 case 1:
81 if (!(_i < documentsHandlers_1.length)) return [3 /*break*/, 4];
82 handler = documentsHandlers_1[_i];
83 return [4 /*yield*/, handler.canHandle(documentDef)];
84 case 2:
85 if (_a.sent()) {
86 return [2 /*return*/, handler.handle(documentDef, config)];
87 }
88 _a.label = 3;
89 case 3:
90 _i++;
91 return [3 /*break*/, 1];
92 case 4: return [2 /*return*/, []];
93 }
94 });
95}); };
96var loadSchema = function (schemaDef, config) { return __awaiter(_this, void 0, void 0, function () {
97 var _i, schemaHandlers_1, handler, pointToSchema, options;
98 return __generator(this, function (_a) {
99 switch (_a.label) {
100 case 0:
101 _i = 0, schemaHandlers_1 = schemaHandlers;
102 _a.label = 1;
103 case 1:
104 if (!(_i < schemaHandlers_1.length)) return [3 /*break*/, 4];
105 handler = schemaHandlers_1[_i];
106 pointToSchema = null;
107 options = {};
108 if (typeof schemaDef === 'string') {
109 pointToSchema = schemaDef;
110 }
111 else if (typeof schemaDef === 'object') {
112 pointToSchema = Object.keys(schemaDef)[0];
113 options = schemaDef[pointToSchema];
114 }
115 return [4 /*yield*/, handler.canHandle(pointToSchema)];
116 case 2:
117 if (_a.sent()) {
118 return [2 /*return*/, handler.handle(pointToSchema, config, options)];
119 }
120 _a.label = 3;
121 case 3:
122 _i++;
123 return [3 /*break*/, 1];
124 case 4: throw new errors_1.DetailedError('Failed to load schema', "\n Failed to load schema from " + schemaDef + ".\n\n GraphQL Code Generator supports:\n - ES Modules and CommonJS exports\n - Introspection JSON File\n - URL of GraphQL endpoint\n - Multiple files with type definitions\n - String in config file\n\n Try to use one of above options and run codegen again.\n\n ");
125 }
126 });
127}); };
128function mergeSchemas(schemas) {
129 return __awaiter(this, void 0, void 0, function () {
130 var mergedSchemaString;
131 return __generator(this, function (_a) {
132 if (schemas.length === 0) {
133 return [2 /*return*/, null];
134 }
135 else if (schemas.length === 1) {
136 return [2 /*return*/, schemas[0]];
137 }
138 else {
139 mergedSchemaString = epoxy_1.mergeGraphQLSchemas(schemas.filter(function (s) { return s; }));
140 return [2 /*return*/, graphql_tools_1.makeExecutableSchema({
141 typeDefs: mergedSchemaString,
142 allowUndefinedInResolve: true,
143 resolverValidationOptions: {
144 requireResolversForResolveType: false,
145 requireResolversForAllFields: false,
146 requireResolversForNonScalar: false,
147 requireResolversForArgs: false
148 }
149 })];
150 }
151 return [2 /*return*/];
152 });
153 });
154}
155exports.mergeSchemas = mergeSchemas;
156function executeCodegen(config) {
157 return __awaiter(this, void 0, void 0, function () {
158 function wrapTask(task, source) {
159 var _this = this;
160 return function () { return __awaiter(_this, void 0, void 0, function () {
161 var error_1;
162 return __generator(this, function (_a) {
163 switch (_a.label) {
164 case 0:
165 _a.trys.push([0, 2, , 3]);
166 return [4 /*yield*/, task()];
167 case 1:
168 _a.sent();
169 return [3 /*break*/, 3];
170 case 2:
171 error_1 = _a.sent();
172 if (source) {
173 error_1.source = source;
174 }
175 throw error_1;
176 case 3: return [2 /*return*/];
177 }
178 });
179 }); };
180 }
181 function normalize() {
182 /* Load Require extensions */
183 var requireExtensions = helpers_1.normalizeInstanceOrArray(config.require);
184 requireExtensions.forEach(function (mod) { return require(mod); });
185 /* Root templates-config */
186 rootConfig = config.config || {};
187 /* Normalize root "schema" field */
188 schemas = helpers_1.normalizeInstanceOrArray(config.schema);
189 /* Normalize root "documents" field */
190 documents = helpers_1.normalizeInstanceOrArray(config.documents);
191 /* Normalize "generators" field */
192 var generateKeys = Object.keys(config.generates);
193 if (generateKeys.length === 0) {
194 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 ");
195 }
196 for (var _i = 0, generateKeys_1 = generateKeys; _i < generateKeys_1.length; _i++) {
197 var filename = generateKeys_1[_i];
198 generates[filename] = helpers_1.normalizeOutputParam(config.generates[filename]);
199 if (generates[filename].plugins.length === 0) {
200 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 ");
201 }
202 }
203 if (schemas.length === 0 && Object.keys(generates).some(function (filename) { return generates[filename].schema.length === 0; })) {
204 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 ");
205 }
206 }
207 function loadRootSchema() {
208 return __awaiter(this, void 0, void 0, function () {
209 var _a;
210 return __generator(this, function (_b) {
211 switch (_b.label) {
212 case 0:
213 if (!schemas.length) return [3 /*break*/, 3];
214 _a = mergeSchemas;
215 return [4 /*yield*/, Promise.all(schemas.map(function (pointToScehma) { return loadSchema(pointToScehma, config); }))];
216 case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])];
217 case 2:
218 rootSchema = _b.sent();
219 _b.label = 3;
220 case 3: return [2 /*return*/];
221 }
222 });
223 });
224 }
225 function loadRootDocuments() {
226 return __awaiter(this, void 0, void 0, function () {
227 var _i, documents_1, docDef, documents_2, errors;
228 return __generator(this, function (_a) {
229 switch (_a.label) {
230 case 0:
231 if (!(documents.length > 0)) return [3 /*break*/, 5];
232 _i = 0, documents_1 = documents;
233 _a.label = 1;
234 case 1:
235 if (!(_i < documents_1.length)) return [3 /*break*/, 4];
236 docDef = documents_1[_i];
237 return [4 /*yield*/, loadDocuments(docDef, config)];
238 case 2:
239 documents_2 = _a.sent();
240 if (documents_2.length > 0) {
241 rootDocuments.push.apply(rootDocuments, documents_2);
242 }
243 _a.label = 3;
244 case 3:
245 _i++;
246 return [3 /*break*/, 1];
247 case 4:
248 if (rootSchema) {
249 errors = validate_documents_1.validateGraphQlDocuments(rootSchema, rootDocuments);
250 validate_documents_1.checkValidationErrors(errors);
251 }
252 _a.label = 5;
253 case 5: return [2 /*return*/];
254 }
255 });
256 });
257 }
258 var result, commonListrOptions, listr, rootConfig, schemas, documents, generates, rootSchema, rootDocuments;
259 return __generator(this, function (_a) {
260 switch (_a.label) {
261 case 0:
262 result = [];
263 commonListrOptions = {
264 exitOnError: true
265 };
266 if (process.env.VERBOSE) {
267 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'verbose', nonTTYRenderer: 'verbose' }));
268 }
269 else if (process.env.NODE_ENV === 'test') {
270 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'silent', nonTTYRenderer: 'silent' }));
271 }
272 else {
273 listr = new Listr(__assign({}, commonListrOptions, { renderer: config.silent ? 'silent' : listr_renderer_1.Renderer, nonTTYRenderer: config.silent ? 'silent' : 'default', collapse: true, clearOutput: false }));
274 }
275 rootConfig = {};
276 generates = {};
277 rootDocuments = [];
278 listr.add({
279 title: 'Parse configuration',
280 task: function (ctx) {
281 normalize();
282 ctx.hasSchemas = schemas.length > 0;
283 ctx.hasDocuments = documents.length > 0;
284 }
285 });
286 listr.add({
287 title: 'Load schema',
288 enabled: function (ctx) { return ctx.hasSchemas; },
289 task: wrapTask(loadRootSchema)
290 });
291 listr.add({
292 title: 'Load documents',
293 enabled: function (ctx) { return ctx.hasDocuments; },
294 task: wrapTask(loadRootDocuments)
295 });
296 listr.add({
297 title: 'Generate outputs',
298 task: function () {
299 return new Listr(Object.keys(generates).map(function (filename, i) { return ({
300 title: "Generate " + filename,
301 task: function () {
302 var outputConfig = generates[filename];
303 var outputFileTemplateConfig = outputConfig.config || {};
304 var outputSchema = rootSchema;
305 var outputDocuments = rootDocuments;
306 var outputSpecificSchemas = helpers_1.normalizeInstanceOrArray(outputConfig.schema);
307 var outputSpecificDocuments = helpers_1.normalizeInstanceOrArray(outputConfig.documents);
308 function addSchema() {
309 return __awaiter(this, void 0, void 0, function () {
310 var _a, _b, _c;
311 return __generator(this, function (_d) {
312 switch (_d.label) {
313 case 0:
314 _a = mergeSchemas;
315 _c = (_b = [
316 rootSchema
317 ]).concat;
318 return [4 /*yield*/, Promise.all(outputSpecificSchemas.map(function (pointToScehma) { return loadSchema(pointToScehma, config); }))];
319 case 1: return [4 /*yield*/, _a.apply(void 0, [_c.apply(_b, [(_d.sent())])])];
320 case 2:
321 outputSchema = _d.sent();
322 return [2 /*return*/];
323 }
324 });
325 });
326 }
327 function addDocuments() {
328 return __awaiter(this, void 0, void 0, function () {
329 var additionalDocs, _i, outputSpecificDocuments_1, docDef, documents_3, errors;
330 return __generator(this, function (_a) {
331 switch (_a.label) {
332 case 0:
333 additionalDocs = [];
334 _i = 0, outputSpecificDocuments_1 = outputSpecificDocuments;
335 _a.label = 1;
336 case 1:
337 if (!(_i < outputSpecificDocuments_1.length)) return [3 /*break*/, 4];
338 docDef = outputSpecificDocuments_1[_i];
339 return [4 /*yield*/, loadDocuments(docDef, config)];
340 case 2:
341 documents_3 = _a.sent();
342 if (documents_3.length > 0) {
343 additionalDocs.push.apply(additionalDocs, documents_3);
344 }
345 _a.label = 3;
346 case 3:
347 _i++;
348 return [3 /*break*/, 1];
349 case 4:
350 if (outputSchema) {
351 errors = validate_documents_1.validateGraphQlDocuments(outputSchema, additionalDocs);
352 validate_documents_1.checkValidationErrors(errors);
353 }
354 outputDocuments = rootDocuments.concat(additionalDocs);
355 return [2 /*return*/];
356 }
357 });
358 });
359 }
360 function doGenerateOutput() {
361 return __awaiter(this, void 0, void 0, function () {
362 var normalizedPluginsArray, output;
363 return __generator(this, function (_a) {
364 switch (_a.label) {
365 case 0:
366 normalizedPluginsArray = helpers_1.normalizeConfig(outputConfig.plugins);
367 return [4 /*yield*/, generateOutput({
368 filename: filename,
369 plugins: normalizedPluginsArray,
370 schema: outputSchema,
371 documents: outputDocuments,
372 inheritedConfig: __assign({}, rootConfig, outputFileTemplateConfig)
373 })];
374 case 1:
375 output = _a.sent();
376 result.push(output);
377 return [2 /*return*/];
378 }
379 });
380 });
381 }
382 return new Listr([
383 {
384 title: 'Add related schemas',
385 enabled: function () { return outputSpecificSchemas.length > 0; },
386 task: wrapTask(addSchema, filename)
387 },
388 {
389 title: 'Add related documents',
390 enabled: function () { return outputSpecificDocuments.length > 0; },
391 task: wrapTask(addDocuments, filename)
392 },
393 {
394 title: 'Generate',
395 task: wrapTask(doGenerateOutput, filename)
396 }
397 ], {
398 // it stops when one of tasks failed
399 exitOnError: true
400 });
401 }
402 }); }), {
403 // it doesn't stop when one of tasks failed, to finish at least some of outputs
404 exitOnError: false,
405 // run 4 at once
406 concurrent: 4
407 });
408 }
409 });
410 return [4 /*yield*/, listr.run()];
411 case 1:
412 _a.sent();
413 return [2 /*return*/, result];
414 }
415 });
416 });
417}
418exports.executeCodegen = executeCodegen;
419function generateOutput(options) {
420 return __awaiter(this, void 0, void 0, function () {
421 var output, _i, _a, plugin, name_1, pluginConfig, result, _b;
422 return __generator(this, function (_c) {
423 switch (_c.label) {
424 case 0:
425 output = '';
426 _i = 0, _a = options.plugins;
427 _c.label = 1;
428 case 1:
429 if (!(_i < _a.length)) return [3 /*break*/, 4];
430 plugin = _a[_i];
431 name_1 = Object.keys(plugin)[0];
432 pluginConfig = plugin[name_1];
433 return [4 /*yield*/, executePlugin({
434 name: name_1,
435 config: typeof pluginConfig !== 'object'
436 ? pluginConfig
437 : __assign({}, options.inheritedConfig, pluginConfig),
438 schema: options.schema,
439 documents: options.documents,
440 outputFilename: options.filename,
441 allPlugins: options.plugins
442 })];
443 case 2:
444 result = _c.sent();
445 output += result;
446 _c.label = 3;
447 case 3:
448 _i++;
449 return [3 /*break*/, 1];
450 case 4:
451 _b = { filename: options.filename };
452 return [4 /*yield*/, prettier_1.prettify(options.filename, output)];
453 case 5: return [2 /*return*/, (_b.content = _c.sent(), _b)];
454 }
455 });
456 });
457}
458exports.generateOutput = generateOutput;
459function getPluginByName(name) {
460 return __awaiter(this, void 0, void 0, function () {
461 var possibleNames, _i, possibleNames_1, packageName, possibleNamesMsg;
462 return __generator(this, function (_a) {
463 possibleNames = [
464 "graphql-codegen-" + name,
465 "graphql-codegen-" + name + "-template",
466 "codegen-" + name,
467 "codegen-" + name + "-template",
468 name
469 ];
470 for (_i = 0, possibleNames_1 = possibleNames; _i < possibleNames_1.length; _i++) {
471 packageName = possibleNames_1[_i];
472 try {
473 return [2 /*return*/, require(packageName)];
474 }
475 catch (err) {
476 if (err.message.indexOf("Cannot find module '" + packageName + "'") === -1) {
477 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 ");
478 }
479 }
480 }
481 possibleNamesMsg = possibleNames
482 .map(function (name) {
483 return ("\n - " + name + "\n ").trimRight();
484 })
485 .join('');
486 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 ");
487 });
488 });
489}
490exports.getPluginByName = getPluginByName;
491function executePlugin(options) {
492 return __awaiter(this, void 0, void 0, function () {
493 var pluginPackage, schema, _a, e_1;
494 return __generator(this, function (_b) {
495 switch (_b.label) {
496 case 0: return [4 /*yield*/, getPluginByName(options.name)];
497 case 1:
498 pluginPackage = _b.sent();
499 if (!pluginPackage.plugin || typeof pluginPackage.plugin !== 'function') {
500 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 ");
501 }
502 if (!!pluginPackage.addToSchema) return [3 /*break*/, 2];
503 _a = options.schema;
504 return [3 /*break*/, 4];
505 case 2: return [4 /*yield*/, mergeSchemas([
506 options.schema,
507 graphql_tools_1.makeExecutableSchema({
508 typeDefs: pluginPackage.addToSchema,
509 allowUndefinedInResolve: true,
510 resolverValidationOptions: {
511 requireResolversForResolveType: false,
512 requireResolversForAllFields: false,
513 requireResolversForNonScalar: false,
514 requireResolversForArgs: false
515 }
516 })
517 ])];
518 case 3:
519 _a = _b.sent();
520 _b.label = 4;
521 case 4:
522 schema = _a;
523 if (!(pluginPackage.validate && typeof pluginPackage.validate === 'function')) return [3 /*break*/, 8];
524 _b.label = 5;
525 case 5:
526 _b.trys.push([5, 7, , 8]);
527 return [4 /*yield*/, pluginPackage.validate(schema, options.documents, options.config, options.outputFilename, options.allPlugins)];
528 case 6:
529 _b.sent();
530 return [3 /*break*/, 8];
531 case 7:
532 e_1 = _b.sent();
533 throw new errors_1.DetailedError("Plugin \"" + options.name + "\" validation failed:", "\n " + e_1.message + "\n ");
534 case 8: return [2 /*return*/, pluginPackage.plugin(schema, options.documents, options.config)];
535 }
536 });
537 });
538}
539exports.executePlugin = executePlugin;
540//# sourceMappingURL=codegen.js.map
\No newline at end of file