@graphql-mesh/utils 1.0.0-alpha-3fc47d119.0 → 1.0.0-alpha-20230420181317-a95037648

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/cjs/apply-transforms.js +35 -0
  2. package/cjs/defaultImportFn.js +57 -0
  3. package/cjs/extract-resolvers.js +23 -0
  4. package/cjs/fileURLToPath.js +50 -0
  5. package/cjs/fs-operations.js +65 -0
  6. package/cjs/getHeadersObj.js +61 -0
  7. package/cjs/global-lru-cache.js +9 -0
  8. package/cjs/group-transforms.js +17 -0
  9. package/cjs/index.js +20 -0
  10. package/cjs/load-from-module-export-expression.js +29 -0
  11. package/cjs/logger.js +127 -0
  12. package/cjs/package.json +1 -0
  13. package/cjs/parseAndPrintWithCache.js +42 -0
  14. package/cjs/pubsub.js +57 -0
  15. package/cjs/read-file-or-url.js +132 -0
  16. package/cjs/resolve-additional-resolvers.js +350 -0
  17. package/cjs/sanitize-name-for-graphql.js +96 -0
  18. package/cjs/with-cancel.js +34 -0
  19. package/cjs/with-cookies.js +18 -0
  20. package/cjs/with-filter.js +53 -0
  21. package/esm/apply-transforms.js +29 -0
  22. package/esm/defaultImportFn.js +32 -0
  23. package/esm/extract-resolvers.js +19 -0
  24. package/esm/fileURLToPath.js +46 -0
  25. package/esm/fs-operations.js +57 -0
  26. package/esm/getHeadersObj.js +57 -0
  27. package/esm/global-lru-cache.js +4 -0
  28. package/esm/group-transforms.js +13 -0
  29. package/esm/index.js +17 -0
  30. package/esm/load-from-module-export-expression.js +25 -0
  31. package/esm/logger.js +118 -0
  32. package/esm/parseAndPrintWithCache.js +37 -0
  33. package/esm/pubsub.js +53 -0
  34. package/esm/read-file-or-url.js +124 -0
  35. package/esm/resolve-additional-resolvers.js +344 -0
  36. package/esm/sanitize-name-for-graphql.js +91 -0
  37. package/esm/with-cancel.js +30 -0
  38. package/esm/with-cookies.js +14 -0
  39. package/esm/with-filter.js +49 -0
  40. package/package.json +28 -23
  41. package/typings/apply-transforms.d.cts +6 -0
  42. package/{apply-transforms.d.ts → typings/apply-transforms.d.ts} +3 -3
  43. package/typings/defaultImportFn.d.cts +2 -0
  44. package/typings/defaultImportFn.d.ts +2 -0
  45. package/typings/extract-resolvers.d.ts +2 -0
  46. package/typings/fileURLToPath.d.ts +1 -0
  47. package/typings/fs-operations.d.ts +7 -0
  48. package/typings/getHeadersObj.d.cts +1 -0
  49. package/typings/getHeadersObj.d.ts +1 -0
  50. package/typings/global-lru-cache.d.cts +3 -0
  51. package/{global-lru-cache.d.ts → typings/global-lru-cache.d.ts} +2 -2
  52. package/typings/group-transforms.d.ts +5 -0
  53. package/typings/index.d.cts +17 -0
  54. package/typings/index.d.ts +17 -0
  55. package/typings/load-from-module-export-expression.d.cts +8 -0
  56. package/{load-from-module-export-expression.d.ts → typings/load-from-module-export-expression.d.ts} +1 -1
  57. package/typings/logger.d.cts +22 -0
  58. package/{logger.d.ts → typings/logger.d.ts} +1 -1
  59. package/typings/parseAndPrintWithCache.d.ts +4 -0
  60. package/typings/pubsub.d.cts +13 -0
  61. package/{pubsub.d.ts → typings/pubsub.d.ts} +3 -2
  62. package/typings/read-file-or-url.d.cts +14 -0
  63. package/{read-file-or-url.d.ts → typings/read-file-or-url.d.ts} +3 -3
  64. package/typings/resolve-additional-resolvers.d.cts +4 -0
  65. package/{resolve-additional-resolvers.d.ts → typings/resolve-additional-resolvers.d.ts} +1 -1
  66. package/typings/sanitize-name-for-graphql.d.cts +2 -0
  67. package/{sanitize-name-for-graphql.d.ts → typings/sanitize-name-for-graphql.d.ts} +1 -0
  68. package/typings/with-cancel.d.cts +1 -0
  69. package/typings/with-cancel.d.ts +1 -0
  70. package/typings/with-cookies.d.cts +3 -0
  71. package/typings/with-cookies.d.ts +3 -0
  72. package/typings/with-filter.d.cts +4 -0
  73. package/typings/with-filter.d.ts +4 -0
  74. package/defaultImportFn.d.ts +0 -1
  75. package/getHeadersObj.d.ts +0 -1
  76. package/index.d.ts +0 -16
  77. package/index.js +0 -1112
  78. package/index.mjs +0 -1054
  79. package/with-cancel.d.ts +0 -1
  80. package/with-filter.d.ts +0 -4
  81. /package/{extract-resolvers.d.ts → typings/extract-resolvers.d.cts} +0 -0
  82. /package/{fileURLToPath.d.ts → typings/fileURLToPath.d.cts} +0 -0
  83. /package/{fs-operations.d.ts → typings/fs-operations.d.cts} +0 -0
  84. /package/{group-transforms.d.ts → typings/group-transforms.d.cts} +0 -0
  85. /package/{parseAndPrintWithCache.d.ts → typings/parseAndPrintWithCache.d.cts} +0 -0
