UNPKG

33.5 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7const path = require('path');
8const minimatch = _interopDefault(require('minimatch'));
9const cosmiconfig = require('cosmiconfig');
10const loadTs = _interopDefault(require('@endemolshinegroup/cosmiconfig-typescript-loader'));
11const cosmiconfigTomlLoader = require('cosmiconfig-toml-loader');
12const stringEnvInterpolation = require('string-env-interpolation');
13const graphqlFileLoader = require('@graphql-tools/graphql-file-loader');
14const urlLoader = require('@graphql-tools/url-loader');
15const jsonFileLoader = require('@graphql-tools/json-file-loader');
16const load = require('@graphql-tools/load');
17const merge = require('@graphql-tools/merge');
18const graphql = require('graphql');
19
20/*! *****************************************************************************
21Copyright (c) Microsoft Corporation.
22
23Permission to use, copy, modify, and/or distribute this software for any
24purpose with or without fee is hereby granted.
25
26THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
27REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
28AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
29INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
30LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
31OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
32PERFORMANCE OF THIS SOFTWARE.
33***************************************************************************** */
34/* global Reflect, Promise */
35
36var extendStatics = function(d, b) {
37 extendStatics = Object.setPrototypeOf ||
38 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
39 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
40 return extendStatics(d, b);
41};
42
43function __extends(d, b) {
44 if (typeof b !== "function" && b !== null)
45 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
46 extendStatics(d, b);
47 function __() { this.constructor = d; }
48 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
49}
50
51var __assign = function() {
52 __assign = Object.assign || function __assign(t) {
53 for (var s, i = 1, n = arguments.length; i < n; i++) {
54 s = arguments[i];
55 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
56 }
57 return t;
58 };
59 return __assign.apply(this, arguments);
60};
61
62function __awaiter(thisArg, _arguments, P, generator) {
63 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
64 return new (P || (P = Promise))(function (resolve, reject) {
65 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
66 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
67 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
68 step((generator = generator.apply(thisArg, _arguments || [])).next());
69 });
70}
71
72function __generator(thisArg, body) {
73 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
74 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
75 function verb(n) { return function (v) { return step([n, v]); }; }
76 function step(op) {
77 if (f) throw new TypeError("Generator is already executing.");
78 while (_) try {
79 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;
80 if (y = 0, t) op = [op[0] & 2, t.value];
81 switch (op[0]) {
82 case 0: case 1: t = op; break;
83 case 4: _.label++; return { value: op[1], done: false };
84 case 5: _.label++; y = op[1]; op = [0]; continue;
85 case 7: op = _.ops.pop(); _.trys.pop(); continue;
86 default:
87 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
88 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
89 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
90 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
91 if (t[2]) _.ops.pop();
92 _.trys.pop(); continue;
93 }
94 op = body.call(thisArg, _);
95 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
96 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
97 }
98}
99
100function ExtendableBuiltin(cls) {
101 function ExtendableBuiltin() {
102 cls.apply(this, arguments);
103 }
104 ExtendableBuiltin.prototype = Object.create(cls.prototype);
105 Object.setPrototypeOf(ExtendableBuiltin, cls);
106 return ExtendableBuiltin;
107}
108function composeMessage() {
109 var lines = [];
110 for (var _i = 0; _i < arguments.length; _i++) {
111 lines[_i] = arguments[_i];
112 }
113 return lines.join('\n');
114}
115var ConfigNotFoundError = /** @class */ (function (_super) {
116 __extends(ConfigNotFoundError, _super);
117 function ConfigNotFoundError(message) {
118 var _this = _super.call(this, message) || this;
119 _this.name = _this.constructor.name;
120 _this.message = message;
121 return _this;
122 }
123 return ConfigNotFoundError;
124}(ExtendableBuiltin(Error)));
125var ConfigEmptyError = /** @class */ (function (_super) {
126 __extends(ConfigEmptyError, _super);
127 function ConfigEmptyError(message) {
128 var _this = _super.call(this, message) || this;
129 _this.name = _this.constructor.name;
130 _this.message = message;
131 return _this;
132 }
133 return ConfigEmptyError;
134}(ExtendableBuiltin(Error)));
135var ConfigInvalidError = /** @class */ (function (_super) {
136 __extends(ConfigInvalidError, _super);
137 function ConfigInvalidError(message) {
138 var _this = _super.call(this, message) || this;
139 _this.name = _this.constructor.name;
140 _this.message = message;
141 return _this;
142 }
143 return ConfigInvalidError;
144}(ExtendableBuiltin(Error)));
145var ProjectNotFoundError = /** @class */ (function (_super) {
146 __extends(ProjectNotFoundError, _super);
147 function ProjectNotFoundError(message) {
148 var _this = _super.call(this, message) || this;
149 _this.name = _this.constructor.name;
150 _this.message = message;
151 return _this;
152 }
153 return ProjectNotFoundError;
154}(ExtendableBuiltin(Error)));
155var LoadersMissingError = /** @class */ (function (_super) {
156 __extends(LoadersMissingError, _super);
157 function LoadersMissingError(message) {
158 var _this = _super.call(this, message) || this;
159 _this.name = _this.constructor.name;
160 _this.message = message;
161 return _this;
162 }
163 return LoadersMissingError;
164}(ExtendableBuiltin(Error)));
165var LoaderNoResultError = /** @class */ (function (_super) {
166 __extends(LoaderNoResultError, _super);
167 function LoaderNoResultError(message) {
168 var _this = _super.call(this, message) || this;
169 _this.name = _this.constructor.name;
170 _this.message = message;
171 return _this;
172 }
173 return LoaderNoResultError;
174}(ExtendableBuiltin(Error)));
175var ExtensionMissingError = /** @class */ (function (_super) {
176 __extends(ExtensionMissingError, _super);
177 function ExtensionMissingError(message) {
178 var _this = _super.call(this, message) || this;
179 _this.name = _this.constructor.name;
180 _this.message = message;
181 return _this;
182 }
183 return ExtensionMissingError;
184}(ExtendableBuiltin(Error)));
185
186var legacySearchPlaces = [
187 '.graphqlconfig',
188 '.graphqlconfig.json',
189 '.graphqlconfig.yaml',
190 '.graphqlconfig.yml',
191];
192function isLegacyConfig(filepath) {
193 filepath = filepath.toLowerCase();
194 return legacySearchPlaces.some(function (name) { return filepath.endsWith(name); });
195}
196function transformContent(content) {
197 return stringEnvInterpolation.env(content);
198}
199var createCustomLoader = function (loader) {
200 return function (filepath, content) {
201 return loader(filepath, transformContent(content));
202 };
203};
204function createCosmiConfig(moduleName, _a) {
205 var legacy = _a.legacy;
206 var options = prepareCosmiconfig(moduleName, {
207 legacy: legacy,
208 });
209 return cosmiconfig.cosmiconfig(moduleName, options);
210}
211function createCosmiConfigSync(moduleName, _a) {
212 var legacy = _a.legacy;
213 var options = prepareCosmiconfig(moduleName, {
214 legacy: legacy,
215 });
216 return cosmiconfig.cosmiconfigSync(moduleName, options);
217}
218function prepareCosmiconfig(moduleName, _a) {
219 var legacy = _a.legacy;
220 var loadYaml = createCustomLoader(cosmiconfig.defaultLoaders['.yaml']);
221 var loadTomlCustom = createCustomLoader(cosmiconfigTomlLoader.loadToml);
222 var loadJson = createCustomLoader(cosmiconfig.defaultLoaders['.json']);
223 var searchPlaces = [
224 "#.config.ts",
225 "#.config.js",
226 '#.config.json',
227 '#.config.yaml',
228 '#.config.yml',
229 '#.config.toml',
230 '.#rc',
231 '.#rc.ts',
232 '.#rc.js',
233 '.#rc.json',
234 '.#rc.yml',
235 '.#rc.yaml',
236 '.#rc.toml',
237 'package.json',
238 ];
239 if (legacy) {
240 searchPlaces.push.apply(searchPlaces, legacySearchPlaces);
241 }
242 // We need to wrap loaders in order to access and transform file content (as string)
243 // Cosmiconfig has transform option but at this point config is not a string but an object
244 return {
245 searchPlaces: searchPlaces.map(function (place) { return place.replace('#', moduleName); }),
246 loaders: {
247 '.ts': loadTs,
248 '.js': cosmiconfig.defaultLoaders['.js'],
249 '.json': loadJson,
250 '.yaml': loadYaml,
251 '.yml': loadYaml,
252 '.toml': loadTomlCustom,
253 noExt: loadYaml,
254 },
255 };
256}
257
258var cwd = typeof process !== 'undefined' ? process.cwd() : undefined;
259function findConfig(_a) {
260 var _b = _a.rootDir, rootDir = _b === void 0 ? cwd : _b, _c = _a.legacy, legacy = _c === void 0 ? true : _c, configName = _a.configName;
261 return __awaiter(this, void 0, void 0, function () {
262 var _d;
263 var _e;
264 return __generator(this, function (_f) {
265 switch (_f.label) {
266 case 0:
267 validate({ rootDir: rootDir });
268 _d = resolve;
269 _e = {
270 rootDir: rootDir
271 };
272 return [4 /*yield*/, createCosmiConfig(configName, { legacy: legacy }).search(rootDir)];
273 case 1: return [2 /*return*/, _d.apply(void 0, [(_e.result = _f.sent(),
274 _e)])];
275 }
276 });
277 });
278}
279function findConfigSync(_a) {
280 var _b = _a.rootDir, rootDir = _b === void 0 ? cwd : _b, _c = _a.legacy, legacy = _c === void 0 ? true : _c, configName = _a.configName;
281 validate({ rootDir: rootDir });
282 return resolve({
283 rootDir: rootDir,
284 result: createCosmiConfigSync(configName, { legacy: legacy }).search(rootDir),
285 });
286}
287//
288function validate(_a) {
289 var rootDir = _a.rootDir;
290 if (!rootDir) {
291 throw new Error("Defining a root directory is required");
292 }
293}
294function resolve(_a) {
295 var result = _a.result, rootDir = _a.rootDir;
296 if (!result) {
297 throw new ConfigNotFoundError(composeMessage("GraphQL Config file is not available in the provided config directory: " + rootDir, "Please check the config directory."));
298 }
299 if (result.isEmpty) {
300 throw new ConfigEmptyError(composeMessage("GraphQL Config file is empty.", "Please check " + result.filepath));
301 }
302 return {
303 config: result.config,
304 filepath: result.filepath,
305 };
306}
307
308function getConfig(_a) {
309 var filepath = _a.filepath, configName = _a.configName, _b = _a.legacy, legacy = _b === void 0 ? true : _b;
310 return __awaiter(this, void 0, void 0, function () {
311 var _c;
312 var _d;
313 return __generator(this, function (_e) {
314 switch (_e.label) {
315 case 0:
316 validate$1({ filepath: filepath });
317 _c = resolve$1;
318 _d = {};
319 return [4 /*yield*/, createCosmiConfig(configName, { legacy: legacy }).load(filepath)];
320 case 1: return [2 /*return*/, _c.apply(void 0, [(_d.result = _e.sent(),
321 _d.filepath = filepath,
322 _d)])];
323 }
324 });
325 });
326}
327function getConfigSync(_a) {
328 var filepath = _a.filepath, configName = _a.configName, _b = _a.legacy, legacy = _b === void 0 ? true : _b;
329 validate$1({ filepath: filepath });
330 return resolve$1({
331 result: createCosmiConfigSync(configName, { legacy: legacy }).load(filepath),
332 filepath: filepath,
333 });
334}
335//
336function resolve$1(_a) {
337 var result = _a.result, filepath = _a.filepath;
338 if (!result) {
339 throw new ConfigNotFoundError(composeMessage("GraphQL Config file is not available: " + filepath, "Please check the config filepath."));
340 }
341 if (result.isEmpty) {
342 throw new ConfigEmptyError(composeMessage("GraphQL Config file is empty.", "Please check " + result.filepath));
343 }
344 return {
345 config: result.config,
346 filepath: result.filepath,
347 };
348}
349function validate$1(_a) {
350 var filepath = _a.filepath;
351 if (!filepath) {
352 throw new Error("Defining a file path is required");
353 }
354}
355
356function isMultipleProjectConfig(config) {
357 return typeof config.projects === 'object';
358}
359function isSingleProjectConfig(config) {
360 return typeof config.schema !== 'undefined';
361}
362function isLegacyProjectConfig(config) {
363 return (typeof config.schemaPath !== 'undefined' ||
364 typeof config.includes !== 'undefined' ||
365 typeof config.excludes !== 'undefined');
366}
367function useMiddleware(fns) {
368 return function (input) {
369 if (fns.length) {
370 return fns.reduce(function (obj, cb) { return cb(obj); }, input);
371 }
372 return input;
373 };
374}
375
376var GraphQLProjectConfig = /** @class */ (function () {
377 function GraphQLProjectConfig(_a) {
378 var filepath = _a.filepath, name = _a.name, config = _a.config, extensionsRegistry = _a.extensionsRegistry;
379 this.filepath = filepath;
380 this.dirpath = path.dirname(filepath);
381 this.name = name;
382 if (isLegacyProjectConfig(config)) {
383 this.extensions = config.extensions || {};
384 this.schema = config.schemaPath;
385 this.include = config.includes;
386 this.exclude = config.excludes;
387 this.isLegacy = true;
388 }
389 else {
390 this.extensions = config.extensions || {};
391 this.schema = config.schema;
392 this.documents = config.documents;
393 this.include = config.include;
394 this.exclude = config.exclude;
395 this.isLegacy = false;
396 }
397 this._extensionsRegistry = extensionsRegistry;
398 }
399 GraphQLProjectConfig.prototype.hasExtension = function (name) {
400 return !!this.extensions[name];
401 };
402 GraphQLProjectConfig.prototype.extension = function (name) {
403 if (this.isLegacy) {
404 var extension_1 = this.extensions[name];
405 if (!extension_1) {
406 throw new ExtensionMissingError("Project " + this.name + " is missing " + name + " extension");
407 }
408 return extension_1;
409 }
410 var extension = this._extensionsRegistry.get(name);
411 if (!extension) {
412 throw new ExtensionMissingError("Project " + this.name + " is missing " + name + " extension");
413 }
414 return __assign(__assign({}, this.extensions[name]), { schema: this.schema, documents: this.documents, include: this.include, exclude: this.exclude });
415 };
416 GraphQLProjectConfig.prototype.getSchema = function (out) {
417 return __awaiter(this, void 0, void 0, function () {
418 return __generator(this, function (_a) {
419 return [2 /*return*/, this.loadSchema(this.schema, out)];
420 });
421 });
422 };
423 GraphQLProjectConfig.prototype.getSchemaSync = function (out) {
424 return this.loadSchemaSync(this.schema, out);
425 };
426 // Get Documents
427 GraphQLProjectConfig.prototype.getDocuments = function () {
428 return __awaiter(this, void 0, void 0, function () {
429 return __generator(this, function (_a) {
430 if (!this.documents) {
431 return [2 /*return*/, []];
432 }
433 return [2 /*return*/, this.loadDocuments(this.documents)];
434 });
435 });
436 };
437 GraphQLProjectConfig.prototype.getDocumentsSync = function () {
438 if (!this.documents) {
439 return [];
440 }
441 return this.loadDocumentsSync(this.documents);
442 };
443 GraphQLProjectConfig.prototype.loadSchema = function (pointer, out, options) {
444 return __awaiter(this, void 0, void 0, function () {
445 return __generator(this, function (_a) {
446 return [2 /*return*/, this._extensionsRegistry.loaders.schema.loadSchema(pointer, out, options)];
447 });
448 });
449 };
450 GraphQLProjectConfig.prototype.loadSchemaSync = function (pointer, out, options) {
451 return this._extensionsRegistry.loaders.schema.loadSchemaSync(pointer, out, options);
452 };
453 // Load Documents
454 GraphQLProjectConfig.prototype.loadDocuments = function (pointer, options) {
455 return __awaiter(this, void 0, void 0, function () {
456 return __generator(this, function (_a) {
457 if (!pointer) {
458 return [2 /*return*/, []];
459 }
460 return [2 /*return*/, this._extensionsRegistry.loaders.documents.loadDocuments(pointer, options)];
461 });
462 });
463 };
464 GraphQLProjectConfig.prototype.loadDocumentsSync = function (pointer, options) {
465 if (!pointer) {
466 return [];
467 }
468 return this._extensionsRegistry.loaders.documents.loadDocumentsSync(pointer, options);
469 };
470 // Rest
471 GraphQLProjectConfig.prototype.match = function (filepath) {
472 var _this = this;
473 var isSchemaOrDocument = [this.schema, this.documents].some(function (pointer) {
474 return match(filepath, _this.dirpath, pointer);
475 });
476 if (isSchemaOrDocument) {
477 return true;
478 }
479 var isExcluded = this.exclude
480 ? match(filepath, this.dirpath, this.exclude)
481 : false;
482 if (isExcluded) {
483 return false;
484 }
485 var isIncluded = this.include
486 ? match(filepath, this.dirpath, this.include)
487 : false;
488 if (isIncluded) {
489 return true;
490 }
491 return false;
492 };
493 return GraphQLProjectConfig;
494}());
495// XXX: it works but uses nodejs - expose normalization of file and dir paths in config
496function match(filepath, dirpath, pointer) {
497 if (!pointer) {
498 return false;
499 }
500 if (Array.isArray(pointer)) {
501 return pointer.some(function (p) { return match(filepath, dirpath, p); });
502 }
503 if (typeof pointer === 'string') {
504 var normalizedFilepath = path.normalize(path.isAbsolute(filepath) ? path.relative(dirpath, filepath) : filepath);
505 return minimatch(normalizedFilepath, path.normalize(pointer), { dot: true });
506 }
507 if (typeof pointer === 'object') {
508 return match(filepath, dirpath, Object.keys(pointer)[0]);
509 }
510 return false;
511}
512
513var LoadersRegistry = /** @class */ (function () {
514 function LoadersRegistry(_a) {
515 var cwd = _a.cwd;
516 this._loaders = new Set();
517 this._middlewares = [];
518 this.cwd = cwd;
519 }
520 LoadersRegistry.prototype.register = function (loader) {
521 this._loaders.add(loader);
522 };
523 LoadersRegistry.prototype.override = function (loaders) {
524 this._loaders = new Set(loaders);
525 };
526 LoadersRegistry.prototype.use = function (middleware) {
527 this._middlewares.push(middleware);
528 };
529 LoadersRegistry.prototype.loadTypeDefs = function (pointer, options) {
530 return __awaiter(this, void 0, void 0, function () {
531 return __generator(this, function (_a) {
532 return [2 /*return*/, load.loadTypedefs(pointer, __assign({ loaders: Array.from(this._loaders), cwd: this.cwd }, options))];
533 });
534 });
535 };
536 LoadersRegistry.prototype.loadTypeDefsSync = function (pointer, options) {
537 return load.loadTypedefsSync(pointer, this.createOptions(options));
538 };
539 LoadersRegistry.prototype.loadDocuments = function (pointer, options) {
540 return __awaiter(this, void 0, void 0, function () {
541 return __generator(this, function (_a) {
542 return [2 /*return*/, load.loadDocuments(pointer, this.createOptions(options))];
543 });
544 });
545 };
546 LoadersRegistry.prototype.loadDocumentsSync = function (pointer, options) {
547 return load.loadDocumentsSync(pointer, this.createOptions(options));
548 };
549 LoadersRegistry.prototype.loadSchema = function (pointer, out, options) {
550 return __awaiter(this, void 0, void 0, function () {
551 var loadSchemaOptions, schemaDoc, _a;
552 return __generator(this, function (_b) {
553 switch (_b.label) {
554 case 0:
555 out = out || 'GraphQLSchema';
556 loadSchemaOptions = this.createOptions(options);
557 if (out === 'GraphQLSchema' && !this._middlewares.length) {
558 return [2 /*return*/, load.loadSchema(pointer, loadSchemaOptions)];
559 }
560 _a = this.transformSchemaSources;
561 return [4 /*yield*/, load.loadTypedefs(pointer, __assign({ filterKinds: load.OPERATION_KINDS }, loadSchemaOptions))];
562 case 1:
563 schemaDoc = _a.apply(this, [_b.sent()]);
564 // TODO: TS screams about `out` not being compatible with SchemaOutput
565 return [2 /*return*/, this.castSchema(schemaDoc, out)];
566 }
567 });
568 });
569 };
570 LoadersRegistry.prototype.loadSchemaSync = function (pointer, out, options) {
571 out = out || 'GraphQLSchema';
572 var loadSchemaOptions = this.createOptions(options);
573 if (out === 'GraphQLSchema' && !this._middlewares.length) {
574 return load.loadSchemaSync(pointer, loadSchemaOptions);
575 }
576 var schemaDoc = this.transformSchemaSources(load.loadTypedefsSync(pointer, __assign({ filterKinds: load.OPERATION_KINDS }, loadSchemaOptions)));
577 return this.castSchema(schemaDoc, out);
578 };
579 LoadersRegistry.prototype.createOptions = function (options) {
580 return __assign({ loaders: Array.from(this._loaders), cwd: this.cwd }, options);
581 };
582 LoadersRegistry.prototype.transformSchemaSources = function (sources) {
583 var documents = sources.map(function (source) { return source.document; });
584 var document = merge.mergeTypeDefs(documents);
585 return useMiddleware(this._middlewares)(document);
586 };
587 LoadersRegistry.prototype.castSchema = function (doc, out) {
588 if (out === 'DocumentNode') {
589 return doc;
590 }
591 if (out === 'GraphQLSchema') {
592 return graphql.buildASTSchema(doc);
593 }
594 return graphql.print(doc);
595 };
596 return LoadersRegistry;
597}());
598
599var GraphQLExtensionsRegistry = /** @class */ (function () {
600 function GraphQLExtensionsRegistry(_a) {
601 var cwd = _a.cwd;
602 this._extensions = {};
603 this.loaders = {
604 schema: new LoadersRegistry({ cwd: cwd }),
605 documents: new LoadersRegistry({ cwd: cwd }),
606 };
607 // schema
608 this.loaders.schema.register(new graphqlFileLoader.GraphQLFileLoader());
609 this.loaders.schema.register(new urlLoader.UrlLoader());
610 this.loaders.schema.register(new jsonFileLoader.JsonFileLoader());
611 // documents
612 this.loaders.documents.register(new graphqlFileLoader.GraphQLFileLoader());
613 }
614 GraphQLExtensionsRegistry.prototype.register = function (extensionFn) {
615 var extension = extensionFn({
616 logger: {},
617 loaders: this.loaders,
618 });
619 this._extensions[extension.name] = extension;
620 };
621 GraphQLExtensionsRegistry.prototype.has = function (extensionName) {
622 return !!this._extensions[extensionName];
623 };
624 GraphQLExtensionsRegistry.prototype.get = function (extensionName) {
625 return this._extensions[extensionName];
626 };
627 GraphQLExtensionsRegistry.prototype.names = function () {
628 return Object.keys(this._extensions);
629 };
630 GraphQLExtensionsRegistry.prototype.forEach = function (cb) {
631 for (var extensionName in this._extensions) {
632 cb(this._extensions[extensionName]);
633 }
634 };
635 return GraphQLExtensionsRegistry;
636}());
637
638var EndpointsExtension = function () {
639 return {
640 name: 'endpoints',
641 };
642};
643
644var cwd$1 = typeof process !== 'undefined' ? process.cwd() : undefined;
645var defaultConfigName = 'graphql';
646var defaultLoadConfigOptions = {
647 rootDir: cwd$1,
648 extensions: [],
649 throwOnMissing: true,
650 throwOnEmpty: true,
651 configName: defaultConfigName,
652 legacy: true,
653};
654function loadConfig(options) {
655 return __awaiter(this, void 0, void 0, function () {
656 var _a, filepath, configName, rootDir, extensions, throwOnEmpty, throwOnMissing, legacy, found, _b, error_1;
657 return __generator(this, function (_c) {
658 switch (_c.label) {
659 case 0:
660 _a = __assign(__assign({}, defaultLoadConfigOptions), options), filepath = _a.filepath, configName = _a.configName, rootDir = _a.rootDir, extensions = _a.extensions, throwOnEmpty = _a.throwOnEmpty, throwOnMissing = _a.throwOnMissing, legacy = _a.legacy;
661 _c.label = 1;
662 case 1:
663 _c.trys.push([1, 6, , 7]);
664 if (!filepath) return [3 /*break*/, 3];
665 return [4 /*yield*/, getConfig({
666 filepath: filepath,
667 configName: configName,
668 legacy: legacy,
669 })];
670 case 2:
671 _b = _c.sent();
672 return [3 /*break*/, 5];
673 case 3: return [4 /*yield*/, findConfig({
674 rootDir: rootDir,
675 configName: configName,
676 legacy: legacy,
677 })];
678 case 4:
679 _b = _c.sent();
680 _c.label = 5;
681 case 5:
682 found = _b;
683 return [2 /*return*/, new GraphQLConfig(found, extensions)];
684 case 6:
685 error_1 = _c.sent();
686 return [2 /*return*/, handleError(error_1, { throwOnMissing: throwOnMissing, throwOnEmpty: throwOnEmpty })];
687 case 7: return [2 /*return*/];
688 }
689 });
690 });
691}
692function loadConfigSync(options) {
693 var _a = __assign(__assign({}, defaultLoadConfigOptions), options), filepath = _a.filepath, configName = _a.configName, rootDir = _a.rootDir, extensions = _a.extensions, throwOnEmpty = _a.throwOnEmpty, throwOnMissing = _a.throwOnMissing, legacy = _a.legacy;
694 try {
695 var found = filepath
696 ? getConfigSync({
697 filepath: filepath,
698 configName: configName,
699 legacy: legacy,
700 })
701 : findConfigSync({
702 rootDir: rootDir,
703 configName: configName,
704 legacy: legacy,
705 });
706 return new GraphQLConfig(found, extensions);
707 }
708 catch (error) {
709 return handleError(error, { throwOnMissing: throwOnMissing, throwOnEmpty: throwOnEmpty });
710 }
711}
712function handleError(error, options) {
713 if ((!options.throwOnMissing && error instanceof ConfigNotFoundError) ||
714 (!options.throwOnEmpty && error instanceof ConfigEmptyError)) {
715 return;
716 }
717 throw error;
718}
719var GraphQLConfig = /** @class */ (function () {
720 function GraphQLConfig(raw, extensions) {
721 var _this = this;
722 this._rawConfig = raw.config;
723 this.filepath = raw.filepath;
724 this.dirpath = path.dirname(raw.filepath);
725 this.extensions = new GraphQLExtensionsRegistry({ cwd: this.dirpath });
726 // Register Endpoints
727 this.extensions.register(EndpointsExtension);
728 extensions.forEach(function (extension) {
729 _this.extensions.register(extension);
730 });
731 this.projects = {};
732 if (isMultipleProjectConfig(this._rawConfig)) {
733 for (var projectName in this._rawConfig.projects) {
734 var config = this._rawConfig.projects[projectName];
735 this.projects[projectName] = new GraphQLProjectConfig({
736 filepath: this.filepath,
737 name: projectName,
738 config: config,
739 extensionsRegistry: this.extensions,
740 });
741 }
742 }
743 else if (isSingleProjectConfig(this._rawConfig)) {
744 this.projects['default'] = new GraphQLProjectConfig({
745 filepath: this.filepath,
746 name: 'default',
747 config: this._rawConfig,
748 extensionsRegistry: this.extensions,
749 });
750 }
751 else if (isLegacyProjectConfig(this._rawConfig)) {
752 this.projects['default'] = new GraphQLProjectConfig({
753 filepath: this.filepath,
754 name: 'default',
755 config: this._rawConfig,
756 extensionsRegistry: this.extensions,
757 });
758 }
759 }
760 GraphQLConfig.prototype.getProject = function (name) {
761 if (!name) {
762 return this.getDefault();
763 }
764 var project = this.projects[name];
765 if (!project) {
766 throw new ProjectNotFoundError("Project '" + name + "' not found");
767 }
768 return project;
769 };
770 GraphQLConfig.prototype.getProjectForFile = function (filepath) {
771 // Looks for a project that includes the file or the file is a part of schema or documents
772 for (var projectName in this.projects) {
773 if (this.projects.hasOwnProperty(projectName)) {
774 var project = this.projects[projectName];
775 if (project.match(filepath)) {
776 return project;
777 }
778 }
779 }
780 // The file doesn't match any of the project
781 // Looks for a first project that has no `include` and `exclude`
782 for (var projectName in this.projects) {
783 if (this.projects.hasOwnProperty(projectName)) {
784 var project = this.projects[projectName];
785 if (!project.include && !project.exclude) {
786 return project;
787 }
788 }
789 }
790 throw new ProjectNotFoundError("File '" + filepath + "' doesn't match any project");
791 };
792 GraphQLConfig.prototype.getDefault = function () {
793 return this.getProject('default');
794 };
795 GraphQLConfig.prototype.isLegacy = function () {
796 return isLegacyConfig(this.filepath);
797 };
798 return GraphQLConfig;
799}());
800
801exports.ConfigEmptyError = ConfigEmptyError;
802exports.ConfigInvalidError = ConfigInvalidError;
803exports.ConfigNotFoundError = ConfigNotFoundError;
804exports.ExtensionMissingError = ExtensionMissingError;
805exports.GraphQLConfig = GraphQLConfig;
806exports.GraphQLProjectConfig = GraphQLProjectConfig;
807exports.LoaderNoResultError = LoaderNoResultError;
808exports.LoadersMissingError = LoadersMissingError;
809exports.ProjectNotFoundError = ProjectNotFoundError;
810exports.composeMessage = composeMessage;
811exports.loadConfig = loadConfig;
812exports.loadConfigSync = loadConfigSync;