UNPKG

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