package/index.mjs DELETED
@@ -1,1054 +0,0 @@
1
- import { load, DEFAULT_SCHEMA, Type } from 'js-yaml';
2
- import { path, fs, process, util } from '@graphql-mesh/cross-helpers';
3
- import { getResolversFromSchema, parseSelectionSet, memoize1, observableToAsyncIterable } from '@graphql-tools/utils';
4
- import lru from 'tiny-lru';
5
- import { isAbstractType, getNamedType, isInterfaceType, isObjectType, Kind, parse, print } from 'graphql';
6
- import lodashGet from 'lodash.get';
7
- import lodashSet from 'lodash.set';
8
- import toPath from 'lodash.topath';
9
- import { stringInterpolator } from '@graphql-mesh/string-interpolation';
10
-
11
- async function defaultImportFn(path) {
12
- let module = await import(/* @vite-ignore */ path).catch(e => {
13
- if (e.message.includes('Must use import to load ES Module')) {
14
- // eslint-disable-next-line no-new-func
15
- return new Function(`return import(${JSON.stringify(path)})`)();
16
- }
17
- throw e;
18
- });
19
- if (module.default != null) {
20
- module = module.default;
21
- }
22
- if (typeof module === 'object' && module != null) {
23
- const prototypeOfObject = Object.getPrototypeOf(module);
24
- if (prototypeOfObject == null || prototypeOfObject === Object.prototype) {
25
- const normalizedVal = {};
26
- for (const key in module) {
27
- normalizedVal[key] = module[key];
28
- }
29
- return normalizedVal;
30
- }
31
- }
32
- return module;
33
- }
34
-
35
- /* eslint-disable @typescript-eslint/return-await */
36
- async function loadFromModuleExportExpression(expression, options) {
37
- if (typeof expression !== 'string') {
38
- return Promise.resolve(expression);
39
- }
40
- const { defaultExportName, cwd, importFn = defaultImportFn } = options || {};
41
- const [modulePath, exportName = defaultExportName] = expression.split('#');
42
- const mod = await tryImport(modulePath, cwd, importFn);
43
- return mod[exportName] || (mod.default && mod.default[exportName]) || mod.default || mod;
44
- }
45
- async function tryImport(modulePath, cwd, importFn) {
46
- try {
47
- return await importFn(modulePath);
48
- }
49
- catch (_a) {
50
- if (!path.isAbsolute(modulePath)) {
51
- const absoluteModulePath = path.isAbsolute(modulePath) ? modulePath : path.join(cwd, modulePath);
52
- return importFn(absoluteModulePath);
53
- }
54
- }
55
- }
56
-
57
- function isUrl(str) {
58
- try {
59
- // eslint-disable-next-line no-new
60
- new URL(str);
61
- return true;
62
- }
63
- catch (_a) {
64
- return false;
65
- }
66
- }
67
- async function readFileOrUrl(filePathOrUrl, config) {
68
- if (isUrl(filePathOrUrl)) {
69
- config.logger.debug(`Fetching ${filePathOrUrl} via HTTP`);
70
- return readUrl(filePathOrUrl, config);
71
- }
72
- else if (filePathOrUrl.startsWith('{') || filePathOrUrl.startsWith('[')) {
73
- return JSON.parse(filePathOrUrl);
74
- }
75
- else {
76
- config.logger.debug(`Reading ${filePathOrUrl} from the file system`);
77
- return readFile(filePathOrUrl, config);
78
- }
79
- }
80
- function getSchema(filepath, logger) {
81
- return DEFAULT_SCHEMA.extend([
82
- new Type('!include', {
83
- kind: 'scalar',
84
- resolve(path) {
85
- return typeof path === 'string';
86
- },
87
- construct(path$1) {
88
- const newCwd = path.dirname(filepath);
89
- const absoluteFilePath = path.isAbsolute(path$1) ? path$1 : path.resolve(newCwd, path$1);
90
- const content = fs.readFileSync(absoluteFilePath, 'utf8');
91
- return loadYaml(absoluteFilePath, content, logger);
92
- },
93
- }),
94
- new Type('!includes', {
95
- kind: 'scalar',
96
- resolve(path) {
97
- return typeof path === 'string';
98
- },
99
- construct(path$1) {
100
- const newCwd = path.dirname(filepath);
101
- const absoluteDirPath = path.isAbsolute(path$1) ? path$1 : path.resolve(newCwd, path$1);
102
- const files = fs.readdirSync(absoluteDirPath);
103
- return files.map(filePath => {
104
- const absoluteFilePath = path.resolve(absoluteDirPath, filePath);
105
- const fileContent = fs.readFileSync(absoluteFilePath, 'utf8');
106
- return loadYaml(absoluteFilePath, fileContent, logger);
107
- });
108
- },
109
- }),
110
- ]);
111
- }
112
- function loadYaml(filepath, content, logger) {
113
- return load(content, {
114
- filename: filepath,
115
- schema: getSchema(filepath, logger),
116
- onWarning(warning) {
117
- logger.warn(`${filepath}: ${warning.message}\n${warning.stack}`);
118
- },
119
- });
120
- }
121
- async function readFile(fileExpression, { allowUnknownExtensions, cwd, fallbackFormat, importFn, logger }) {
122
- const [filePath] = fileExpression.split('#');
123
- if (/js$/.test(filePath) || /ts$/.test(filePath)) {
124
- return loadFromModuleExportExpression(fileExpression, {
125
- cwd,
126
- importFn,
127
- defaultExportName: 'default',
128
- });
129
- }
130
- const actualPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
131
- const rawResult = await fs.promises.readFile(actualPath, 'utf-8');
132
- if (/json$/.test(actualPath)) {
133
- return JSON.parse(rawResult);
134
- }
135
- if (/yaml$/.test(actualPath) || /yml$/.test(actualPath)) {
136
- return loadYaml(actualPath, rawResult, logger);
137
- }
138
- else if (fallbackFormat) {
139
- switch (fallbackFormat) {
140
- case 'json':
141
- return JSON.parse(rawResult);
142
- case 'yaml':
143
- return loadYaml(actualPath, rawResult, logger);
144
- case 'ts':
145
- case 'js':
146
- return importFn(actualPath);
147
- }
148
- }
149
- else if (!allowUnknownExtensions) {
150
- throw new Error(`Failed to parse JSON/YAML. Ensure file '${filePath}' has ` +
151
- `the correct extension (i.e. '.json', '.yaml', or '.yml).`);
152
- }
153
- return rawResult;
154
- }
155
- async function readUrl(path, config) {
156
- var _a, _b;
157
- const { allowUnknownExtensions, fallbackFormat } = config || {};
158
- config.headers = config.headers || {};
159
- const response = await config.fetch(path, config);
160
- const contentType = ((_a = response.headers) === null || _a === void 0 ? void 0 : _a.get('content-type')) || '';
161
- const responseText = await response.text();
162
- (_b = config === null || config === void 0 ? void 0 : config.logger) === null || _b === void 0 ? void 0 : _b.debug(`${path} returned `, responseText);
163
- if (/json$/.test(path) || contentType.startsWith('application/json') || fallbackFormat === 'json') {
164
- return JSON.parse(responseText);
165
- }
166
- else if (/yaml$/.test(path) ||
167
- /yml$/.test(path) ||
168
- contentType.includes('yaml') ||
169
- contentType.includes('yml') ||
170
- fallbackFormat === 'yaml') {
171
- return loadYaml(path, responseText, config === null || config === void 0 ? void 0 : config.logger);
172
- }
173
- else if (!allowUnknownExtensions) {
174
- throw new Error(`Failed to parse JSON/YAML. Ensure URL '${path}' has ` +
175
- `the correct extension (i.e. '.json', '.yaml', or '.yml) or mime type in the response headers.`);
176
- }
177
- return responseText;
178
- }
179
-
180
- function withCancel(asyncIterable, onCancel) {
181
- return new Proxy(asyncIterable, {
182
- get(asyncIterable, prop) {
183
- var _a;
184
- if (prop === Symbol.asyncIterator) {
185
- return function getIteratorWithCancel() {
186
- const asyncIterator = asyncIterable[Symbol.asyncIterator]();
187
- return {
188
- next: asyncIterator.next ? (...args) => asyncIterator.next(...args) : undefined,
189
- return: async (...args) => {
190
- onCancel();
191
- if (asyncIterator.return) {
192
- return asyncIterator.return(...args);
193
- }
194
- return {
195
- value: undefined,
196
- done: true,
197
- };
198
- },
199
- throw: asyncIterator.throw ? (...args) => asyncIterator.throw(...args) : undefined,
200
- };
201
- };
202
- }
203
- return (_a = asyncIterable[prop]) === null || _a === void 0 ? void 0 : _a.bind(asyncIterable);
204
- },
205
- });
206
- }
207
-
208
- function extractResolvers(schema) {
209
- const allResolvers = getResolversFromSchema(schema);
210
- const filteredResolvers = {};
211
- for (const prop in allResolvers) {
212
- if (!prop.startsWith('_')) {
213
- filteredResolvers[prop] = allResolvers[prop];
214
- }
215
- if (typeof filteredResolvers === 'object') {
216
- for (const fieldName in filteredResolvers[prop]) {
217
- if (!prop.startsWith('_resolveType')) {
218
- filteredResolvers[prop][fieldName] = allResolvers[prop][fieldName];
219
- }
220
- }
221
- }
222
- }
223
- return filteredResolvers;
224
- }
225
-
226
- function groupTransforms(transforms) {
227
- const wrapTransforms = [];
228
- const noWrapTransforms = [];
229
- transforms === null || transforms === void 0 ? void 0 : transforms.forEach(transform => {
230
- if (transform.noWrap) {
231
- noWrapTransforms.push(transform);
232
- }
233
- else {
234
- wrapTransforms.push(transform);
235
- }
236
- });
237
- return { wrapTransforms, noWrapTransforms };
238
- }
239
-
240
- function applySchemaTransforms(originalWrappingSchema, subschemaConfig, transformedSchema, transforms) {
241
- if (transforms === null || transforms === void 0 ? void 0 : transforms.length) {
242
- return transforms.reduce((schema, transform) => 'transformSchema' in transform ? transform.transformSchema(schema, subschemaConfig, transformedSchema) : schema, originalWrappingSchema);
243
- }
244
- return originalWrappingSchema;
245
- }
246
- function applyRequestTransforms(originalRequest, delegationContext, transformationContext, transforms) {
247
- transformationContext.contextMap = transformationContext.contextMap || new WeakMap();
248
- const contextMap = transformationContext.contextMap;
249
- transforms === null || transforms === void 0 ? void 0 : transforms.forEach(transform => {
250
- if (!contextMap.has(transform)) {
251
- contextMap.set(transform, {
252
- nextIndex: 0,
253
- paths: {},
254
- });
255
- }
256
- });
257
- return transforms.reduceRight((request, transform) => 'transformRequest' in transform
258
- ? transform.transformRequest(request, delegationContext, contextMap.get(transform))
259
- : request, originalRequest);
260
- }
261
- function applyResultTransforms(originalResult, delegationContext, transformationContext, transforms) {
262
- const contextMap = transformationContext.contextMap;
263
- return transforms.reduce((result, transform) => 'transformResult' in transform
264
- ? transform.transformResult(result, delegationContext, contextMap.get(transform))
265
- : result, originalResult);
266
- }
267
-
268
- async function pathExists(path) {
269
- if (!path) {
270
- return false;
271
- }
272
- try {
273
- await fs.promises.stat(path);
274
- return true;
275
- }
276
- catch (e) {
277
- if (e.toString().includes('ENOENT')) {
278
- return false;
279
- }
280
- else {
281
- throw e;
282
- }
283
- }
284
- }
285
- function writeJSON(path, data, replacer, space) {
286
- const stringified = JSON.stringify(data, replacer, space);
287
- return writeFile(path, stringified, 'utf-8');
288
- }
289
- const writeFile = async (path$1, ...args) => {
290
- if (typeof path$1 === 'string') {
291
- const containingDir = path.dirname(path$1);
292
- if (!(await pathExists(containingDir))) {
293
- await mkdir(containingDir);
294
- }
295
- }
296
- return fs.promises.writeFile(path$1, ...args);
297
- };
298
- async function mkdir(path, options = { recursive: true }) {
299
- const ifExists = await pathExists(path);
300
- if (!ifExists) {
301
- await fs.promises.mkdir(path, options);
302
- }
303
- }
304
- async function rmdirs(dir) {
305
- if (await pathExists(dir)) {
306
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
307
- const results = await Promise.allSettled(entries.map(entry => {
308
- const fullPath = path.join(dir, entry.name);
309
- if (entry.isDirectory()) {
310
- return rmdirs(fullPath);
311
- }
312
- else {
313
- return fs.promises.unlink(fullPath);
314
- }
315
- }));
316
- for (const result of results) {
317
- if (result.status === 'rejected' && result.reason.code !== 'ENOENT') {
318
- throw result.reason;
319
- }
320
- }
321
- await fs.promises.rmdir(dir);
322
- }
323
- }
324
-
325
- function createLruCache(max, ttl) {
326
- return lru(max, ttl);
327
- }
328
-
329
- const reservedNames = ['Query', 'Mutation', 'Subscription'];
330
- const KNOWN_CHARACTERS = {
331
- '+': 'PLUS',
332
- '-': 'MINUS',
333
- '>': 'GREATER_THAN',
334
- '<': 'LESS_THAN',
335
- '=': 'EQUALS',
336
- '&': 'AMPERSAND',
337
- '|': 'PIPE',
338
- '@': 'AT',
339
- '*': 'STAR',
340
- ':': 'COLON',
341
- '{': 'LEFT_CURLY_BRACE',
342
- '}': 'RIGHT_CURLY_BRACE',
343
- '[': 'LEFT_SQUARE_BRACE',
344
- ']': 'RIGHT_SQUARE_BRACE',
345
- ',': 'COMMA',
346
- '%': 'PERCENT',
347
- $: 'DOLLAR',
348
- '#': 'POUND',
349
- '^': 'CARET',
350
- '~': 'TILDE',
351
- '?': 'QUESTION_MARK',
352
- '!': 'EXCLAMATION_MARK',
353
- '"': 'QUOTATION_MARK',
354
- "'": 'SINGLE_QUOTE',
355
- '\\': 'BACKSLASH',
356
- '/': 'SLASH',
357
- '.': 'DOT',
358
- '`': 'BACKTICK',
359
- ';': 'SEMICOLON',
360
- '(': 'LEFT_PARENTHESIS',
361
- ')': 'RIGHT_PARENTHESIS',
362
- };
363
- function getKnownCharacterOrCharCode(ch) {
364
- return KNOWN_CHARACTERS[ch] || ch.charCodeAt(0).toString();
365
- }
366
- function sanitizeNameForGraphQL(unsafeName) {
367
- let sanitizedName = unsafeName.trim();
368
- if (!isNaN(parseInt(sanitizedName))) {
369
- if (sanitizedName.startsWith('-')) {
370
- sanitizedName = sanitizedName.replace('-', 'NEGATIVE_');
371
- }
372
- else {
373
- sanitizedName = '_' + sanitizedName;
374
- }
375
- }
376
- if (!/^[_a-zA-Z0-9]*$/.test(sanitizedName)) {
377
- const unsanitizedName = sanitizedName;
378
- sanitizedName = '';
379
- for (const ch of unsanitizedName) {
380
- if (/^[_a-zA-Z0-9]$/.test(ch)) {
381
- sanitizedName += ch;
382
- }
383
- else if (ch === ' ' || ch === '-' || ch === '.') {
384
- sanitizedName += '_';
385
- }
386
- else {
387
- sanitizedName += `_${getKnownCharacterOrCharCode(ch)}_`;
388
- }
389
- }
390
- }
391
- // Names cannot start with __
392
- if (sanitizedName.startsWith('__')) {
393
- sanitizedName = sanitizedName.replace('__', '_0');
394
- }
395
- if (reservedNames.includes(sanitizedName)) {
396
- sanitizedName += '_';
397
- }
398
- return sanitizedName;
399
- }
400
-
401
- function withFilter(asyncIteratorFn, filterFn) {
402
- return async (rootValue, args, context, info) => {
403
- const asyncIterator = await asyncIteratorFn(rootValue, args, context, info);
404
- const getNextPromise = () => {
405
- return new Promise((resolve, reject) => {
406
- const inner = () => {
407
- asyncIterator
408
- .next()
409
- .then(payload => {
410
- if (payload.done === true) {
411
- resolve(payload);
412
- return;
413
- }
414
- Promise.resolve(filterFn(payload.value, args, context, info))
415
- .catch(() => false) // We ignore errors from filter function
416
- .then(filterResult => {
417
- if (filterResult === true) {
418
- resolve(payload);
419
- return;
420
- }
421
- // Skip the current value and wait for the next one
422
- inner();
423
- })
424
- .catch(() => false); // We ignore errors from filter function;
425
- })
426
- .catch(err => {
427
- reject(err);
428
- });
429
- };
430
- inner();
431
- });
432
- };
433
- const asyncIterator2 = {
434
- next() {
435
- return getNextPromise();
436
- },
437
- return() {
438
- return asyncIterator.return();
439
- },
440
- throw(error) {
441
- return asyncIterator.throw(error);
442
- },
443
- [Symbol.asyncIterator]() {
444
- return this;
445
- },
446
- };
447
- return asyncIterator2;
448
- };
449
- }
450
-
451
- function getTypeByPath(type, path) {
452
- if ('ofType' in type) {
453
- return getTypeByPath(getNamedType(type), path);
454
- }
455
- if (path.length === 0) {
456
- return getNamedType(type);
457
- }
458
- if (!('getFields' in type)) {
459
- throw new Error(`${type} cannot have a path ${path.join('.')}`);
460
- }
461
- const fieldMap = type.getFields();
462
- const currentFieldName = path[0];
463
- // Might be an index of an array
464
- if (!Number.isNaN(parseInt(currentFieldName))) {
465
- return getTypeByPath(type, path.slice(1));
466
- }
467
- const field = fieldMap[currentFieldName];
468
- if (!(field === null || field === void 0 ? void 0 : field.type)) {
469
- throw new Error(`${type}.${currentFieldName} is not a valid field.`);
470
- }
471
- return getTypeByPath(field.type, path.slice(1));
472
- }
473
- function generateSelectionSetFactory(schema, additionalResolver) {
474
- if (additionalResolver.sourceSelectionSet) {
475
- return () => parseSelectionSet(additionalResolver.sourceSelectionSet);
476
- // If result path provided without a selectionSet
477
- }
478
- else if (additionalResolver.result) {
479
- const resultPath = toPath(additionalResolver.result);
480
- let abstractResultTypeName;
481
- const sourceType = schema.getType(additionalResolver.sourceTypeName);
482
- const sourceTypeFields = sourceType.getFields();
483
- const sourceField = sourceTypeFields[additionalResolver.sourceFieldName];
484
- const resultFieldType = getTypeByPath(sourceField.type, resultPath);
485
- if (isAbstractType(resultFieldType)) {
486
- if (additionalResolver.resultType) {
487
- abstractResultTypeName = additionalResolver.resultType;
488
- }
489
- else {
490
- const targetType = schema.getType(additionalResolver.targetTypeName);
491
- const targetTypeFields = targetType.getFields();
492
- const targetField = targetTypeFields[additionalResolver.targetFieldName];
493
- const targetFieldType = getNamedType(targetField.type);
494
- abstractResultTypeName = targetFieldType === null || targetFieldType === void 0 ? void 0 : targetFieldType.name;
495
- }
496
- if (abstractResultTypeName !== resultFieldType.name) {
497
- const abstractResultType = schema.getType(abstractResultTypeName);
498
- if ((isInterfaceType(abstractResultType) || isObjectType(abstractResultType)) &&
499
- !schema.isSubType(resultFieldType, abstractResultType)) {
500
- throw new Error(`${additionalResolver.sourceTypeName}.${additionalResolver.sourceFieldName}.${resultPath.join('.')} doesn't implement ${abstractResultTypeName}.}`);
501
- }
502
- }
503
- }
504
- return (subtree) => {
505
- let finalSelectionSet = subtree;
506
- let isLastResult = true;
507
- const resultPathReversed = [...resultPath].reverse();
508
- for (const pathElem of resultPathReversed) {
509
- // Ensure the path elem is not array index
510
- if (Number.isNaN(parseInt(pathElem))) {
511
- if (isLastResult && abstractResultTypeName && abstractResultTypeName !== resultFieldType.name) {
512
- finalSelectionSet = {
513
- kind: Kind.SELECTION_SET,
514
- selections: [
515
- {
516
- kind: Kind.INLINE_FRAGMENT,
517
- typeCondition: {
518
- kind: Kind.NAMED_TYPE,
519
- name: {
520
- kind: Kind.NAME,
521
- value: abstractResultTypeName,
522
- },
523
- },
524
- selectionSet: finalSelectionSet,
525
- },
526
- ],
527
- };
528
- }
529
- finalSelectionSet = {
530
- kind: Kind.SELECTION_SET,
531
- selections: [
532
- {
533
- // we create a wrapping AST Field
534
- kind: Kind.FIELD,
535
- name: {
536
- kind: Kind.NAME,
537
- value: pathElem,
538
- },
539
- // Inside the field selection
540
- selectionSet: finalSelectionSet,
541
- },
542
- ],
543
- };
544
- isLastResult = false;
545
- }
546
- }
547
- return finalSelectionSet;
548
- };
549
- }
550
- return undefined;
551
- }
552
- function generateValuesFromResults(resultExpression) {
553
- return function valuesFromResults(result) {
554
- if (Array.isArray(result)) {
555
- return result.map(valuesFromResults);
556
- }
557
- return lodashGet(result, resultExpression);
558
- };
559
- }
560
- function resolveAdditionalResolversWithoutImport(additionalResolver, pubsub) {
561
- const baseOptions = {};
562
- if (additionalResolver.result) {
563
- baseOptions.valuesFromResults = generateValuesFromResults(additionalResolver.result);
564
- }
565
- if ('pubsubTopic' in additionalResolver) {
566
- return {
567
- [additionalResolver.targetTypeName]: {
568
- [additionalResolver.targetFieldName]: {
569
- subscribe: withFilter((root, args, context, info) => {
570
- const resolverData = { root, args, context, info, env: process.env };
571
- const topic = stringInterpolator.parse(additionalResolver.pubsubTopic, resolverData);
572
- return pubsub.asyncIterator(topic);
573
- }, (root, args, context, info) => {
574
- // eslint-disable-next-line no-new-func
575
- return additionalResolver.filterBy ? new Function(`return ${additionalResolver.filterBy}`)() : true;
576
- }),
577
- resolve: (payload) => {
578
- if (baseOptions.valuesFromResults) {
579
- return baseOptions.valuesFromResults(payload);
580
- }
581
- return payload;
582
- },
583
- },
584
- },
585
- };
586
- }
587
- else if ('keysArg' in additionalResolver) {
588
- return {
589
- [additionalResolver.targetTypeName]: {
590
- [additionalResolver.targetFieldName]: {
591
- selectionSet: additionalResolver.requiredSelectionSet || `{ ${additionalResolver.keyField} }`,
592
- resolve: async (root, args, context, info) => {
593
- if (!baseOptions.selectionSet) {
594
- baseOptions.selectionSet = generateSelectionSetFactory(info.schema, additionalResolver);
595
- }
596
- const resolverData = { root, args, context, info, env: process.env };
597
- const targetArgs = {};
598
- for (const argPath in additionalResolver.additionalArgs || {}) {
599
- lodashSet(targetArgs, argPath, stringInterpolator.parse(additionalResolver.additionalArgs[argPath], resolverData));
600
- }
601
- const options = {
602
- ...baseOptions,
603
- root,
604
- context,
605
- info,
606
- argsFromKeys: (keys) => {
607
- const args = {};
608
- lodashSet(args, additionalResolver.keysArg, keys);
609
- Object.assign(args, targetArgs);
610
- return args;
611
- },
612
- key: lodashGet(root, additionalResolver.keyField),
613
- };
614
- return context[additionalResolver.sourceName][additionalResolver.sourceTypeName][additionalResolver.sourceFieldName](options);
615
- },
616
- },
617
- },
618
- };
619
- }
620
- else if ('targetTypeName' in additionalResolver) {
621
- return {
622
- [additionalResolver.targetTypeName]: {
623
- [additionalResolver.targetFieldName]: {
624
- selectionSet: additionalResolver.requiredSelectionSet,
625
- resolve: (root, args, context, info) => {
626
- // Assert source exists
627
- if (!context[additionalResolver.sourceName]) {
628
- throw new Error(`No source found named "${additionalResolver.sourceName}"`);
629
- }
630
- if (!context[additionalResolver.sourceName][additionalResolver.sourceTypeName]) {
631
- throw new Error(`No root type found named "${additionalResolver.sourceTypeName}" exists in the source ${additionalResolver.sourceName}\n` +
632
- `It should be one of the following; ${Object.keys(context[additionalResolver.sourceName]).join(',')})}}`);
633
- }
634
- if (!context[additionalResolver.sourceName][additionalResolver.sourceTypeName][additionalResolver.sourceFieldName]) {
635
- throw new Error(`No field named "${additionalResolver.sourceFieldName}" exists in the type ${additionalResolver.sourceTypeName} from the source ${additionalResolver.sourceName}`);
636
- }
637
- if (!baseOptions.selectionSet) {
638
- baseOptions.selectionSet = generateSelectionSetFactory(info.schema, additionalResolver);
639
- }
640
- const resolverData = { root, args, context, info, env: process.env };
641
- const targetArgs = {};
642
- for (const argPath in additionalResolver.sourceArgs) {
643
- lodashSet(targetArgs, argPath, stringInterpolator.parse(additionalResolver.sourceArgs[argPath].toString(), resolverData));
644
- }
645
- const options = {
646
- ...baseOptions,
647
- root,
648
- args: targetArgs,
649
- context,
650
- info,
651
- };
652
- return context[additionalResolver.sourceName][additionalResolver.sourceTypeName][additionalResolver.sourceFieldName](options);
653
- },
654
- },
655
- },
656
- };
657
- }
658
- else {
659
- return additionalResolver;
660
- }
661
- }
662
- function resolveAdditionalResolvers(baseDir, additionalResolvers, importFn, pubsub) {
663
- return Promise.all((additionalResolvers || []).map(async (additionalResolver) => {
664
- if (typeof additionalResolver === 'string') {
665
- const resolvers = await loadFromModuleExportExpression(additionalResolver, {
666
- cwd: baseDir,
667
- defaultExportName: 'resolvers',
668
- importFn,
669
- });
670
- if (!resolvers) {
671
- console.warn(`Unable to load resolvers from file: ${additionalResolver}`);
672
- return {};
673
- }
674
- return resolvers;
675
- }
676
- else {
677
- const baseOptions = {};
678
- if (additionalResolver.result) {
679
- baseOptions.valuesFromResults = generateValuesFromResults(additionalResolver.result);
680
- }
681
- if ('pubsubTopic' in additionalResolver) {
682
- return {
683
- [additionalResolver.targetTypeName]: {
684
- [additionalResolver.targetFieldName]: {
685
- subscribe: withFilter((root, args, context, info) => {
686
- const resolverData = { root, args, context, info, env: process.env };
687
- const topic = stringInterpolator.parse(additionalResolver.pubsubTopic, resolverData);
688
- return pubsub.asyncIterator(topic);
689
- }, (root, args, context, info) => {
690
- // eslint-disable-next-line no-new-func
691
- return additionalResolver.filterBy ? new Function(`return ${additionalResolver.filterBy}`)() : true;
692
- }),
693
- resolve: (payload) => {
694
- if (baseOptions.valuesFromResults) {
695
- return baseOptions.valuesFromResults(payload);
696
- }
697
- return payload;
698
- },
699
- },
700
- },
701
- };
702
- }
703
- else if ('keysArg' in additionalResolver) {
704
- return {
705
- [additionalResolver.targetTypeName]: {
706
- [additionalResolver.targetFieldName]: {
707
- selectionSet: additionalResolver.requiredSelectionSet || `{ ${additionalResolver.keyField} }`,
708
- resolve: async (root, args, context, info) => {
709
- if (!baseOptions.selectionSet) {
710
- baseOptions.selectionSet = generateSelectionSetFactory(info.schema, additionalResolver);
711
- }
712
- const resolverData = { root, args, context, info, env: process.env };
713
- const targetArgs = {};
714
- for (const argPath in additionalResolver.additionalArgs || {}) {
715
- lodashSet(targetArgs, argPath, stringInterpolator.parse(additionalResolver.additionalArgs[argPath], resolverData));
716
- }
717
- const options = {
718
- ...baseOptions,
719
- root,
720
- context,
721
- info,
722
- argsFromKeys: (keys) => {
723
- const args = {};
724
- lodashSet(args, additionalResolver.keysArg, keys);
725
- Object.assign(args, targetArgs);
726
- return args;
727
- },
728
- key: lodashGet(root, additionalResolver.keyField),
729
- };
730
- return context[additionalResolver.sourceName][additionalResolver.sourceTypeName][additionalResolver.sourceFieldName](options);
731
- },
732
- },
733
- },
734
- };
735
- }
736
- else if ('targetTypeName' in additionalResolver) {
737
- return {
738
- [additionalResolver.targetTypeName]: {
739
- [additionalResolver.targetFieldName]: {
740
- selectionSet: additionalResolver.requiredSelectionSet,
741
- resolve: (root, args, context, info) => {
742
- // Assert source exists
743
- if (!context[additionalResolver.sourceName]) {
744
- throw new Error(`No source found named "${additionalResolver.sourceName}"`);
745
- }
746
- if (!context[additionalResolver.sourceName][additionalResolver.sourceTypeName]) {
747
- throw new Error(`No root type found named "${additionalResolver.sourceTypeName}" exists in the source ${additionalResolver.sourceName}\n` +
748
- `It should be one of the following; ${Object.keys(context[additionalResolver.sourceName]).join(',')})}}`);
749
- }
750
- if (!context[additionalResolver.sourceName][additionalResolver.sourceTypeName][additionalResolver.sourceFieldName]) {
751
- throw new Error(`No field named "${additionalResolver.sourceFieldName}" exists in the type ${additionalResolver.sourceTypeName} from the source ${additionalResolver.sourceName}`);
752
- }
753
- if (!baseOptions.selectionSet) {
754
- baseOptions.selectionSet = generateSelectionSetFactory(info.schema, additionalResolver);
755
- }
756
- const resolverData = { root, args, context, info, env: process.env };
757
- const targetArgs = {};
758
- for (const argPath in additionalResolver.sourceArgs) {
759
- lodashSet(targetArgs, argPath, stringInterpolator.parse(additionalResolver.sourceArgs[argPath].toString(), resolverData));
760
- }
761
- const options = {
762
- ...baseOptions,
763
- root,
764
- args: targetArgs,
765
- context,
766
- info,
767
- };
768
- return context[additionalResolver.sourceName][additionalResolver.sourceTypeName][additionalResolver.sourceFieldName](options);
769
- },
770
- },
771
- },
772
- };
773
- }
774
- else {
775
- return additionalResolver;
776
- }
777
- }
778
- }));
779
- }
780
-
781
- const ANSI_CODES = {
782
- black: '\x1b[30m',
783
- red: '\x1b[31m',
784
- green: '\x1b[32m',
785
- yellow: '\x1b[33m',
786
- blue: '\x1b[34m',
787
- magenta: '\x1b[35m',
788
- cyan: '\x1b[36m',
789
- white: '\x1b[37m',
790
- reset: '\x1b[0m',
791
- bold: '\x1b[1m',
792
- orange: '\x1b[48:5:166m',
793
- };
794
- const warnColor = msg => ANSI_CODES.orange + msg + ANSI_CODES.reset;
795
- const infoColor = msg => ANSI_CODES.cyan + msg + ANSI_CODES.reset;
796
- const errorColor = msg => ANSI_CODES.red + msg + ANSI_CODES.reset;
797
- const debugColor = msg => ANSI_CODES.magenta + msg + ANSI_CODES.reset;
798
- const titleBold = msg => ANSI_CODES.bold + msg + ANSI_CODES.reset;
799
- class DefaultLogger {
800
- constructor(name) {
801
- this.name = name;
802
- }
803
- getLoggerMessage(...args) {
804
- return args
805
- .flat(Infinity)
806
- .map(arg => {
807
- if (typeof arg === 'string') {
808
- if (arg.length > 100 && !this.isDebug) {
809
- return arg.slice(0, 100) + '...';
810
- }
811
- return arg;
812
- }
813
- else if (typeof arg === 'object' && (arg === null || arg === void 0 ? void 0 : arg.stack) != null) {
814
- return arg.stack;
815
- }
816
- return util.inspect(arg);
817
- })
818
- .join(` `);
819
- }
820
- handleLazyMessage(...lazyArgs) {
821
- const flattenedArgs = lazyArgs.flat(Infinity).flatMap(arg => {
822
- if (typeof arg === 'function') {
823
- return arg();
824
- }
825
- return arg;
826
- });
827
- return this.getLoggerMessage(flattenedArgs);
828
- }
829
- get isDebug() {
830
- return (process.env.DEBUG === '1' ||
831
- globalThis.DEBUG === '1' ||
832
- this.name.includes(process.env.DEBUG || globalThis.DEBUG));
833
- }
834
- get prefix() {
835
- return this.name ? titleBold(this.name) : ``;
836
- }
837
- log(...args) {
838
- const message = this.getLoggerMessage(...args);
839
- return console.log(`${this.prefix} ${message}`);
840
- }
841
- warn(...args) {
842
- const message = this.getLoggerMessage(...args);
843
- const fullMessage = `⚠️ ${this.prefix} ${warnColor(message)}`;
844
- if (console.warn) {
845
- console.warn(fullMessage);
846
- }
847
- else {
848
- console.log(fullMessage);
849
- }
850
- }
851
- info(...args) {
852
- const message = this.getLoggerMessage(...args);
853
- const fullMessage = `💡 ${this.prefix} ${infoColor(message)}`;
854
- if (console.info) {
855
- console.info(fullMessage);
856
- }
857
- else {
858
- console.log(fullMessage);
859
- }
860
- }
861
- error(...args) {
862
- const message = this.getLoggerMessage(...args);
863
- const fullMessage = `💥 ${this.prefix} ${errorColor(message)}`;
864
- console.log(fullMessage);
865
- }
866
- debug(...lazyArgs) {
867
- if (this.isDebug) {
868
- const message = this.handleLazyMessage(lazyArgs);
869
- const fullMessage = `🐛 ${this.prefix} ${debugColor(message)}`;
870
- if (console.debug) {
871
- console.debug(fullMessage);
872
- }
873
- else {
874
- console.log(fullMessage);
875
- }
876
- }
877
- }
878
- child(name) {
879
- return new DefaultLogger(this.name ? `${this.name} - ${name}` : name);
880
- }
881
- }
882
-
883
- const parseCache = createLruCache(1000, 3600);
884
- const printCache = createLruCache(1000, 3600);
885
- function parseWithCache(sdl) {
886
- const trimmedSdl = sdl.trim();
887
- let document = parseCache.get(trimmedSdl);
888
- if (!document) {
889
- document = parse(trimmedSdl, { noLocation: true });
890
- parseCache.set(trimmedSdl, document);
891
- printCache.set(JSON.stringify(document), trimmedSdl);
892
- }
893
- return document;
894
- }
895
- const printWithCache = memoize1(function printWithCache(document) {
896
- const stringifedDocumentJson = JSON.stringify(document);
897
- let sdl = printCache.get(stringifedDocumentJson);
898
- if (!sdl) {
899
- sdl = print(document).trim();
900
- printCache.set(stringifedDocumentJson, sdl);
901
- parseCache.set(sdl, document);
902
- }
903
- return sdl;
904
- });
905
- function gql([sdl], ...args) {
906
- let result = sdl;
907
- for (const arg of args || []) {
908
- if (typeof arg === 'string') {
909
- result += arg;
910
- }
911
- else {
912
- result += printWithCache(arg);
913
- }
914
- }
915
- return parseWithCache(result);
916
- }
917
-
918
- class PubSub {
919
- constructor() {
920
- this.subIdListenerMap = new Map();
921
- this.listenerEventMap = new Map();
922
- this.eventNameListenersMap = new Map();
923
- }
924
- publish(triggerName, detail) {
925
- const eventNameListeners = this.eventNameListenersMap.get(triggerName);
926
- if (eventNameListeners) {
927
- Promise.allSettled([...eventNameListeners].map(listener => listener(detail))).catch(e => console.error(e));
928
- }
929
- }
930
- subscribe(triggerName, onMessage) {
931
- let eventNameListeners = this.eventNameListenersMap.get(triggerName);
932
- if (!eventNameListeners) {
933
- eventNameListeners = new Set();
934
- this.eventNameListenersMap.set(triggerName, eventNameListeners);
935
- }
936
- const subId = Date.now();
937
- eventNameListeners.add(onMessage);
938
- this.subIdListenerMap.set(subId, onMessage);
939
- this.listenerEventMap.set(onMessage, triggerName);
940
- return subId;
941
- }
942
- unsubscribe(subId) {
943
- const listener = this.subIdListenerMap.get(subId);
944
- if (listener) {
945
- this.subIdListenerMap.delete(subId);
946
- const eventName = this.listenerEventMap.get(listener);
947
- if (eventName) {
948
- const eventNameListeners = this.eventNameListenersMap.get(eventName);
949
- if (eventNameListeners) {
950
- eventNameListeners.delete(listener);
951
- }
952
- }
953
- }
954
- this.listenerEventMap.delete(listener);
955
- }
956
- asyncIterator(triggerName) {
957
- return observableToAsyncIterable({
958
- subscribe: observer => {
959
- const subId = this.subscribe(triggerName, data => observer.next(data));
960
- return {
961
- unsubscribe: () => this.unsubscribe(subId),
962
- };
963
- },
964
- });
965
- }
966
- }
967
-
968
- function fileUriToPath(uri) {
969
- if (typeof uri !== 'string' || uri.length <= 7 || uri.substring(0, 7) !== 'file://') {
970
- throw new TypeError('must pass in a file:// URI to convert to a file path');
971
- }
972
- const rest = decodeURI(uri.substring(7));
973
- const firstSlash = rest.indexOf('/');
974
- let host = rest.substring(0, firstSlash);
975
- let path$1 = rest.substring(firstSlash + 1);
976
- // 2. Scheme Definition
977
- // As a special case, <host> can be the string "localhost" or the empty
978
- // string; this is interpreted as "the machine from which the URL is
979
- // being interpreted".
980
- if (host === 'localhost') {
981
- host = '';
982
- }
983
- if (host) {
984
- host = path.sep + path.sep + host;
985
- }
986
- // 3.2 Drives, drive letters, mount points, file system root
987
- // Drive letters are mapped into the top of a file URI in various ways,
988
- // depending on the implementation; some applications substitute
989
- // vertical bar ("|") for the colon after the drive letter, yielding
990
- // "file:///c|/tmp/test.txt". In some cases, the colon is left
991
- // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
992
- // colon is simply omitted, as in "file:///c/tmp/test.txt".
993
- path$1 = path$1.replace(/^(.+)\|/, '$1:');
994
- // for Windows, we need to invert the path separators from what a URI uses
995
- if (path.sep === '\\') {
996
- path$1 = path$1.replace(/\//g, '\\');
997
- }
998
- if (/^.+:/.test(path$1)) ;
999
- else {
1000
- // unix path…
1001
- path$1 = path.sep + path$1;
1002
- }
1003
- return host + path$1;
1004
- }
1005
- function fileURLToPath(url) {
1006
- if (url === null || url === void 0 ? void 0 : url.startsWith('file://')) {
1007
- return fileUriToPath(url);
1008
- }
1009
- return url || '';
1010
- }
1011
-
1012
- function headersToJSON(headers) {
1013
- const obj = {};
1014
- headers.forEach((value, key) => {
1015
- obj[key] = value;
1016
- });
1017
- return obj;
1018
- }
1019
- function getHeadersObj(headers) {
1020
- return new Proxy({}, {
1021
- get(_target, name) {
1022
- if (name === 'toJSON') {
1023
- return () => headersToJSON(headers);
1024
- }
1025
- return headers.get(name.toString());
1026
- },
1027
- has(_target, name) {
1028
- if (name === 'toJSON') {
1029
- return true;
1030
- }
1031
- return headers.has(name.toString());
1032
- },
1033
- ownKeys(_target) {
1034
- const keys = [];
1035
- headers.forEach((_value, name) => {
1036
- keys.push(name);
1037
- });
1038
- return keys;
1039
- },
1040
- set(_target, name, value) {
1041
- headers.set(name.toString(), value);
1042
- return true;
1043
- },
1044
- deleteProperty(_target, name) {
1045
- headers.delete(name.toString());
1046
- return true;
1047
- },
1048
- preventExtensions() {
1049
- return true;
1050
- },
1051
- });
1052
- }
1053
-
1054
- export { DefaultLogger, PubSub, applyRequestTransforms, applyResultTransforms, applySchemaTransforms, createLruCache, debugColor, defaultImportFn, errorColor, extractResolvers, fileURLToPath, getHeadersObj, gql, groupTransforms, infoColor, isUrl, loadFromModuleExportExpression, loadYaml, mkdir, parseWithCache, pathExists, printWithCache, readFile, readFileOrUrl, readUrl, resolveAdditionalResolvers, resolveAdditionalResolversWithoutImport, rmdirs, sanitizeNameForGraphQL, titleBold, warnColor, withCancel, writeFile, writeJSON };