UNPKG

16.1 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
7function _interopNamespace(e) {
8 if (e && e.__esModule) { return e; } else {
9 var n = {};
10 if (e) {
11 Object.keys(e).forEach(function (k) {
12 var d = Object.getOwnPropertyDescriptor(e, k);
13 Object.defineProperty(n, k, d.get ? d : {
14 enumerable: true,
15 get: function () {
16 return e[k];
17 }
18 });
19 });
20 }
21 n['default'] = e;
22 return n;
23 }
24}
25
26const fetchache = require('fetchache');
27const crossFetch = require('cross-fetch');
28const isUrl = _interopDefault(require('is-url'));
29const jsYaml = require('js-yaml');
30const path = require('path');
31const fs = require('fs');
32const stringInterpolation = require('@ardatan/string-interpolation');
33const dateFns = require('date-fns');
34const objectHash = _interopDefault(require('object-hash'));
35const graphql = require('graphql');
36const utils = require('@graphql-tools/utils');
37const flatstr = _interopDefault(require('flatstr'));
38const lru = _interopDefault(require('tiny-lru'));
39const graphqlJit = require('graphql-jit');
40
41const { readFile, stat } = fs.promises || {};
42function getCachedFetch(cache) {
43 return fetchache.fetchFactory({
44 fetch: crossFetch.fetch,
45 Request: crossFetch.Request,
46 Response: crossFetch.Response,
47 cache,
48 });
49}
50async function readFileOrUrlWithCache(filePathOrUrl, cache, config) {
51 if (isUrl(filePathOrUrl)) {
52 return readUrlWithCache(filePathOrUrl, cache, config);
53 }
54 else {
55 return readFileWithCache(filePathOrUrl, cache, config);
56 }
57}
58async function readFileWithCache(filePath, cache, config) {
59 const { allowUnknownExtensions, cwd, fallbackFormat } = config || {};
60 const actualPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd || process.cwd(), filePath);
61 const cachedObj = await cache.get(actualPath);
62 const stats = await stat(actualPath);
63 if (cachedObj) {
64 if (stats.mtimeMs <= cachedObj.mtimeMs) {
65 return cachedObj.result;
66 }
67 }
68 let result = await readFile(actualPath, 'utf-8');
69 if (/json$/.test(filePath)) {
70 result = JSON.parse(result);
71 }
72 else if (/yaml$/.test(filePath) || /yml$/.test(filePath)) {
73 result = jsYaml.load(result);
74 }
75 else if (fallbackFormat) {
76 switch (fallbackFormat) {
77 case 'json':
78 result = JSON.parse(result);
79 break;
80 case 'yaml':
81 result = jsYaml.load(result);
82 break;
83 }
84 }
85 else if (!allowUnknownExtensions) {
86 throw new Error(`Failed to parse JSON/YAML. Ensure file '${filePath}' has ` +
87 `the correct extension (i.e. '.json', '.yaml', or '.yml).`);
88 }
89 cache.set(filePath, { result, mtimeMs: stats.mtimeMs });
90 return result;
91}
92async function readUrlWithCache(path, cache, config) {
93 var _a;
94 const { allowUnknownExtensions, fallbackFormat } = config || {};
95 const fetch = (config === null || config === void 0 ? void 0 : config.fetch) || getCachedFetch(cache);
96 const response = await fetch(path, config);
97 const contentType = ((_a = response.headers) === null || _a === void 0 ? void 0 : _a.get('content-type')) || '';
98 const responseText = await response.text();
99 if (/json$/.test(path) || contentType.startsWith('application/json') || fallbackFormat === 'json') {
100 return JSON.parse(responseText);
101 }
102 else if (/yaml$/.test(path) ||
103 /yml$/.test(path) ||
104 contentType.includes('yaml') ||
105 contentType.includes('yml') ||
106 fallbackFormat === 'yaml') {
107 return jsYaml.load(responseText);
108 }
109 else if (!allowUnknownExtensions) {
110 throw new Error(`Failed to parse JSON/YAML. Ensure URL '${path}' has ` +
111 `the correct extension (i.e. '.json', '.yaml', or '.yml) or mime type in the response headers.`);
112 }
113 return responseText;
114}
115
116const stringInterpolator = new stringInterpolation.Interpolator({
117 delimiter: ['{', '}'],
118});
119stringInterpolator.addAlias('typeName', 'info.parentType.name');
120stringInterpolator.addAlias('type', 'info.parentType.name');
121stringInterpolator.addAlias('parentType', 'info.parentType.name');
122stringInterpolator.addAlias('fieldName', 'info.fieldName');
123stringInterpolator.registerModifier('date', (formatStr) => dateFns.format(new Date(), formatStr));
124stringInterpolator.registerModifier('hash', (value) => objectHash(value, { ignoreUnknown: true }));
125
126async function loadFromModuleExportExpression(expression, options) {
127 if (typeof expression !== 'string') {
128 return expression;
129 }
130 const { defaultExportName, cwd } = options || {};
131 const [modulePath, exportName = defaultExportName] = expression.split('#');
132 const mod = await tryImport(modulePath, cwd);
133 if (exportName === 'default' || !exportName) {
134 return mod.default || mod;
135 }
136 else {
137 return mod[exportName] || (mod.default && mod.default[exportName]);
138 }
139}
140async function tryImport(modulePath, cwd) {
141 try {
142 return await new Promise(function (resolve) { resolve(_interopNamespace(require(modulePath))); });
143 }
144 catch (e1) {
145 if (!path.isAbsolute(modulePath)) {
146 try {
147 const absoluteModulePath = path.isAbsolute(modulePath) ? modulePath : path.join(cwd || process.cwd(), modulePath);
148 return await new Promise(function (resolve) { resolve(_interopNamespace(require(absoluteModulePath))); });
149 }
150 catch (e2) {
151 if (e2.message.includes('Cannot find module')) {
152 throw e1;
153 }
154 else {
155 throw e2;
156 }
157 }
158 }
159 throw e1;
160 }
161}
162function loadFromModuleExportExpressionSync(expression, options) {
163 if (typeof expression !== 'string') {
164 return expression;
165 }
166 const { defaultExportName, cwd } = options || {};
167 const [modulePath, exportName = defaultExportName] = expression.split('#');
168 const mod = tryImportSync(modulePath, cwd);
169 if (exportName === 'default' || !exportName) {
170 return mod.default || mod;
171 }
172 else {
173 return mod[exportName] || (mod.default && mod.default[exportName]);
174 }
175}
176function tryImportSync(modulePath, cwd) {
177 try {
178 return require(modulePath);
179 }
180 catch (e1) {
181 if (!path.isAbsolute(modulePath)) {
182 try {
183 const absoluteModulePath = path.isAbsolute(modulePath) ? modulePath : path.join(cwd || process.cwd(), modulePath);
184 return require(absoluteModulePath);
185 }
186 catch (e2) {
187 if (e2.message.includes('Cannot find module')) {
188 throw e1;
189 }
190 else {
191 throw e2;
192 }
193 }
194 }
195 throw e1;
196 }
197}
198
199(function (ArgType) {
200 ArgType["ID"] = "ID";
201 ArgType["String"] = "String";
202 ArgType["Boolean"] = "Boolean";
203 ArgType["Float"] = "Float";
204 ArgType["Int"] = "Int";
205})(exports.ArgType || (exports.ArgType = {}));
206function getInputTypeFromTypeName(typeName) {
207 if (graphql.isInputType(typeName)) {
208 return typeName;
209 }
210 else {
211 switch (typeName) {
212 case exports.ArgType.ID:
213 return graphql.GraphQLID;
214 case exports.ArgType.String:
215 return graphql.GraphQLString;
216 case exports.ArgType.Boolean:
217 return graphql.GraphQLBoolean;
218 case exports.ArgType.Float:
219 return graphql.GraphQLFloat;
220 case exports.ArgType.Int:
221 return graphql.GraphQLInt;
222 }
223 }
224}
225function parseInterpolationStrings(interpolationStrings, argTypeMap) {
226 const interpolationKeys = interpolationStrings.reduce((keys, str) => [...keys, ...(str ? stringInterpolator.parseRules(str).map((match) => match.key) : [])], []);
227 const args = {};
228 const contextVariables = [];
229 for (const interpolationKey of interpolationKeys) {
230 const interpolationKeyParts = interpolationKey.split('.');
231 const varName = interpolationKeyParts[interpolationKeyParts.length - 1];
232 if (interpolationKeyParts[0] === 'args') {
233 const argType = argTypeMap && varName in argTypeMap ? getInputTypeFromTypeName(argTypeMap[varName]) : graphql.GraphQLID;
234 args[varName] = {
235 type: argType,
236 };
237 }
238 else if (interpolationKeyParts[0] === 'context') {
239 contextVariables.push(varName);
240 }
241 }
242 return {
243 args,
244 contextVariables,
245 };
246}
247function getInterpolatedStringFactory(nonInterpolatedString) {
248 return resolverData => stringInterpolator.parse(nonInterpolatedString, resolverData);
249}
250function getInterpolatedHeadersFactory(nonInterpolatedHeaders = {}) {
251 return resolverData => {
252 const headers = new crossFetch.Headers();
253 for (const headerName in nonInterpolatedHeaders) {
254 const headerValue = nonInterpolatedHeaders[headerName];
255 if (headerValue) {
256 headers.set(headerName, stringInterpolator.parse(headerValue, resolverData));
257 }
258 }
259 return headers;
260 };
261}
262function getHeadersObject(headers) {
263 const headersObj = {};
264 headers.forEach((value, key) => {
265 headersObj[key] = value;
266 });
267 return headersObj;
268}
269
270function withCancel(asyncIteratorLike, onCancel) {
271 const asyncIterator = asyncIteratorLike[Symbol.asyncIterator]();
272 if (!asyncIterator.return) {
273 asyncIterator.return = () => Promise.resolve({ value: undefined, done: true });
274 }
275 const savedReturn = asyncIterator.return.bind(asyncIterator);
276 asyncIterator.return = () => {
277 onCancel();
278 return savedReturn();
279 };
280 return asyncIterator;
281}
282
283function extractResolvers(schema) {
284 const allResolvers = utils.getResolversFromSchema(schema);
285 const filteredResolvers = {};
286 for (const prop in allResolvers) {
287 if (!prop.startsWith('_')) {
288 filteredResolvers[prop] = allResolvers[prop];
289 }
290 }
291 return filteredResolvers;
292}
293
294function ensureDocumentNode(document) {
295 return typeof document === 'string' ? graphql.parse(document) : document;
296}
297
298function groupTransforms(transforms) {
299 const wrapTransforms = [];
300 const noWrapTransforms = [];
301 transforms === null || transforms === void 0 ? void 0 : transforms.forEach(transform => {
302 if (transform.noWrap) {
303 noWrapTransforms.push(transform);
304 }
305 else {
306 wrapTransforms.push(transform);
307 }
308 });
309 return { wrapTransforms, noWrapTransforms };
310}
311
312function applySchemaTransforms(originalWrappingSchema, subschemaConfig, transformedSchema, transforms) {
313 return transforms.reduce((schema, transform) => 'transformSchema' in transform ? transform.transformSchema(schema, subschemaConfig, transformedSchema) : schema, originalWrappingSchema);
314}
315function applyRequestTransforms(originalRequest, delegationContext, transformationContext, transforms) {
316 transformationContext.contextMap = transformationContext.contextMap || new WeakMap();
317 const contextMap = transformationContext.contextMap;
318 transforms === null || transforms === void 0 ? void 0 : transforms.forEach(transform => {
319 if (!contextMap.has(transform)) {
320 contextMap.set(transform, {
321 nextIndex: 0,
322 paths: {},
323 });
324 }
325 });
326 return transforms.reduceRight((request, transform) => 'transformRequest' in transform
327 ? transform.transformRequest(request, delegationContext, contextMap.get(transform))
328 : request, originalRequest);
329}
330function applyResultTransforms(originalResult, delegationContext, transformationContext, transforms) {
331 const contextMap = transformationContext.contextMap;
332 return transforms.reduceRight((result, transform) => 'transformResult' in transform
333 ? transform.transformResult(result, delegationContext, contextMap.get(transform))
334 : result, originalResult);
335}
336
337function flatString(str) {
338 return flatstr(str);
339}
340function jsonFlatStringify(data, replacer, space) {
341 return flatString(JSON.stringify(data, replacer, space));
342}
343
344const { stat: stat$1, writeFile: fsWriteFile, readFile: readFile$1, mkdir: fsMkdir } = fs.promises || {};
345async function pathExists(path) {
346 if (!path) {
347 return false;
348 }
349 try {
350 await stat$1(path);
351 return true;
352 }
353 catch (e) {
354 if (e.toString().includes('ENOENT')) {
355 return false;
356 }
357 else {
358 throw e;
359 }
360 }
361}
362function readJSONSync(path) {
363 const fileContent = fs.readFileSync(path, 'utf-8');
364 return JSON.parse(fileContent);
365}
366async function readJSON(path) {
367 const fileContent = await readFile$1(path, 'utf-8');
368 return JSON.parse(fileContent);
369}
370function writeJSON(path, data, replacer, space) {
371 const stringified = jsonFlatStringify(data, replacer, space);
372 return writeFile(path, stringified, 'utf-8');
373}
374const writeFile = async (path$1, ...args) => {
375 if (typeof path$1 === 'string') {
376 const containingDir = path.dirname(path$1);
377 if (!(await pathExists(containingDir))) {
378 await mkdir(containingDir);
379 }
380 }
381 return fsWriteFile(path$1, ...args);
382};
383async function mkdir(path, options = { recursive: true }) {
384 const ifExists = await pathExists(path);
385 if (!ifExists) {
386 await fsMkdir(path, options);
387 }
388}
389
390const globalLruCache = lru();
391
392const jitExecutorFactory = (schema, prefix) => ({ document, variables, context }, operationName, rootValue) => {
393 const documentStr = graphql.print(document);
394 const cacheKey = [prefix, documentStr, operationName].join('_');
395 if (!globalLruCache.has(cacheKey)) {
396 const compiledQuery = graphqlJit.compileQuery(schema, document, operationName, {
397 disableLeafSerialization: true,
398 customJSONSerializer: true,
399 });
400 globalLruCache.set(cacheKey, compiledQuery);
401 }
402 const cachedQuery = globalLruCache.get(cacheKey);
403 if (graphqlJit.isCompiledQuery(cachedQuery)) {
404 return cachedQuery.query(rootValue, context, variables);
405 }
406 return cachedQuery;
407};
408
409exports.isUrl = isUrl;
410exports.applyRequestTransforms = applyRequestTransforms;
411exports.applyResultTransforms = applyResultTransforms;
412exports.applySchemaTransforms = applySchemaTransforms;
413exports.ensureDocumentNode = ensureDocumentNode;
414exports.extractResolvers = extractResolvers;
415exports.flatString = flatString;
416exports.getCachedFetch = getCachedFetch;
417exports.getHeadersObject = getHeadersObject;
418exports.getInputTypeFromTypeName = getInputTypeFromTypeName;
419exports.getInterpolatedHeadersFactory = getInterpolatedHeadersFactory;
420exports.getInterpolatedStringFactory = getInterpolatedStringFactory;
421exports.globalLruCache = globalLruCache;
422exports.groupTransforms = groupTransforms;
423exports.jitExecutorFactory = jitExecutorFactory;
424exports.jsonFlatStringify = jsonFlatStringify;
425exports.loadFromModuleExportExpression = loadFromModuleExportExpression;
426exports.loadFromModuleExportExpressionSync = loadFromModuleExportExpressionSync;
427exports.mkdir = mkdir;
428exports.parseInterpolationStrings = parseInterpolationStrings;
429exports.pathExists = pathExists;
430exports.readFileOrUrlWithCache = readFileOrUrlWithCache;
431exports.readFileWithCache = readFileWithCache;
432exports.readJSON = readJSON;
433exports.readJSONSync = readJSONSync;
434exports.readUrlWithCache = readUrlWithCache;
435exports.stringInterpolator = stringInterpolator;
436exports.withCancel = withCancel;
437exports.writeFile = writeFile;
438exports.writeJSON = writeJSON;
439//# sourceMappingURL=index.cjs.js.map