@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
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withFilter = void 0;
4
+ function withFilter(asyncIteratorFn, filterFn) {
5
+ return async (rootValue, args, context, info) => {
6
+ const asyncIterator = await asyncIteratorFn(rootValue, args, context, info);
7
+ const getNextPromise = () => {
8
+ return new Promise((resolve, reject) => {
9
+ const inner = () => {
10
+ asyncIterator
11
+ .next()
12
+ .then(payload => {
13
+ if (payload.done === true) {
14
+ resolve(payload);
15
+ return;
16
+ }
17
+ Promise.resolve(filterFn(payload.value, args, context, info))
18
+ .catch(() => false) // We ignore errors from filter function
19
+ .then(filterResult => {
20
+ if (filterResult === true) {
21
+ resolve(payload);
22
+ return;
23
+ }
24
+ // Skip the current value and wait for the next one
25
+ inner();
26
+ })
27
+ .catch(() => false); // We ignore errors from filter function;
28
+ })
29
+ .catch(err => {
30
+ reject(err);
31
+ });
32
+ };
33
+ inner();
34
+ });
35
+ };
36
+ const asyncIterator2 = {
37
+ next() {
38
+ return getNextPromise();
39
+ },
40
+ return() {
41
+ return asyncIterator.return();
42
+ },
43
+ throw(error) {
44
+ return asyncIterator.throw(error);
45
+ },
46
+ [Symbol.asyncIterator]() {
47
+ return this;
48
+ },
49
+ };
50
+ return asyncIterator2;
51
+ };
52
+ }
53
+ exports.withFilter = withFilter;
@@ -0,0 +1,29 @@
1
+ export function applySchemaTransforms(originalWrappingSchema, subschemaConfig, transformedSchema, transforms) {
2
+ if (transforms === null || transforms === void 0 ? void 0 : transforms.length) {
3
+ return transforms.reduce((schema, transform) => 'transformSchema' in transform
4
+ ? transform.transformSchema(schema, subschemaConfig)
5
+ : schema, originalWrappingSchema);
6
+ }
7
+ return originalWrappingSchema;
8
+ }
9
+ export function applyRequestTransforms(originalRequest, delegationContext, transformationContext, transforms) {
10
+ transformationContext.contextMap = transformationContext.contextMap || new WeakMap();
11
+ const contextMap = transformationContext.contextMap;
12
+ transforms === null || transforms === void 0 ? void 0 : transforms.forEach(transform => {
13
+ if (!contextMap.has(transform)) {
14
+ contextMap.set(transform, {
15
+ nextIndex: 0,
16
+ paths: {},
17
+ });
18
+ }
19
+ });
20
+ return transforms.reduceRight((request, transform) => 'transformRequest' in transform
21
+ ? transform.transformRequest(request, delegationContext, contextMap.get(transform))
22
+ : request, originalRequest);
23
+ }
24
+ export function applyResultTransforms(originalResult, delegationContext, transformationContext, transforms) {
25
+ const contextMap = transformationContext.contextMap;
26
+ return transforms.reduce((result, transform) => 'transformResult' in transform
27
+ ? transform.transformResult(result, delegationContext, contextMap.get(transform))
28
+ : result, originalResult);
29
+ }
@@ -0,0 +1,32 @@
1
+ import { path as pathModule } from '@graphql-mesh/cross-helpers';
2
+ async function defaultImportFn(path) {
3
+ let module = await import(/* @vite-ignore */ path)
4
+ .catch(e => {
5
+ if (e.code === 'ERR_REQUIRE_ESM') {
6
+ // eslint-disable-next-line no-new-func
7
+ return new Function(`return import(${JSON.stringify(path)})`)();
8
+ }
9
+ throw e;
10
+ })
11
+ .catch(e => {
12
+ if (pathModule.isAbsolute(path) && !path.endsWith('.js') && !path.endsWith('.ts')) {
13
+ return defaultImportFn(`${path}.ts`);
14
+ }
15
+ throw e;
16
+ });
17
+ if (module.default != null) {
18
+ module = module.default;
19
+ }
20
+ if (typeof module === 'object' && module != null) {
21
+ const prototypeOfObject = Object.getPrototypeOf(module);
22
+ if (prototypeOfObject == null || prototypeOfObject === Object.prototype) {
23
+ const normalizedVal = {};
24
+ for (const key in module) {
25
+ normalizedVal[key] = module[key];
26
+ }
27
+ return normalizedVal;
28
+ }
29
+ }
30
+ return module;
31
+ }
32
+ export { defaultImportFn };
@@ -0,0 +1,19 @@
1
+ import { getResolversFromSchema } from '@graphql-tools/utils';
2
+ export function extractResolvers(schema) {
3
+ const allResolvers = getResolversFromSchema(schema);
4
+ const filteredResolvers = {};
5
+ for (const prop in allResolvers) {
6
+ if (!prop.startsWith('_')) {
7
+ filteredResolvers[prop] = allResolvers[prop];
8
+ }
9
+ if (typeof filteredResolvers === 'object') {
10
+ for (const fieldName in filteredResolvers[prop]) {
11
+ if (!prop.startsWith('_resolveType')) {
12
+ filteredResolvers[prop][fieldName] =
13
+ allResolvers[prop][fieldName];
14
+ }
15
+ }
16
+ }
17
+ }
18
+ return filteredResolvers;
19
+ }
@@ -0,0 +1,46 @@
1
+ import { path as pathModule } from '@graphql-mesh/cross-helpers';
2
+ function fileUriToPath(uri) {
3
+ if (typeof uri !== 'string' || uri.length <= 7 || uri.substring(0, 7) !== 'file://') {
4
+ throw new TypeError('must pass in a file:// URI to convert to a file path');
5
+ }
6
+ const rest = decodeURI(uri.substring(7));
7
+ const firstSlash = rest.indexOf('/');
8
+ let host = rest.substring(0, firstSlash);
9
+ let path = rest.substring(firstSlash + 1);
10
+ // 2. Scheme Definition
11
+ // As a special case, <host> can be the string "localhost" or the empty
12
+ // string; this is interpreted as "the machine from which the URL is
13
+ // being interpreted".
14
+ if (host === 'localhost') {
15
+ host = '';
16
+ }
17
+ if (host) {
18
+ host = pathModule.sep + pathModule.sep + host;
19
+ }
20
+ // 3.2 Drives, drive letters, mount points, file system root
21
+ // Drive letters are mapped into the top of a file URI in various ways,
22
+ // depending on the implementation; some applications substitute
23
+ // vertical bar ("|") for the colon after the drive letter, yielding
24
+ // "file:///c|/tmp/test.txt". In some cases, the colon is left
25
+ // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
26
+ // colon is simply omitted, as in "file:///c/tmp/test.txt".
27
+ path = path.replace(/^(.+)\|/, '$1:');
28
+ // for Windows, we need to invert the path separators from what a URI uses
29
+ if (pathModule.sep === '\\') {
30
+ path = path.replace(/\//g, '\\');
31
+ }
32
+ if (/^.+:/.test(path)) {
33
+ // has Windows drive at beginning of path
34
+ }
35
+ else {
36
+ // unix path…
37
+ path = pathModule.sep + path;
38
+ }
39
+ return host + path;
40
+ }
41
+ export function fileURLToPath(url) {
42
+ if (url === null || url === void 0 ? void 0 : url.startsWith('file://')) {
43
+ return fileUriToPath(url);
44
+ }
45
+ return url || '';
46
+ }
@@ -0,0 +1,57 @@
1
+ import { fs, path as pathModule } from '@graphql-mesh/cross-helpers';
2
+ export async function pathExists(path) {
3
+ if (!path) {
4
+ return false;
5
+ }
6
+ try {
7
+ await fs.promises.stat(path);
8
+ return true;
9
+ }
10
+ catch (e) {
11
+ if (e.toString().includes('ENOENT')) {
12
+ return false;
13
+ }
14
+ else {
15
+ throw e;
16
+ }
17
+ }
18
+ }
19
+ export function writeJSON(path, data, replacer, space) {
20
+ const stringified = JSON.stringify(data, replacer, space);
21
+ return writeFile(path, stringified, 'utf-8');
22
+ }
23
+ export const writeFile = async (path, ...args) => {
24
+ if (typeof path === 'string') {
25
+ const containingDir = pathModule.dirname(path);
26
+ if (!(await pathExists(containingDir))) {
27
+ await mkdir(containingDir);
28
+ }
29
+ }
30
+ return fs.promises.writeFile(path, ...args);
31
+ };
32
+ export async function mkdir(path, options = { recursive: true }) {
33
+ const ifExists = await pathExists(path);
34
+ if (!ifExists) {
35
+ await fs.promises.mkdir(path, options);
36
+ }
37
+ }
38
+ export async function rmdirs(dir) {
39
+ if (await pathExists(dir)) {
40
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
41
+ const results = await Promise.allSettled(entries.map(entry => {
42
+ const fullPath = pathModule.join(dir, entry.name);
43
+ if (entry.isDirectory()) {
44
+ return rmdirs(fullPath);
45
+ }
46
+ else {
47
+ return fs.promises.unlink(fullPath);
48
+ }
49
+ }));
50
+ for (const result of results) {
51
+ if (result.status === 'rejected' && result.reason.code !== 'ENOENT') {
52
+ throw result.reason;
53
+ }
54
+ }
55
+ await fs.promises.rmdir(dir);
56
+ }
57
+ }
@@ -0,0 +1,57 @@
1
+ function headersToJSON(headers) {
2
+ return Object.fromEntries(headers.entries());
3
+ }
4
+ function isHeaders(headers) {
5
+ return headers != null && 'get' in headers && typeof headers.get === 'function';
6
+ }
7
+ export function getHeadersObj(headers) {
8
+ if (headers == null || !isHeaders(headers)) {
9
+ return headers;
10
+ }
11
+ return new Proxy({}, {
12
+ get(_target, name) {
13
+ if (name === 'toJSON') {
14
+ return () => headersToJSON(headers);
15
+ }
16
+ return headers.get(name.toString().toLowerCase()) || undefined;
17
+ },
18
+ has(_target, name) {
19
+ if (name === 'toJSON') {
20
+ return true;
21
+ }
22
+ return headers.has(name.toString().toLowerCase());
23
+ },
24
+ ownKeys(_target) {
25
+ return [...headers.keys()];
26
+ },
27
+ set(_target, name, value) {
28
+ headers.set(name.toString().toLowerCase(), value);
29
+ return true;
30
+ },
31
+ defineProperty(_target, name, descriptor) {
32
+ if (descriptor.value != null) {
33
+ headers.set(name.toString().toLowerCase(), descriptor.value);
34
+ }
35
+ return true;
36
+ },
37
+ getOwnPropertyDescriptor(_target, name) {
38
+ const value = headers.get(name.toString().toLowerCase());
39
+ if (value == null) {
40
+ return undefined;
41
+ }
42
+ return {
43
+ configurable: true,
44
+ enumerable: true,
45
+ value,
46
+ writable: true,
47
+ };
48
+ },
49
+ deleteProperty(_target, name) {
50
+ headers.delete(name.toString().toLowerCase());
51
+ return true;
52
+ },
53
+ preventExtensions() {
54
+ return true;
55
+ },
56
+ });
57
+ }
@@ -0,0 +1,4 @@
1
+ import lru from 'tiny-lru';
2
+ export function createLruCache(max, ttl) {
3
+ return lru(max, ttl);
4
+ }
@@ -0,0 +1,13 @@
1
+ export function groupTransforms(transforms) {
2
+ const wrapTransforms = [];
3
+ const noWrapTransforms = [];
4
+ transforms === null || transforms === void 0 ? void 0 : transforms.forEach(transform => {
5
+ if (transform.noWrap) {
6
+ noWrapTransforms.push(transform);
7
+ }
8
+ else {
9
+ wrapTransforms.push(transform);
10
+ }
11
+ });
12
+ return { wrapTransforms, noWrapTransforms };
13
+ }
package/esm/index.js ADDED
@@ -0,0 +1,17 @@
1
+ export * from './read-file-or-url.js';
2
+ export * from './load-from-module-export-expression.js';
3
+ export * from './with-cancel.js';
4
+ export * from './extract-resolvers.js';
5
+ export * from './group-transforms.js';
6
+ export * from './apply-transforms.js';
7
+ export * from './fs-operations.js';
8
+ export * from './global-lru-cache.js';
9
+ export * from './sanitize-name-for-graphql.js';
10
+ export * from './resolve-additional-resolvers.js';
11
+ export * from './logger.js';
12
+ export * from './parseAndPrintWithCache.js';
13
+ export * from './defaultImportFn.js';
14
+ export * from './pubsub.js';
15
+ export * from './fileURLToPath.js';
16
+ export * from './getHeadersObj.js';
17
+ export * from './with-cookies.js';
@@ -0,0 +1,25 @@
1
+ /* eslint-disable @typescript-eslint/return-await */
2
+ import { path } from '@graphql-mesh/cross-helpers';
3
+ import { defaultImportFn } from './defaultImportFn.js';
4
+ export async function loadFromModuleExportExpression(expression, options) {
5
+ if (typeof expression !== 'string') {
6
+ return Promise.resolve(expression);
7
+ }
8
+ const { defaultExportName, cwd, importFn = defaultImportFn } = options || {};
9
+ const [modulePath, exportName = defaultExportName] = expression.split('#');
10
+ const mod = await tryImport(modulePath, cwd, importFn);
11
+ return mod[exportName] || (mod.default && mod.default[exportName]) || mod.default || mod;
12
+ }
13
+ async function tryImport(modulePath, cwd, importFn) {
14
+ try {
15
+ return await importFn(modulePath);
16
+ }
17
+ catch (_a) {
18
+ if (!path.isAbsolute(modulePath)) {
19
+ const absoluteModulePath = path.isAbsolute(modulePath)
20
+ ? modulePath
21
+ : path.join(cwd, modulePath);
22
+ return importFn(absoluteModulePath);
23
+ }
24
+ }
25
+ }
package/esm/logger.js ADDED
@@ -0,0 +1,118 @@
1
+ import { process, util } from '@graphql-mesh/cross-helpers';
2
+ const ANSI_CODES = {
3
+ black: '\x1b[30m',
4
+ red: '\x1b[31m',
5
+ green: '\x1b[32m',
6
+ yellow: '\x1b[33m',
7
+ blue: '\x1b[34m',
8
+ magenta: '\x1b[35m',
9
+ cyan: '\x1b[36m',
10
+ white: '\x1b[37m',
11
+ reset: '\x1b[0m',
12
+ bold: '\x1b[1m',
13
+ orange: '\x1b[48:5:166m',
14
+ };
15
+ export const warnColor = msg => ANSI_CODES.orange + msg + ANSI_CODES.reset;
16
+ export const infoColor = msg => ANSI_CODES.cyan + msg + ANSI_CODES.reset;
17
+ export const errorColor = msg => ANSI_CODES.red + msg + ANSI_CODES.reset;
18
+ export const debugColor = msg => ANSI_CODES.magenta + msg + ANSI_CODES.reset;
19
+ export const titleBold = msg => ANSI_CODES.bold + msg + ANSI_CODES.reset;
20
+ export class DefaultLogger {
21
+ constructor(name) {
22
+ this.name = name;
23
+ }
24
+ getLoggerMessage({ args = [], trim = !this.isDebug }) {
25
+ return args
26
+ .flat(Infinity)
27
+ .map(arg => {
28
+ if (typeof arg === 'string') {
29
+ if (trim && arg.length > 100) {
30
+ return (arg.slice(0, 100) +
31
+ '...' +
32
+ '<Error message is too long. Enable DEBUG=1 to see the full message.>');
33
+ }
34
+ return arg;
35
+ }
36
+ else if (typeof arg === 'object' && (arg === null || arg === void 0 ? void 0 : arg.stack) != null) {
37
+ return arg.stack;
38
+ }
39
+ return util.inspect(arg);
40
+ })
41
+ .join(` `);
42
+ }
43
+ handleLazyMessage({ lazyArgs, trim }) {
44
+ const flattenedArgs = lazyArgs.flat(Infinity).flatMap(arg => {
45
+ if (typeof arg === 'function') {
46
+ return arg();
47
+ }
48
+ return arg;
49
+ });
50
+ return this.getLoggerMessage({
51
+ args: flattenedArgs,
52
+ trim,
53
+ });
54
+ }
55
+ get isDebug() {
56
+ return (process.env.DEBUG === '1' ||
57
+ globalThis.DEBUG === '1' ||
58
+ this.name.includes(process.env.DEBUG || globalThis.DEBUG));
59
+ }
60
+ get prefix() {
61
+ return this.name ? titleBold(this.name) : ``;
62
+ }
63
+ log(...args) {
64
+ const message = this.getLoggerMessage({
65
+ args,
66
+ });
67
+ return console.log(`${this.prefix} ${message}`);
68
+ }
69
+ warn(...args) {
70
+ const message = this.getLoggerMessage({
71
+ args,
72
+ });
73
+ const fullMessage = `⚠️ ${this.prefix} ${warnColor(message)}`;
74
+ if (console.warn) {
75
+ console.warn(fullMessage);
76
+ }
77
+ else {
78
+ console.log(fullMessage);
79
+ }
80
+ }
81
+ info(...args) {
82
+ const message = this.getLoggerMessage({
83
+ args,
84
+ });
85
+ const fullMessage = `💡 ${this.prefix} ${infoColor(message)}`;
86
+ if (console.info) {
87
+ console.info(fullMessage);
88
+ }
89
+ else {
90
+ console.log(fullMessage);
91
+ }
92
+ }
93
+ error(...args) {
94
+ const message = this.getLoggerMessage({
95
+ args,
96
+ trim: false,
97
+ });
98
+ const fullMessage = `💥 ${this.prefix} ${errorColor(message)}`;
99
+ console.log(fullMessage);
100
+ }
101
+ debug(...lazyArgs) {
102
+ if (this.isDebug) {
103
+ const message = this.handleLazyMessage({
104
+ lazyArgs,
105
+ });
106
+ const fullMessage = `🐛 ${this.prefix} ${debugColor(message)}`;
107
+ if (console.debug) {
108
+ console.debug(fullMessage);
109
+ }
110
+ else {
111
+ console.log(fullMessage);
112
+ }
113
+ }
114
+ }
115
+ child(name) {
116
+ return new DefaultLogger(this.name ? `${this.name} - ${name}` : name);
117
+ }
118
+ }
@@ -0,0 +1,37 @@
1
+ import { parse, print } from 'graphql';
2
+ import { memoize1 } from '@graphql-tools/utils';
3
+ import { createLruCache } from './global-lru-cache.js';
4
+ const parseCache = createLruCache(1000, 3600);
5
+ const printCache = createLruCache(1000, 3600);
6
+ export function parseWithCache(sdl) {
7
+ const trimmedSdl = sdl.trim();
8
+ let document = parseCache.get(trimmedSdl);
9
+ if (!document) {
10
+ document = parse(trimmedSdl, { noLocation: true });
11
+ parseCache.set(trimmedSdl, document);
12
+ printCache.set(JSON.stringify(document), trimmedSdl);
13
+ }
14
+ return document;
15
+ }
16
+ export const printWithCache = memoize1(function printWithCache(document) {
17
+ const stringifedDocumentJson = JSON.stringify(document);
18
+ let sdl = printCache.get(stringifedDocumentJson);
19
+ if (!sdl) {
20
+ sdl = print(document).trim();
21
+ printCache.set(stringifedDocumentJson, sdl);
22
+ parseCache.set(sdl, document);
23
+ }
24
+ return sdl;
25
+ });
26
+ export function gql([sdl], ...args) {
27
+ let result = sdl;
28
+ for (const arg of args || []) {
29
+ if (typeof arg === 'string') {
30
+ result += arg;
31
+ }
32
+ else {
33
+ result += printWithCache(arg);
34
+ }
35
+ }
36
+ return parseWithCache(result);
37
+ }
package/esm/pubsub.js ADDED
@@ -0,0 +1,53 @@
1
+ import { observableToAsyncIterable } from '@graphql-tools/utils';
2
+ export class PubSub {
3
+ constructor() {
4
+ this.subIdListenerMap = new Map();
5
+ this.listenerEventMap = new Map();
6
+ this.eventNameListenersMap = new Map();
7
+ }
8
+ getEventNames() {
9
+ return this.eventNameListenersMap.keys();
10
+ }
11
+ publish(triggerName, detail) {
12
+ const eventNameListeners = this.eventNameListenersMap.get(triggerName);
13
+ if (eventNameListeners) {
14
+ Promise.allSettled([...eventNameListeners].map(listener => listener(detail))).catch(e => console.error(e));
15
+ }
16
+ }
17
+ subscribe(triggerName, onMessage) {
18
+ let eventNameListeners = this.eventNameListenersMap.get(triggerName);
19
+ if (!eventNameListeners) {
20
+ eventNameListeners = new Set();
21
+ this.eventNameListenersMap.set(triggerName, eventNameListeners);
22
+ }
23
+ const subId = Date.now();
24
+ eventNameListeners.add(onMessage);
25
+ this.subIdListenerMap.set(subId, onMessage);
26
+ this.listenerEventMap.set(onMessage, triggerName);
27
+ return subId;
28
+ }
29
+ unsubscribe(subId) {
30
+ const listener = this.subIdListenerMap.get(subId);
31
+ if (listener) {
32
+ this.subIdListenerMap.delete(subId);
33
+ const eventName = this.listenerEventMap.get(listener);
34
+ if (eventName) {
35
+ const eventNameListeners = this.eventNameListenersMap.get(eventName);
36
+ if (eventNameListeners) {
37
+ eventNameListeners.delete(listener);
38
+ }
39
+ }
40
+ }
41
+ this.listenerEventMap.delete(listener);
42
+ }
43
+ asyncIterator(triggerName) {
44
+ return observableToAsyncIterable({
45
+ subscribe: observer => {
46
+ const subId = this.subscribe(triggerName, data => observer.next(data));
47
+ return {
48
+ unsubscribe: () => this.unsubscribe(subId),
49
+ };
50
+ },
51
+ });
52
+ }
53
+ }