UNPKG

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