UNPKG

25.4 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 validate_documents_1 = require("./loaders/documents/validate-documents");
51var commander = require("commander");
52var path = require("path");
53var fs = require("fs");
54var mkdirp = require("mkdirp");
55var graphql_1 = require("graphql");
56var graphql_config_1 = require("graphql-config");
57var documents_glob_1 = require("./utils/documents-glob");
58var document_loader_1 = require("./loaders/documents/document-loader");
59var templates_scanner_1 = require("./loaders/template/templates-scanner");
60var graphql_codegen_compiler_1 = require("graphql-codegen-compiler");
61var graphql_codegen_core_1 = require("graphql-codegen-core");
62var introspection_from_file_1 = require("./loaders/schema/introspection-from-file");
63var introspection_from_url_1 = require("./loaders/schema/introspection-from-url");
64var schema_from_typedefs_1 = require("./loaders/schema/schema-from-typedefs");
65var schema_from_export_1 = require("./loaders/schema/schema-from-export");
66var epoxy_1 = require("@graphql-modules/epoxy");
67var graphql_tools_1 = require("graphql-tools");
68var spinner_1 = require("./spinner");
69process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
70function collect(val, memo) {
71 memo.push(val);
72 return memo;
73}
74exports.initCLI = function (args) {
75 commander
76 .usage('gql-gen [options]')
77 .option('-s, --schema <path>', 'Path to GraphQL schema: local JSON file, GraphQL endpoint, local file that exports GraphQLSchema/AST/JSON')
78 .option('-cs, --clientSchema <path>', 'Path to GraphQL client schema: local JSON file, local file that exports GraphQLSchema/AST/JSON')
79 .option('-h, --header [header]', 'Header to add to the introspection HTTP request when using --url/--schema with url', collect, [])
80 .option('-t, --template <template-name>', 'Language/platform name templates, or a name of NPM modules that `export default` GqlGenConfig object')
81 .option('-p, --project <project-path>', 'Project path(s) to scan for custom template files')
82 .option('--config <json-file>', 'Codegen configuration file, defaults to: ./gql-gen.json')
83 .option('-m, --skip-schema', 'Generates only client side documents, without server side schema types')
84 .option('-c, --skip-documents', 'Generates only server side schema types, without client side documents')
85 .option('-o, --out <path>', 'Output file(s) path', String, './')
86 .option('-r, --require [require]', 'module to preload (option can be repeated)', collect, [])
87 .option('-ow, --no-overwrite', 'Skip file writing if the output file(s) already exists in path')
88 .option('-w, --watch', 'Watch for changes and execute generation automatically')
89 .option('--silent', 'Does not print anything to the console')
90 .option('-ms, --merge-schema <merge-logic>', 'Merge schemas with custom logic')
91 .arguments('<options> [documents...]')
92 .parse(args);
93 return commander;
94};
95exports.cliError = function (err, exitOnError) {
96 if (exitOnError === void 0) { exitOnError = true; }
97 spinner_1.default.fail();
98 var msg;
99 if (err instanceof Error) {
100 msg = err.message || err.toString();
101 }
102 else if (typeof err === 'string') {
103 msg = err;
104 }
105 else {
106 msg = JSON.stringify(err);
107 }
108 graphql_codegen_core_1.getLogger().error(msg);
109 if (exitOnError) {
110 process.exit(1);
111 }
112 return;
113};
114exports.validateCliOptions = function (options) {
115 if (options.silent) {
116 graphql_codegen_core_1.setSilentLogger();
117 }
118 else {
119 graphql_codegen_core_1.useWinstonLogger();
120 }
121 var schema = options.schema;
122 var template = options.template;
123 var project = options.project;
124 if (!schema) {
125 try {
126 var graphqlProjectConfig = graphql_config_1.getGraphQLProjectConfig(project);
127 options.schema = graphqlProjectConfig.schemaPath;
128 }
129 catch (e) {
130 if (e instanceof graphql_config_1.ConfigNotFoundError) {
131 exports.cliError('Flag --schema is missing!');
132 }
133 }
134 }
135 if (!template && !project) {
136 exports.cliError('Please specify language/platform, using --template flag, or specify --project to generate with custom project!');
137 }
138};
139var schemaHandlers = [
140 new introspection_from_url_1.IntrospectionFromUrlLoader(),
141 new introspection_from_file_1.IntrospectionFromFileLoader(),
142 new schema_from_typedefs_1.SchemaFromTypedefs(),
143 new schema_from_export_1.SchemaFromExport()
144];
145exports.executeWithOptions = function (options) { return __awaiter(_this, void 0, void 0, function () {
146 var schema, clientSchema, documents, template, project, gqlGenConfigFilePath, out, generateSchema, generateDocuments, modulesToRequire, templateConfig, localFilePath, localFileExists, templateFromExport, configPath, config, templates, resolvedHelpers_1, relevantEnvVars, addToSchema, asArray, executeGeneration, normalizeOutput;
147 var _this = this;
148 return __generator(this, function (_a) {
149 switch (_a.label) {
150 case 0:
151 spinner_1.default.start('Validating options');
152 exports.validateCliOptions(options);
153 schema = options.schema;
154 clientSchema = options.clientSchema;
155 documents = options.args || [];
156 template = options.template;
157 project = options.project;
158 gqlGenConfigFilePath = options.config || './gql-gen.json';
159 out = options.out || './';
160 generateSchema = !options.skipSchema;
161 generateDocuments = !options.skipDocuments;
162 modulesToRequire = options.require || [];
163 modulesToRequire.forEach(function (mod) { return require(mod); });
164 templateConfig = null;
165 if (template && template !== '') {
166 spinner_1.default.log("Loading template: " + template);
167 graphql_codegen_core_1.debugLog("[executeWithOptions] using template: " + template);
168 // Backward compatibility for older versions
169 if (template === 'ts' ||
170 template === 'ts-single' ||
171 template === 'typescript' ||
172 template === 'typescript-single') {
173 spinner_1.default.warn("You are using the old template name, please install it from NPM and use it by it's new name: \"graphql-codegen-typescript-template\"");
174 template = 'graphql-codegen-typescript-template';
175 }
176 else if (template === 'ts-multiple' || template === 'typescript-multiple') {
177 spinner_1.default.warn("You are using the old template name, please install it from NPM and use it by it's new name: \"graphql-codegen-typescript-template-multiple\"");
178 template = 'graphql-codegen-typescript-template-multiple';
179 }
180 localFilePath = path.resolve(process.cwd(), template);
181 localFileExists = fs.existsSync(localFilePath);
182 try {
183 templateFromExport = require(localFileExists ? localFilePath : template);
184 if (!templateFromExport) {
185 throw new Error();
186 }
187 templateConfig = templateFromExport.default || templateFromExport.config || templateFromExport;
188 spinner_1.default.succeed();
189 }
190 catch (e) {
191 throw new Error("Unknown codegen template: \"" + template + "\", please make sure it's installed using npm/Yarn!");
192 }
193 }
194 graphql_codegen_core_1.debugLog("[executeWithOptions] using project: " + project);
195 configPath = path.resolve(process.cwd(), gqlGenConfigFilePath);
196 config = null;
197 if (fs.existsSync(configPath)) {
198 graphql_codegen_core_1.getLogger().info("Loading config file from: " + configPath);
199 config = JSON.parse(fs.readFileSync(configPath).toString());
200 graphql_codegen_core_1.debugLog("[executeWithOptions] Got project config JSON: " + JSON.stringify(config));
201 }
202 if (project && project !== '') {
203 spinner_1.default.log("Using project: " + project);
204 if (config === null) {
205 throw new Error("To use project feature, please specify --config path or create gql-gen.json in your project root!");
206 }
207 templates = templates_scanner_1.scanForTemplatesInPath(project, graphql_codegen_compiler_1.ALLOWED_CUSTOM_TEMPLATE_EXT);
208 resolvedHelpers_1 = {};
209 Object.keys(config.customHelpers || {}).map(function (helperName) {
210 var filePath = config.customHelpers[helperName];
211 var resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
212 if (fs.existsSync(resolvedPath)) {
213 var requiredFile = require(resolvedPath);
214 if (requiredFile && typeof requiredFile === 'function') {
215 resolvedHelpers_1[helperName] = requiredFile;
216 }
217 else {
218 throw new Error("Custom template file " + resolvedPath + " does not have a default export function!");
219 }
220 }
221 else {
222 throw new Error("Custom template file " + helperName + " does not exists in path: " + resolvedPath);
223 }
224 });
225 templateConfig = {
226 inputType: graphql_codegen_core_1.EInputType.PROJECT,
227 templates: templates,
228 flattenTypes: config.flattenTypes,
229 primitives: config.primitives,
230 customHelpers: resolvedHelpers_1
231 };
232 }
233 spinner_1.default.succeed();
234 relevantEnvVars = Object.keys(process.env)
235 .filter(function (name) { return name.startsWith('CODEGEN_'); })
236 .reduce(function (prev, name) {
237 var cleanName = name
238 .replace('CODEGEN_', '')
239 .toLowerCase()
240 .replace(/[-_]+/g, ' ')
241 .replace(/[^\w\s]/g, '')
242 .replace(/ (.)/g, function (res) { return res.toUpperCase(); })
243 .replace(/ /g, '');
244 var value = process.env[name];
245 if (value === 'true') {
246 value = true;
247 }
248 else if (value === 'false') {
249 value = false;
250 }
251 prev[cleanName] = value;
252 return prev;
253 }, {});
254 addToSchema = [];
255 if (graphql_codegen_core_1.isGeneratorConfig(templateConfig)) {
256 templateConfig.config = __assign({}, (config && config.generatorConfig ? config.generatorConfig || {} : {}), (options && options['templateConfig'] ? options['templateConfig'] : {}), (relevantEnvVars || {}));
257 if (templateConfig.deprecationNote) {
258 spinner_1.default.warn("Template " + template + " is deprecated: " + templateConfig.deprecationNote);
259 }
260 if (templateConfig.addToSchema) {
261 asArray = Array.isArray(templateConfig.addToSchema)
262 ? templateConfig.addToSchema
263 : [templateConfig.addToSchema];
264 addToSchema = asArray.map(function (extension) { return (typeof extension === 'string' ? graphql_1.parse(extension) : extension); });
265 }
266 if (config) {
267 if ('flattenTypes' in config) {
268 templateConfig.flattenTypes = config.flattenTypes;
269 }
270 if ('primitives' in config) {
271 templateConfig.primitives = __assign({}, templateConfig.primitives, config.primitives);
272 }
273 }
274 }
275 executeGeneration = function () { return __awaiter(_this, void 0, void 0, function () {
276 var loadSchema, schemas, allSchemas, graphQlSchema, _i, addToSchema_1, extension, context, hasDocuments, foundDocumentsPaths, documentsFiles, loadDocumentErrors, errorCount, _a, loadDocumentErrors_1, loadDocumentError, _b, _c, graphQLError, transformedDocuments;
277 var _this = this;
278 return __generator(this, function (_d) {
279 switch (_d.label) {
280 case 0:
281 loadSchema = function (pointToSchema) { return __awaiter(_this, void 0, void 0, function () {
282 var _i, schemaHandlers_1, handler;
283 return __generator(this, function (_a) {
284 switch (_a.label) {
285 case 0:
286 _i = 0, schemaHandlers_1 = schemaHandlers;
287 _a.label = 1;
288 case 1:
289 if (!(_i < schemaHandlers_1.length)) return [3 /*break*/, 4];
290 handler = schemaHandlers_1[_i];
291 return [4 /*yield*/, handler.canHandle(pointToSchema)];
292 case 2:
293 if (_a.sent()) {
294 return [2 /*return*/, handler.handle(pointToSchema, options)];
295 }
296 _a.label = 3;
297 case 3:
298 _i++;
299 return [3 /*break*/, 1];
300 case 4: throw new Error('Could not handle schema');
301 }
302 });
303 }); };
304 schemas = [];
305 try {
306 spinner_1.default.log('Loading remote schema');
307 graphql_codegen_core_1.debugLog("[executeWithOptions] Schema is being loaded ");
308 schemas.push(loadSchema(schema));
309 spinner_1.default.succeed();
310 }
311 catch (e) {
312 graphql_codegen_core_1.debugLog("[executeWithOptions] Failed to load schema", e);
313 exports.cliError('Invalid --schema provided, please use a path to local file, HTTP endpoint or a glob expression!');
314 }
315 if (clientSchema) {
316 spinner_1.default.log('Loading client schema');
317 try {
318 graphql_codegen_core_1.debugLog("[executeWithOptions] Client Schema is being loaded ");
319 schemas.push(loadSchema(clientSchema));
320 spinner_1.default.succeed();
321 }
322 catch (e) {
323 graphql_codegen_core_1.debugLog("[executeWithOptions] Failed to load client schema", e);
324 exports.cliError('Invalid --clientSchema provided, please use a path to local file or a glob expression!');
325 }
326 }
327 return [4 /*yield*/, Promise.all(schemas)];
328 case 1:
329 allSchemas = _d.sent();
330 graphQlSchema = allSchemas.length === 1
331 ? allSchemas[0]
332 : graphql_tools_1.makeExecutableSchema({ typeDefs: epoxy_1.mergeGraphQLSchemas(allSchemas), allowUndefinedInResolve: true });
333 if (addToSchema && addToSchema.length > 0) {
334 for (_i = 0, addToSchema_1 = addToSchema; _i < addToSchema_1.length; _i++) {
335 extension = addToSchema_1[_i];
336 graphql_codegen_core_1.debugLog("Extending GraphQL Schema with: ", extension);
337 graphQlSchema = graphql_1.extendSchema(graphQlSchema, extension);
338 }
339 }
340 if (process.env.VERBOSE !== undefined) {
341 graphql_codegen_core_1.getLogger().info("GraphQL Schema is: ", graphQlSchema);
342 }
343 context = graphql_codegen_core_1.schemaToTemplateContext(graphQlSchema);
344 graphql_codegen_core_1.debugLog("[executeWithOptions] Schema template context build, the result is: ");
345 Object.keys(context).forEach(function (key) {
346 if (Array.isArray(context[key])) {
347 graphql_codegen_core_1.debugLog("Total of " + key + ": " + context[key].length);
348 }
349 });
350 hasDocuments = documents.length;
351 if (hasDocuments) {
352 spinner_1.default.log('Loading documents');
353 }
354 return [4 /*yield*/, documents_glob_1.documentsFromGlobs(documents)];
355 case 2:
356 foundDocumentsPaths = _d.sent();
357 return [4 /*yield*/, document_loader_1.loadDocumentsSources(foundDocumentsPaths)];
358 case 3:
359 documentsFiles = _d.sent();
360 loadDocumentErrors = validate_documents_1.validateGraphQlDocuments(graphQlSchema, documentsFiles);
361 if (loadDocumentErrors.length > 0) {
362 errorCount = 0;
363 for (_a = 0, loadDocumentErrors_1 = loadDocumentErrors; _a < loadDocumentErrors_1.length; _a++) {
364 loadDocumentError = loadDocumentErrors_1[_a];
365 for (_b = 0, _c = loadDocumentError.errors; _b < _c.length; _b++) {
366 graphQLError = _c[_b];
367 graphql_codegen_core_1.getLogger().error("[" + loadDocumentError.filePath + "] GraphQL Error: " + graphQLError.message);
368 errorCount++;
369 }
370 }
371 exports.cliError("Found " + errorCount + " errors when validating your GraphQL documents against schema!", !options.watch);
372 }
373 transformedDocuments = graphql_codegen_core_1.transformDocumentsFiles(graphQlSchema, documentsFiles);
374 if (hasDocuments) {
375 spinner_1.default.succeed();
376 }
377 spinner_1.default.log("Compiling template: " + template);
378 return [2 /*return*/, graphql_codegen_compiler_1.compileTemplate(templateConfig, context, [transformedDocuments], {
379 generateSchema: generateSchema,
380 generateDocuments: generateDocuments
381 })];
382 }
383 });
384 }); };
385 normalizeOutput = function (item) {
386 var resultName = item.filename;
387 if (!path.isAbsolute(resultName)) {
388 var resolved = path.resolve(process.cwd(), out);
389 if (fs.existsSync(resolved)) {
390 var stats = fs.lstatSync(resolved);
391 if (stats.isDirectory()) {
392 resultName = path.resolve(resolved, item.filename);
393 }
394 else if (stats.isFile()) {
395 resultName = resolved;
396 }
397 }
398 else {
399 if (out.endsWith('/')) {
400 resultName = path.resolve(resolved, item.filename);
401 }
402 else {
403 resultName = resolved;
404 }
405 }
406 }
407 var resultDir = path.dirname(resultName);
408 mkdirp.sync(resultDir);
409 return {
410 content: item.content,
411 filename: resultName
412 };
413 };
414 return [4 /*yield*/, executeGeneration()];
415 case 1: return [2 /*return*/, (_a.sent()).map(normalizeOutput)];
416 }
417 });
418}); };
419//# sourceMappingURL=codegen.js.map
\No newline at end of file