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