UNPKG

17.3 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 commander = require("commander");
51var path = require("path");
52var fs = require("fs");
53var mkdirp = require("mkdirp");
54var documents_glob_1 = require("./utils/documents-glob");
55var document_loader_1 = require("./loaders/documents/document-loader");
56var templates_scanner_1 = require("./loaders/template/templates-scanner");
57var graphql_codegen_compiler_1 = require("graphql-codegen-compiler");
58var graphql_codegen_core_1 = require("graphql-codegen-core");
59var introspection_from_file_1 = require("./loaders/schema/introspection-from-file");
60var introspection_from_url_1 = require("./loaders/schema/introspection-from-url");
61var schema_from_typedefs_1 = require("./loaders/schema/schema-from-typedefs");
62var schema_from_export_1 = require("./loaders/schema/schema-from-export");
63process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
64function collect(val, memo) {
65 memo.push(val);
66 return memo;
67}
68exports.initCLI = function (args) {
69 commander
70 .usage('gql-gen [options]')
71 .option('-s, --schema <path>', 'Path to GraphQL schema: local JSON file, GraphQL endpoint, local file that exports GraphQLSchema/AST/JSON')
72 .option('-h, --header [header]', 'Header to add to the introspection HTTP request when using --url/--schema with url', collect, [])
73 .option('-t, --template <template-name>', 'Language/platform name templates, or a name of NPM modules that `export default` GqlGenConfig object')
74 .option('-p, --project <project-path>', 'Project path(s) to scan for custom template files')
75 .option('--config <json-file>', 'Codegen configuration file, defaults to: ./gql-gen.json')
76 .option('-m, --skip-schema', 'Generates only client side documents, without server side schema types')
77 .option('-c, --skip-documents', 'Generates only server side schema types, without client side documents')
78 .option('-o, --out <path>', 'Output file(s) path', String, './')
79 .option('-r, --require [require]', 'module to preload (option can be repeated)', collect, [])
80 .option('-ow, --no-overwrite', 'Skip file writing if the output file(s) already exists in path')
81 .option('-w, --watch', 'Watch for changes and execute generation automatically')
82 .arguments('<options> [documents...]')
83 .parse(args);
84 return commander;
85};
86exports.cliError = function (err) {
87 graphql_codegen_core_1.logger.error(err);
88 process.exit(1);
89 return;
90};
91exports.validateCliOptions = function (options) {
92 var schema = options.schema;
93 var template = options.template;
94 var project = options.project;
95 if (!schema) {
96 exports.cliError('Flag --schema is missing!');
97 }
98 if (!template && !project) {
99 exports.cliError('Please specify language/platform, using --template flag, or specify --project to generate with custom project!');
100 }
101};
102var schemaHandlers = [
103 new introspection_from_url_1.IntrospectionFromUrlLoader(),
104 new introspection_from_file_1.IntrospectionFromFileLoader(),
105 new schema_from_typedefs_1.SchemaFromTypedefs(),
106 new schema_from_export_1.SchemaFromExport()
107];
108exports.executeWithOptions = function (options) { return __awaiter(_this, void 0, void 0, function () {
109 var schema, documents, template, project, gqlGenConfigFilePath, out, generateSchema, generateDocuments, modulesToRequire, templateConfig, localFilePath, localFileExists, templateFromExport, configPath, config, templates, resolvedHelpers_1, relevantEnvVars, executeGeneration, normalizeOutput;
110 var _this = this;
111 return __generator(this, function (_a) {
112 switch (_a.label) {
113 case 0:
114 exports.validateCliOptions(options);
115 schema = options.schema;
116 documents = options.args || [];
117 template = options.template;
118 project = options.project;
119 gqlGenConfigFilePath = options.config || './gql-gen.json';
120 out = options.out || './';
121 generateSchema = !options.skipSchema;
122 generateDocuments = !options.skipDocuments;
123 modulesToRequire = options.require || [];
124 modulesToRequire.forEach(function (mod) { return require(mod); });
125 templateConfig = null;
126 if (template && template !== '') {
127 graphql_codegen_core_1.debugLog("[executeWithOptions] using template: " + template);
128 // Backward compatibility for older versions
129 if (template === 'ts' ||
130 template === 'ts-single' ||
131 template === 'typescript' ||
132 template === 'typescript-single') {
133 template = 'graphql-codegen-typescript-template';
134 }
135 else if (template === 'ts-multiple' || template === 'typescript-multiple') {
136 template = 'graphql-codegen-typescript-template-multiple';
137 }
138 localFilePath = path.resolve(process.cwd(), template);
139 localFileExists = fs.existsSync(localFilePath);
140 templateFromExport = require(localFileExists ? localFilePath : template);
141 if (!templateFromExport) {
142 throw new Error("Unknown codegen template: " + template + ", please make sure it's installed using npm/Yarn!");
143 }
144 else {
145 templateConfig = templateFromExport.default || templateFromExport.config || templateFromExport;
146 }
147 }
148 graphql_codegen_core_1.debugLog("[executeWithOptions] using project: " + project);
149 configPath = path.resolve(process.cwd(), gqlGenConfigFilePath);
150 config = null;
151 if (fs.existsSync(configPath)) {
152 graphql_codegen_core_1.logger.info('Loading config file from: ', configPath);
153 config = JSON.parse(fs.readFileSync(configPath).toString());
154 graphql_codegen_core_1.debugLog("[executeWithOptions] Got project config JSON: ", config);
155 }
156 if (project && project !== '') {
157 if (config === null) {
158 throw new Error("To use project feature, please specify --config path or create gql-gen.json in your project root!");
159 }
160 templates = templates_scanner_1.scanForTemplatesInPath(project, graphql_codegen_compiler_1.ALLOWED_CUSTOM_TEMPLATE_EXT);
161 resolvedHelpers_1 = {};
162 Object.keys(config.customHelpers || {}).map(function (helperName) {
163 var filePath = config.customHelpers[helperName];
164 var resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
165 if (fs.existsSync(resolvedPath)) {
166 var requiredFile = require(resolvedPath);
167 if (requiredFile && requiredFile && typeof requiredFile === 'function') {
168 resolvedHelpers_1[helperName] = requiredFile;
169 }
170 else {
171 throw new Error("Custom template file " + resolvedPath + " does not have a default export function!");
172 }
173 }
174 else {
175 throw new Error("Custom template file " + helperName + " does not exists in path: " + resolvedPath);
176 }
177 });
178 templateConfig = {
179 inputType: graphql_codegen_core_1.EInputType.PROJECT,
180 templates: templates,
181 flattenTypes: config.flattenTypes,
182 primitives: config.primitives,
183 customHelpers: resolvedHelpers_1
184 };
185 }
186 relevantEnvVars = Object.keys(process.env)
187 .filter(function (name) { return name.startsWith('CODEGEN_'); })
188 .reduce(function (prev, name) {
189 var cleanName = name
190 .replace('CODEGEN_', '')
191 .toLowerCase()
192 .replace(/[-_]+/g, ' ')
193 .replace(/[^\w\s]/g, '')
194 .replace(/ (.)/g, function (res) { return res.toUpperCase(); })
195 .replace(/ /g, '');
196 var value = process.env[name];
197 if (value === 'true') {
198 value = true;
199 }
200 else if (value === 'false') {
201 value = false;
202 }
203 prev[cleanName] = value;
204 return prev;
205 }, {});
206 if (graphql_codegen_core_1.isGeneratorConfig(templateConfig)) {
207 templateConfig.config = __assign({}, (config && config.generatorConfig ? config.generatorConfig || {} : {}), (relevantEnvVars || {}));
208 if (templateConfig.deprecationNote) {
209 graphql_codegen_core_1.logger.warn("Template " + template + " is deprecated: " + templateConfig.deprecationNote);
210 }
211 }
212 executeGeneration = function () { return __awaiter(_this, void 0, void 0, function () {
213 var schemaExportPromise, _i, schemaHandlers_1, handler, graphQlSchema, context, transformedDocuments, _a, _b, _c;
214 return __generator(this, function (_d) {
215 switch (_d.label) {
216 case 0:
217 schemaExportPromise = null;
218 _i = 0, schemaHandlers_1 = schemaHandlers;
219 _d.label = 1;
220 case 1:
221 if (!(_i < schemaHandlers_1.length)) return [3 /*break*/, 4];
222 handler = schemaHandlers_1[_i];
223 return [4 /*yield*/, handler.canHandle(schema)];
224 case 2:
225 if (_d.sent()) {
226 schemaExportPromise = handler.handle(schema, options);
227 return [3 /*break*/, 4];
228 }
229 _d.label = 3;
230 case 3:
231 _i++;
232 return [3 /*break*/, 1];
233 case 4:
234 if (!schemaExportPromise) {
235 exports.cliError('Invalid --schema provided, please use a path to local file, HTTP endpoint or a glob expression!');
236 }
237 return [4 /*yield*/, schemaExportPromise];
238 case 5:
239 graphQlSchema = _d.sent();
240 if (process.env.VERBOSE !== undefined) {
241 graphql_codegen_core_1.logger.info("GraphQL Schema is: ", graphQlSchema);
242 }
243 context = graphql_codegen_core_1.schemaToTemplateContext(graphQlSchema);
244 graphql_codegen_core_1.debugLog("[executeWithOptions] Schema template context build, the result is: ");
245 Object.keys(context).forEach(function (key) {
246 if (Array.isArray(context[key])) {
247 graphql_codegen_core_1.debugLog("Total of " + key + ": " + context[key].length);
248 }
249 });
250 _a = graphql_codegen_core_1.transformDocument;
251 _b = [graphQlSchema];
252 _c = document_loader_1.loadDocumentsSources;
253 return [4 /*yield*/, documents_glob_1.documentsFromGlobs(documents)];
254 case 6:
255 transformedDocuments = _a.apply(void 0, _b.concat([_c.apply(void 0, [_d.sent()])]));
256 return [2 /*return*/, graphql_codegen_compiler_1.compileTemplate(templateConfig, context, [transformedDocuments], {
257 generateSchema: generateSchema,
258 generateDocuments: generateDocuments
259 })];
260 }
261 });
262 }); };
263 normalizeOutput = function (item) {
264 var resultName = item.filename;
265 if (!path.isAbsolute(resultName)) {
266 var resolved = path.resolve(process.cwd(), out);
267 if (fs.existsSync(resolved)) {
268 var stats = fs.lstatSync(resolved);
269 if (stats.isDirectory()) {
270 resultName = path.resolve(resolved, item.filename);
271 }
272 else if (stats.isFile()) {
273 resultName = resolved;
274 }
275 }
276 else {
277 if (out.endsWith('/')) {
278 resultName = path.resolve(resolved, item.filename);
279 }
280 else {
281 resultName = resolved;
282 }
283 }
284 }
285 var resultDir = path.dirname(resultName);
286 mkdirp.sync(resultDir);
287 return {
288 content: item.content,
289 filename: resultName
290 };
291 };
292 return [4 /*yield*/, executeGeneration()];
293 case 1: return [2 /*return*/, (_a.sent()).map(normalizeOutput)];
294 }
295 });
296}); };
297//# sourceMappingURL=codegen.js.map
\No newline at end of file