1 | "use strict";
|
2 | var __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 | };
|
10 | var __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 | };
|
18 | var __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 | };
|
45 | var _this = this;
|
46 | Object.defineProperty(exports, "__esModule", { value: true });
|
47 | var commander = require("commander");
|
48 | var path = require("path");
|
49 | var fs = require("fs");
|
50 | var mkdirp = require("mkdirp");
|
51 | var validUrl = require("valid-url");
|
52 | var introspection_from_file_1 = require("./loaders/introspection-from-file");
|
53 | var introspection_from_url_1 = require("./loaders/introspection-from-url");
|
54 | var schema_from_export_1 = require("./loaders/schema-from-export");
|
55 | var documents_glob_1 = require("./utils/documents-glob");
|
56 | var document_loader_1 = require("./loaders/document-loader");
|
57 | var templates_scanner_1 = require("./loaders/templates-scanner");
|
58 | var graphql_codegen_compiler_1 = require("graphql-codegen-compiler");
|
59 | var graphql_codegen_core_1 = require("graphql-codegen-core");
|
60 | process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
|
61 | function collect(val, memo) {
|
62 | memo.push(val);
|
63 | return memo;
|
64 | }
|
65 | exports.initCLI = function (args) {
|
66 | commander
|
67 | .usage('gql-gen [options]')
|
68 | .option('-f, --file <filePath>', 'Parse local GraphQL introspection JSON file')
|
69 | .option('-u, --url <graphql-endpoint>', 'Parse remote GraphQL endpoint as introspection file')
|
70 | .option('-e, --export <export-file>', 'Path to a JavaScript (es5/6) file that exports (as default export) your `GraphQLSchema` object')
|
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 | .arguments('<options> [documents...]')
|
82 | .parse(args);
|
83 | return commander;
|
84 | };
|
85 | exports.cliError = function (err) {
|
86 | graphql_codegen_core_1.logger.error(err);
|
87 | process.exit(1);
|
88 | return;
|
89 | };
|
90 | exports.validateCliOptions = function (options) {
|
91 | var schema = options.schema;
|
92 | var file = options.file;
|
93 | var url = options.url;
|
94 | var fsExport = options.export;
|
95 | var template = options.template;
|
96 | var project = options.project;
|
97 | if (!schema && !file && !url && !fsExport) {
|
98 | exports.cliError('Please specify one of --schema, --file, --url or --export flags!');
|
99 | }
|
100 | if (file) {
|
101 | graphql_codegen_core_1.logger.warn("--file is deprecated, use --schema instead.");
|
102 | }
|
103 | else if (url) {
|
104 | graphql_codegen_core_1.logger.warn("--url is deprecated, use --schema instead.");
|
105 | }
|
106 | else if (fsExport) {
|
107 | graphql_codegen_core_1.logger.warn("--export is deprecated, use --schema instead.");
|
108 | }
|
109 | if (!template && !project) {
|
110 | exports.cliError('Please specify language/platform, using --template flag, or specify --project to generate with custom project!');
|
111 | }
|
112 | };
|
113 | exports.executeWithOptions = function (options) { return __awaiter(_this, void 0, void 0, function () {
|
114 | var schema, file, url, fsExport, documents, template, project, gqlGenConfigFilePath, out, headers, generateSchema, generateDocuments, modulesToRequire, schemaExportPromise, extension, graphQlSchema, context, transformedDocuments, _a, _b, _c, templateConfig, localFilePath, localFileExists, templateFromExport, configPath, config, templates, resolvedHelpers_1, relevantEnvVars;
|
115 | return __generator(this, function (_d) {
|
116 | switch (_d.label) {
|
117 | case 0:
|
118 | exports.validateCliOptions(options);
|
119 | schema = options.schema;
|
120 | file = options.file;
|
121 | url = options.url;
|
122 | fsExport = options.export;
|
123 | documents = options.args || [];
|
124 | template = options.template;
|
125 | project = options.project;
|
126 | gqlGenConfigFilePath = options.config || './gql-gen.json';
|
127 | out = options.out || './';
|
128 | headers = options.header;
|
129 | generateSchema = !options.skipSchema;
|
130 | generateDocuments = !options.skipDocuments;
|
131 | modulesToRequire = options.require || [];
|
132 | modulesToRequire.forEach(function (mod) { return require(mod); });
|
133 | if (schema) {
|
134 | if (validUrl.isUri(schema)) {
|
135 | schemaExportPromise = introspection_from_url_1.introspectionFromUrl(schema, headers).then(graphql_codegen_core_1.introspectionToGraphQLSchema);
|
136 | }
|
137 | else if (fs.existsSync(schema)) {
|
138 | extension = path.extname(schema);
|
139 | if (!extension) {
|
140 | exports.cliError('Invalid --schema local path provided, unable to find the file extension!');
|
141 | }
|
142 | else if (extension === '.json') {
|
143 | schemaExportPromise = introspection_from_file_1.introspectionFromFile(schema).then(graphql_codegen_core_1.introspectionToGraphQLSchema);
|
144 | }
|
145 | else {
|
146 | schemaExportPromise = schema_from_export_1.schemaFromExport(schema);
|
147 | }
|
148 | }
|
149 | else {
|
150 | exports.cliError('Invalid --schema provided, please use a path to local file or HTTP endpoint');
|
151 | }
|
152 | }
|
153 | else if (file) {
|
154 | schemaExportPromise = introspection_from_file_1.introspectionFromFile(file).then(graphql_codegen_core_1.introspectionToGraphQLSchema);
|
155 | }
|
156 | else if (url) {
|
157 | schemaExportPromise = introspection_from_url_1.introspectionFromUrl(url, headers).then(graphql_codegen_core_1.introspectionToGraphQLSchema);
|
158 | }
|
159 | else if (fsExport) {
|
160 | schemaExportPromise = schema_from_export_1.schemaFromExport(fsExport);
|
161 | }
|
162 | if (!schemaExportPromise) {
|
163 | exports.cliError('Invalid --schema provided, please use a path to local file or HTTP endpoint');
|
164 | }
|
165 | return [4 , schemaExportPromise];
|
166 | case 1:
|
167 | graphQlSchema = _d.sent();
|
168 | if (process.env.VERBOSE !== undefined) {
|
169 | graphql_codegen_core_1.logger.info("GraphQL Schema is: ", graphQlSchema);
|
170 | }
|
171 | context = graphql_codegen_core_1.schemaToTemplateContext(graphQlSchema);
|
172 | graphql_codegen_core_1.debugLog("[executeWithOptions] Schema template context build, the result is: ");
|
173 | Object.keys(context).forEach(function (key) {
|
174 | if (Array.isArray(context[key])) {
|
175 | graphql_codegen_core_1.debugLog("Total of " + key + ": " + context[key].length);
|
176 | }
|
177 | });
|
178 | _a = graphql_codegen_core_1.transformDocument;
|
179 | _b = [graphQlSchema];
|
180 | _c = document_loader_1.loadDocumentsSources;
|
181 | return [4 , documents_glob_1.documentsFromGlobs(documents)];
|
182 | case 2:
|
183 | transformedDocuments = _a.apply(void 0, _b.concat([_c.apply(void 0, [_d.sent()])]));
|
184 | templateConfig = null;
|
185 | if (template && template !== '') {
|
186 | graphql_codegen_core_1.debugLog("[executeWithOptions] using template: " + template);
|
187 |
|
188 | if (template === 'ts' ||
|
189 | template === 'ts-single' ||
|
190 | template === 'typescript' ||
|
191 | template === 'typescript-single') {
|
192 | template = 'graphql-codegen-typescript-template';
|
193 | }
|
194 | else if (template === 'ts-multiple' || template === 'typescript-multiple') {
|
195 | template = 'graphql-codegen-typescript-template-multiple';
|
196 | }
|
197 | localFilePath = path.resolve(process.cwd(), template);
|
198 | localFileExists = fs.existsSync(localFilePath);
|
199 | templateFromExport = require(localFileExists ? localFilePath : template);
|
200 | if (!templateFromExport) {
|
201 | throw new Error("Unknown codegen template: " + template + ", please make sure it's installed using npm/Yarn!");
|
202 | }
|
203 | else {
|
204 | templateConfig = templateFromExport.default || templateFromExport.config || templateFromExport;
|
205 | }
|
206 | }
|
207 | graphql_codegen_core_1.debugLog("[executeWithOptions] using project: " + project);
|
208 | configPath = path.resolve(process.cwd(), gqlGenConfigFilePath);
|
209 | config = null;
|
210 | if (fs.existsSync(configPath)) {
|
211 | graphql_codegen_core_1.logger.info('Loading config file from: ', configPath);
|
212 | config = JSON.parse(fs.readFileSync(configPath).toString());
|
213 | graphql_codegen_core_1.debugLog("[executeWithOptions] Got project config JSON: ", config);
|
214 | }
|
215 | if (project && project !== '') {
|
216 | if (config === null) {
|
217 | throw new Error("To use project feature, please specify --config path or create gql-gen.json in your project root!");
|
218 | }
|
219 | templates = templates_scanner_1.scanForTemplatesInPath(project, graphql_codegen_compiler_1.ALLOWED_CUSTOM_TEMPLATE_EXT);
|
220 | resolvedHelpers_1 = {};
|
221 | Object.keys(config.customHelpers || {}).map(function (helperName) {
|
222 | var filePath = config.customHelpers[helperName];
|
223 | var resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
|
224 | if (fs.existsSync(resolvedPath)) {
|
225 | var requiredFile = require(resolvedPath);
|
226 | if (requiredFile && requiredFile && typeof requiredFile === 'function') {
|
227 | resolvedHelpers_1[helperName] = requiredFile;
|
228 | }
|
229 | else {
|
230 | throw new Error("Custom template file " + resolvedPath + " does not have a default export function!");
|
231 | }
|
232 | }
|
233 | else {
|
234 | throw new Error("Custom template file " + helperName + " does not exists in path: " + resolvedPath);
|
235 | }
|
236 | });
|
237 | templateConfig = {
|
238 | inputType: graphql_codegen_core_1.EInputType.PROJECT,
|
239 | templates: templates,
|
240 | flattenTypes: config.flattenTypes,
|
241 | primitives: config.primitives,
|
242 | customHelpers: resolvedHelpers_1
|
243 | };
|
244 | }
|
245 | relevantEnvVars = Object.keys(process.env)
|
246 | .filter(function (name) { return name.startsWith('CODEGEN_'); })
|
247 | .reduce(function (prev, name) {
|
248 | var cleanName = name
|
249 | .replace('CODEGEN_', '')
|
250 | .toLowerCase()
|
251 | .replace(/[-_]+/g, ' ')
|
252 | .replace(/[^\w\s]/g, '')
|
253 | .replace(/ (.)/g, function (res) { return res.toUpperCase(); })
|
254 | .replace(/ /g, '');
|
255 | var value = process.env[name];
|
256 | if (value === 'true') {
|
257 | value = true;
|
258 | }
|
259 | else if (value === 'false') {
|
260 | value = false;
|
261 | }
|
262 | prev[cleanName] = value;
|
263 | return prev;
|
264 | }, {});
|
265 | if (graphql_codegen_core_1.isGeneratorConfig(templateConfig)) {
|
266 | templateConfig.config = __assign({}, (config && config.generatorConfig ? config.generatorConfig || {} : {}), (relevantEnvVars || {}));
|
267 | if (templateConfig.deprecationNote) {
|
268 | graphql_codegen_core_1.logger.warn("Template " + template + " is deprecated: " + templateConfig.deprecationNote);
|
269 | }
|
270 | }
|
271 | return [4 , graphql_codegen_compiler_1.compileTemplate(templateConfig, context, [transformedDocuments], {
|
272 | generateSchema: generateSchema,
|
273 | generateDocuments: generateDocuments
|
274 | })];
|
275 | case 3: return [2 , (_d.sent()).map(function (item) {
|
276 | var resultName = item.filename;
|
277 | if (!path.isAbsolute(resultName)) {
|
278 | var resolved = path.resolve(process.cwd(), out);
|
279 | if (fs.existsSync(resolved)) {
|
280 | var stats = fs.lstatSync(resolved);
|
281 | if (stats.isDirectory()) {
|
282 | resultName = path.resolve(resolved, item.filename);
|
283 | }
|
284 | else if (stats.isFile()) {
|
285 | resultName = resolved;
|
286 | }
|
287 | }
|
288 | else {
|
289 | if (out.endsWith('/')) {
|
290 | resultName = path.resolve(resolved, item.filename);
|
291 | }
|
292 | else {
|
293 | resultName = resolved;
|
294 | }
|
295 | }
|
296 | }
|
297 | var resultDir = path.dirname(resultName);
|
298 | mkdirp.sync(resultDir);
|
299 | return {
|
300 | content: item.content,
|
301 | filename: resultName
|
302 | };
|
303 | })];
|
304 | }
|
305 | });
|
306 | }); };
|
307 |
|
\ | No newline at end of file |