@graphql-tools/utils 8.7.0 → 8.8.0-alpha-6c480b2d.0

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 (161) hide show
  1. package/cjs/AggregateError.js +25 -0
  2. package/cjs/Interfaces.js +31 -0
  3. package/cjs/addTypes.js +62 -0
  4. package/cjs/astFromType.js +31 -0
  5. package/cjs/astFromValueUntyped.js +78 -0
  6. package/cjs/build-operation-for-field.js +351 -0
  7. package/cjs/collectFields.js +98 -0
  8. package/cjs/comments.js +380 -0
  9. package/cjs/errors.js +22 -0
  10. package/cjs/executor.js +2 -0
  11. package/cjs/fields.js +115 -0
  12. package/cjs/filterSchema.js +66 -0
  13. package/cjs/fixSchemaAst.js +26 -0
  14. package/cjs/forEachDefaultValue.js +29 -0
  15. package/cjs/forEachField.js +19 -0
  16. package/cjs/get-directives.js +103 -0
  17. package/cjs/get-fields-with-directives.js +52 -0
  18. package/cjs/get-implementing-types.js +19 -0
  19. package/cjs/getArgumentValues.js +76 -0
  20. package/cjs/getObjectTypeFromTypeMap.js +13 -0
  21. package/cjs/getOperationASTFromRequest.js +16 -0
  22. package/cjs/getResolversFromSchema.js +73 -0
  23. package/cjs/getResponseKeyFromInfo.js +12 -0
  24. package/cjs/heal.js +177 -0
  25. package/cjs/helpers.js +76 -0
  26. package/cjs/implementsAbstractType.js +17 -0
  27. package/cjs/index.js +53 -0
  28. package/cjs/inspect.js +107 -0
  29. package/cjs/isAsyncIterable.js +10 -0
  30. package/cjs/isDocumentNode.js +8 -0
  31. package/cjs/loaders.js +2 -0
  32. package/cjs/mapAsyncIterator.js +53 -0
  33. package/cjs/mapSchema.js +470 -0
  34. package/cjs/memoize.js +189 -0
  35. package/cjs/mergeDeep.js +45 -0
  36. package/cjs/observableToAsyncIterable.js +85 -0
  37. package/cjs/package.json +1 -0
  38. package/cjs/parse-graphql-json.js +44 -0
  39. package/cjs/parse-graphql-sdl.js +84 -0
  40. package/cjs/print-schema-with-directives.js +494 -0
  41. package/cjs/prune.js +133 -0
  42. package/cjs/renameType.js +152 -0
  43. package/cjs/rewire.js +159 -0
  44. package/cjs/rootTypes.js +37 -0
  45. package/cjs/selectionSets.js +9 -0
  46. package/cjs/stub.js +68 -0
  47. package/cjs/transformInputValue.js +55 -0
  48. package/cjs/types.js +27 -0
  49. package/cjs/updateArgument.js +54 -0
  50. package/cjs/validate-documents.js +76 -0
  51. package/cjs/valueMatchesCriteria.js +21 -0
  52. package/cjs/visitResult.js +229 -0
  53. package/cjs/withCancel.js +56 -0
  54. package/esm/AggregateError.js +21 -0
  55. package/esm/Interfaces.js +28 -0
  56. package/esm/addTypes.js +58 -0
  57. package/esm/astFromType.js +27 -0
  58. package/esm/astFromValueUntyped.js +74 -0
  59. package/esm/build-operation-for-field.js +347 -0
  60. package/esm/collectFields.js +94 -0
  61. package/esm/comments.js +367 -0
  62. package/esm/errors.js +17 -0
  63. package/esm/executor.js +1 -0
  64. package/esm/fields.js +108 -0
  65. package/esm/filterSchema.js +62 -0
  66. package/esm/fixSchemaAst.js +22 -0
  67. package/esm/forEachDefaultValue.js +25 -0
  68. package/esm/forEachField.js +15 -0
  69. package/esm/get-directives.js +96 -0
  70. package/esm/get-fields-with-directives.js +48 -0
  71. package/esm/get-implementing-types.js +15 -0
  72. package/esm/getArgumentValues.js +72 -0
  73. package/esm/getObjectTypeFromTypeMap.js +9 -0
  74. package/esm/getOperationASTFromRequest.js +12 -0
  75. package/esm/getResolversFromSchema.js +69 -0
  76. package/esm/getResponseKeyFromInfo.js +8 -0
  77. package/esm/heal.js +172 -0
  78. package/esm/helpers.js +65 -0
  79. package/esm/implementsAbstractType.js +13 -0
  80. package/esm/index.js +50 -0
  81. package/esm/inspect.js +103 -0
  82. package/esm/isAsyncIterable.js +6 -0
  83. package/esm/isDocumentNode.js +4 -0
  84. package/esm/loaders.js +1 -0
  85. package/esm/mapAsyncIterator.js +49 -0
  86. package/esm/mapSchema.js +465 -0
  87. package/esm/memoize.js +180 -0
  88. package/esm/mergeDeep.js +41 -0
  89. package/esm/observableToAsyncIterable.js +81 -0
  90. package/esm/parse-graphql-json.js +40 -0
  91. package/esm/parse-graphql-sdl.js +78 -0
  92. package/esm/print-schema-with-directives.js +472 -0
  93. package/esm/prune.js +129 -0
  94. package/esm/renameType.js +148 -0
  95. package/esm/rewire.js +155 -0
  96. package/esm/rootTypes.js +33 -0
  97. package/esm/selectionSets.js +5 -0
  98. package/esm/stub.js +61 -0
  99. package/esm/transformInputValue.js +48 -0
  100. package/esm/types.js +24 -0
  101. package/esm/updateArgument.js +49 -0
  102. package/esm/validate-documents.js +70 -0
  103. package/esm/valueMatchesCriteria.js +17 -0
  104. package/esm/visitResult.js +223 -0
  105. package/esm/withCancel.js +51 -0
  106. package/package.json +31 -10
  107. package/{AggregateError.d.ts → typings/AggregateError.d.ts} +0 -0
  108. package/{Interfaces.d.ts → typings/Interfaces.d.ts} +0 -0
  109. package/{addTypes.d.ts → typings/addTypes.d.ts} +0 -0
  110. package/{astFromType.d.ts → typings/astFromType.d.ts} +0 -0
  111. package/{astFromValueUntyped.d.ts → typings/astFromValueUntyped.d.ts} +0 -0
  112. package/{build-operation-for-field.d.ts → typings/build-operation-for-field.d.ts} +0 -0
  113. package/{collectFields.d.ts → typings/collectFields.d.ts} +0 -0
  114. package/{comments.d.ts → typings/comments.d.ts} +0 -0
  115. package/{errors.d.ts → typings/errors.d.ts} +1 -1
  116. package/{executor.d.ts → typings/executor.d.ts} +1 -1
  117. package/{fields.d.ts → typings/fields.d.ts} +0 -0
  118. package/{filterSchema.d.ts → typings/filterSchema.d.ts} +1 -1
  119. package/{fixSchemaAst.d.ts → typings/fixSchemaAst.d.ts} +1 -1
  120. package/{forEachDefaultValue.d.ts → typings/forEachDefaultValue.d.ts} +1 -1
  121. package/{forEachField.d.ts → typings/forEachField.d.ts} +1 -1
  122. package/{get-directives.d.ts → typings/get-directives.d.ts} +0 -0
  123. package/{get-fields-with-directives.d.ts → typings/get-fields-with-directives.d.ts} +0 -0
  124. package/{get-implementing-types.d.ts → typings/get-implementing-types.d.ts} +0 -0
  125. package/{getArgumentValues.d.ts → typings/getArgumentValues.d.ts} +0 -0
  126. package/{getObjectTypeFromTypeMap.d.ts → typings/getObjectTypeFromTypeMap.d.ts} +1 -1
  127. package/{getOperationASTFromRequest.d.ts → typings/getOperationASTFromRequest.d.ts} +1 -1
  128. package/{getResolversFromSchema.d.ts → typings/getResolversFromSchema.d.ts} +1 -1
  129. package/{getResponseKeyFromInfo.d.ts → typings/getResponseKeyFromInfo.d.ts} +0 -0
  130. package/{heal.d.ts → typings/heal.d.ts} +0 -0
  131. package/{helpers.d.ts → typings/helpers.d.ts} +0 -0
  132. package/{implementsAbstractType.d.ts → typings/implementsAbstractType.d.ts} +1 -1
  133. package/typings/index.d.ts +50 -0
  134. package/{inspect.d.ts → typings/inspect.d.ts} +0 -0
  135. package/{isAsyncIterable.d.ts → typings/isAsyncIterable.d.ts} +0 -0
  136. package/{isDocumentNode.d.ts → typings/isDocumentNode.d.ts} +0 -0
  137. package/{loaders.d.ts → typings/loaders.d.ts} +1 -1
  138. package/{mapAsyncIterator.d.ts → typings/mapAsyncIterator.d.ts} +0 -0
  139. package/{mapSchema.d.ts → typings/mapSchema.d.ts} +1 -1
  140. package/{memoize.d.ts → typings/memoize.d.ts} +0 -0
  141. package/{mergeDeep.d.ts → typings/mergeDeep.d.ts} +0 -0
  142. package/{observableToAsyncIterable.d.ts → typings/observableToAsyncIterable.d.ts} +0 -0
  143. package/{parse-graphql-json.d.ts → typings/parse-graphql-json.d.ts} +2 -2
  144. package/{parse-graphql-sdl.d.ts → typings/parse-graphql-sdl.d.ts} +1 -1
  145. package/{print-schema-with-directives.d.ts → typings/print-schema-with-directives.d.ts} +1 -1
  146. package/{prune.d.ts → typings/prune.d.ts} +1 -1
  147. package/{renameType.d.ts → typings/renameType.d.ts} +0 -0
  148. package/{rewire.d.ts → typings/rewire.d.ts} +0 -0
  149. package/{rootTypes.d.ts → typings/rootTypes.d.ts} +0 -0
  150. package/{selectionSets.d.ts → typings/selectionSets.d.ts} +1 -1
  151. package/{stub.d.ts → typings/stub.d.ts} +0 -0
  152. package/{transformInputValue.d.ts → typings/transformInputValue.d.ts} +1 -1
  153. package/{types.d.ts → typings/types.d.ts} +0 -0
  154. package/{updateArgument.d.ts → typings/updateArgument.d.ts} +0 -0
  155. package/{validate-documents.d.ts → typings/validate-documents.d.ts} +1 -1
  156. package/{valueMatchesCriteria.d.ts → typings/valueMatchesCriteria.d.ts} +0 -0
  157. package/{visitResult.d.ts → typings/visitResult.d.ts} +1 -1
  158. package/{withCancel.d.ts → typings/withCancel.d.ts} +0 -0
  159. package/index.d.ts +0 -50
  160. package/index.js +0 -4428
  161. package/index.mjs +0 -4315
package/index.js DELETED
@@ -1,4428 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const graphql = require('graphql');
6
-
7
- const asArray = (fns) => (Array.isArray(fns) ? fns : fns ? [fns] : []);
8
- const invalidDocRegex = /\.[a-z0-9]+$/i;
9
- function isDocumentString(str) {
10
- if (typeof str !== 'string') {
11
- return false;
12
- }
13
- // XXX: is-valid-path or is-glob treat SDL as a valid path
14
- // (`scalar Date` for example)
15
- // this why checking the extension is fast enough
16
- // and prevent from parsing the string in order to find out
17
- // if the string is a SDL
18
- if (invalidDocRegex.test(str)) {
19
- return false;
20
- }
21
- try {
22
- graphql.parse(str);
23
- return true;
24
- }
25
- catch (e) { }
26
- return false;
27
- }
28
- const invalidPathRegex = /[‘“!%&^<=>`]/;
29
- function isValidPath(str) {
30
- return typeof str === 'string' && !invalidPathRegex.test(str);
31
- }
32
- function compareStrings(a, b) {
33
- if (String(a) < String(b)) {
34
- return -1;
35
- }
36
- if (String(a) > String(b)) {
37
- return 1;
38
- }
39
- return 0;
40
- }
41
- function nodeToString(a) {
42
- var _a, _b;
43
- let name;
44
- if ('alias' in a) {
45
- name = (_a = a.alias) === null || _a === void 0 ? void 0 : _a.value;
46
- }
47
- if (name == null && 'name' in a) {
48
- name = (_b = a.name) === null || _b === void 0 ? void 0 : _b.value;
49
- }
50
- if (name == null) {
51
- name = a.kind;
52
- }
53
- return name;
54
- }
55
- function compareNodes(a, b, customFn) {
56
- const aStr = nodeToString(a);
57
- const bStr = nodeToString(b);
58
- if (typeof customFn === 'function') {
59
- return customFn(aStr, bStr);
60
- }
61
- return compareStrings(aStr, bStr);
62
- }
63
- function isSome(input) {
64
- return input != null;
65
- }
66
- function assertSome(input, message = 'Value should be something') {
67
- if (input == null) {
68
- throw new Error(message);
69
- }
70
- }
71
-
72
- function createGraphQLError(message, options) {
73
- if (graphql.versionInfo.major >= 17) {
74
- return new graphql.GraphQLError(message, options);
75
- }
76
- return new graphql.GraphQLError(message, options === null || options === void 0 ? void 0 : options.nodes, options === null || options === void 0 ? void 0 : options.source, options === null || options === void 0 ? void 0 : options.positions, options === null || options === void 0 ? void 0 : options.path, options === null || options === void 0 ? void 0 : options.originalError, options === null || options === void 0 ? void 0 : options.extensions);
77
- }
78
- function relocatedError(originalError, path) {
79
- return createGraphQLError(originalError.message, {
80
- nodes: originalError.nodes,
81
- source: originalError.source,
82
- positions: originalError.positions,
83
- path: path == null ? originalError.path : path,
84
- originalError,
85
- extensions: originalError.extensions,
86
- });
87
- }
88
-
89
- if (typeof AggregateError === 'undefined') {
90
- class AggregateErrorClass extends Error {
91
- constructor(errors, message = '') {
92
- super(message);
93
- this.errors = errors;
94
- this.name = 'AggregateError';
95
- Error.captureStackTrace(this, AggregateErrorClass);
96
- }
97
- }
98
- exports.AggregateError = function (errors, message) {
99
- return new AggregateErrorClass(errors, message);
100
- };
101
- }
102
- else {
103
- exports.AggregateError = AggregateError;
104
- }
105
- function isAggregateError(error) {
106
- return 'errors' in error && Array.isArray(error['errors']);
107
- }
108
-
109
- // Taken from graphql-js
110
- const MAX_RECURSIVE_DEPTH = 3;
111
- /**
112
- * Used to print values in error messages.
113
- */
114
- function inspect(value) {
115
- return formatValue(value, []);
116
- }
117
- function formatValue(value, seenValues) {
118
- switch (typeof value) {
119
- case 'string':
120
- return JSON.stringify(value);
121
- case 'function':
122
- return value.name ? `[function ${value.name}]` : '[function]';
123
- case 'object':
124
- return formatObjectValue(value, seenValues);
125
- default:
126
- return String(value);
127
- }
128
- }
129
- function formatError(value) {
130
- if (value instanceof graphql.GraphQLError) {
131
- return value.toString();
132
- }
133
- return `${value.name}: ${value.message};\n ${value.stack}`;
134
- }
135
- function formatObjectValue(value, previouslySeenValues) {
136
- if (value === null) {
137
- return 'null';
138
- }
139
- if (value instanceof Error) {
140
- if (isAggregateError(value)) {
141
- return formatError(value) + '\n' + formatArray(value.errors, previouslySeenValues);
142
- }
143
- return formatError(value);
144
- }
145
- if (previouslySeenValues.includes(value)) {
146
- return '[Circular]';
147
- }
148
- const seenValues = [...previouslySeenValues, value];
149
- if (isJSONable(value)) {
150
- const jsonValue = value.toJSON();
151
- // check for infinite recursion
152
- if (jsonValue !== value) {
153
- return typeof jsonValue === 'string' ? jsonValue : formatValue(jsonValue, seenValues);
154
- }
155
- }
156
- else if (Array.isArray(value)) {
157
- return formatArray(value, seenValues);
158
- }
159
- return formatObject(value, seenValues);
160
- }
161
- function isJSONable(value) {
162
- return typeof value.toJSON === 'function';
163
- }
164
- function formatObject(object, seenValues) {
165
- const entries = Object.entries(object);
166
- if (entries.length === 0) {
167
- return '{}';
168
- }
169
- if (seenValues.length > MAX_RECURSIVE_DEPTH) {
170
- return '[' + getObjectTag(object) + ']';
171
- }
172
- const properties = entries.map(([key, value]) => key + ': ' + formatValue(value, seenValues));
173
- return '{ ' + properties.join(', ') + ' }';
174
- }
175
- function formatArray(array, seenValues) {
176
- if (array.length === 0) {
177
- return '[]';
178
- }
179
- if (seenValues.length > MAX_RECURSIVE_DEPTH) {
180
- return '[Array]';
181
- }
182
- const len = array.length;
183
- const remaining = array.length;
184
- const items = [];
185
- for (let i = 0; i < len; ++i) {
186
- items.push(formatValue(array[i], seenValues));
187
- }
188
- if (remaining === 1) {
189
- items.push('... 1 more item');
190
- }
191
- else if (remaining > 1) {
192
- items.push(`... ${remaining} more items`);
193
- }
194
- return '[' + items.join(', ') + ']';
195
- }
196
- function getObjectTag(object) {
197
- const tag = Object.prototype.toString
198
- .call(object)
199
- .replace(/^\[object /, '')
200
- .replace(/]$/, '');
201
- if (tag === 'Object' && typeof object.constructor === 'function') {
202
- const name = object.constructor.name;
203
- if (typeof name === 'string' && name !== '') {
204
- return name;
205
- }
206
- }
207
- return tag;
208
- }
209
-
210
- /**
211
- * Prepares an object map of argument values given a list of argument
212
- * definitions and list of argument AST nodes.
213
- *
214
- * Note: The returned value is a plain Object with a prototype, since it is
215
- * exposed to user code. Care should be taken to not pull values from the
216
- * Object prototype.
217
- */
218
- function getArgumentValues(def, node, variableValues = {}) {
219
- var _a;
220
- const variableMap = Object.entries(variableValues).reduce((prev, [key, value]) => ({
221
- ...prev,
222
- [key]: value,
223
- }), {});
224
- const coercedValues = {};
225
- const argumentNodes = (_a = node.arguments) !== null && _a !== void 0 ? _a : [];
226
- const argNodeMap = argumentNodes.reduce((prev, arg) => ({
227
- ...prev,
228
- [arg.name.value]: arg,
229
- }), {});
230
- for (const { name, type: argType, defaultValue } of def.args) {
231
- const argumentNode = argNodeMap[name];
232
- if (!argumentNode) {
233
- if (defaultValue !== undefined) {
234
- coercedValues[name] = defaultValue;
235
- }
236
- else if (graphql.isNonNullType(argType)) {
237
- throw createGraphQLError(`Argument "${name}" of required type "${inspect(argType)}" ` + 'was not provided.', {
238
- nodes: [node],
239
- });
240
- }
241
- continue;
242
- }
243
- const valueNode = argumentNode.value;
244
- let isNull = valueNode.kind === graphql.Kind.NULL;
245
- if (valueNode.kind === graphql.Kind.VARIABLE) {
246
- const variableName = valueNode.name.value;
247
- if (variableValues == null || variableMap[variableName] == null) {
248
- if (defaultValue !== undefined) {
249
- coercedValues[name] = defaultValue;
250
- }
251
- else if (graphql.isNonNullType(argType)) {
252
- throw createGraphQLError(`Argument "${name}" of required type "${inspect(argType)}" ` +
253
- `was provided the variable "$${variableName}" which was not provided a runtime value.`, {
254
- nodes: [valueNode],
255
- });
256
- }
257
- continue;
258
- }
259
- isNull = variableValues[variableName] == null;
260
- }
261
- if (isNull && graphql.isNonNullType(argType)) {
262
- throw createGraphQLError(`Argument "${name}" of non-null type "${inspect(argType)}" ` + 'must not be null.', {
263
- nodes: [valueNode],
264
- });
265
- }
266
- const coercedValue = graphql.valueFromAST(valueNode, argType, variableValues);
267
- if (coercedValue === undefined) {
268
- // Note: ValuesOfCorrectTypeRule validation should catch this before
269
- // execution. This is a runtime check to ensure execution does not
270
- // continue with an invalid argument value.
271
- throw createGraphQLError(`Argument "${name}" has invalid value ${graphql.print(valueNode)}.`, {
272
- nodes: [valueNode],
273
- });
274
- }
275
- coercedValues[name] = coercedValue;
276
- }
277
- return coercedValues;
278
- }
279
-
280
- function getDirectivesInExtensions(node, pathToDirectivesInExtensions = ['directives']) {
281
- return pathToDirectivesInExtensions.reduce((acc, pathSegment) => (acc == null ? acc : acc[pathSegment]), node === null || node === void 0 ? void 0 : node.extensions);
282
- }
283
- function _getDirectiveInExtensions(directivesInExtensions, directiveName) {
284
- const directiveInExtensions = directivesInExtensions.filter(directiveAnnotation => directiveAnnotation.name === directiveName);
285
- if (!directiveInExtensions.length) {
286
- return undefined;
287
- }
288
- return directiveInExtensions.map(directive => { var _a; return (_a = directive.args) !== null && _a !== void 0 ? _a : {}; });
289
- }
290
- function getDirectiveInExtensions(node, directiveName, pathToDirectivesInExtensions = ['directives']) {
291
- const directivesInExtensions = pathToDirectivesInExtensions.reduce((acc, pathSegment) => (acc == null ? acc : acc[pathSegment]), node === null || node === void 0 ? void 0 : node.extensions);
292
- if (directivesInExtensions === undefined) {
293
- return undefined;
294
- }
295
- if (Array.isArray(directivesInExtensions)) {
296
- return _getDirectiveInExtensions(directivesInExtensions, directiveName);
297
- }
298
- // Support condensed format by converting to longer format
299
- // The condensed format does not preserve ordering of directives when repeatable directives are used.
300
- // See https://github.com/ardatan/graphql-tools/issues/2534
301
- const reformattedDirectivesInExtensions = [];
302
- for (const [name, argsOrArrayOfArgs] of Object.entries(directivesInExtensions)) {
303
- if (Array.isArray(argsOrArrayOfArgs)) {
304
- for (const args of argsOrArrayOfArgs) {
305
- reformattedDirectivesInExtensions.push({ name, args });
306
- }
307
- }
308
- else {
309
- reformattedDirectivesInExtensions.push({ name, args: argsOrArrayOfArgs });
310
- }
311
- }
312
- return _getDirectiveInExtensions(reformattedDirectivesInExtensions, directiveName);
313
- }
314
- function getDirectives(schema, node, pathToDirectivesInExtensions = ['directives']) {
315
- const directivesInExtensions = getDirectivesInExtensions(node, pathToDirectivesInExtensions);
316
- if (directivesInExtensions != null && directivesInExtensions.length > 0) {
317
- return directivesInExtensions;
318
- }
319
- const schemaDirectives = schema && schema.getDirectives ? schema.getDirectives() : [];
320
- const schemaDirectiveMap = schemaDirectives.reduce((schemaDirectiveMap, schemaDirective) => {
321
- schemaDirectiveMap[schemaDirective.name] = schemaDirective;
322
- return schemaDirectiveMap;
323
- }, {});
324
- let astNodes = [];
325
- if (node.astNode) {
326
- astNodes.push(node.astNode);
327
- }
328
- if ('extensionASTNodes' in node && node.extensionASTNodes) {
329
- astNodes = [...astNodes, ...node.extensionASTNodes];
330
- }
331
- const result = [];
332
- for (const astNode of astNodes) {
333
- if (astNode.directives) {
334
- for (const directiveNode of astNode.directives) {
335
- const schemaDirective = schemaDirectiveMap[directiveNode.name.value];
336
- if (schemaDirective) {
337
- result.push({ name: directiveNode.name.value, args: getArgumentValues(schemaDirective, directiveNode) });
338
- }
339
- }
340
- }
341
- }
342
- return result;
343
- }
344
- function getDirective(schema, node, directiveName, pathToDirectivesInExtensions = ['directives']) {
345
- const directiveInExtensions = getDirectiveInExtensions(node, directiveName, pathToDirectivesInExtensions);
346
- if (directiveInExtensions != null) {
347
- return directiveInExtensions;
348
- }
349
- const schemaDirective = schema && schema.getDirective ? schema.getDirective(directiveName) : undefined;
350
- if (schemaDirective == null) {
351
- return undefined;
352
- }
353
- let astNodes = [];
354
- if (node.astNode) {
355
- astNodes.push(node.astNode);
356
- }
357
- if ('extensionASTNodes' in node && node.extensionASTNodes) {
358
- astNodes = [...astNodes, ...node.extensionASTNodes];
359
- }
360
- const result = [];
361
- for (const astNode of astNodes) {
362
- if (astNode.directives) {
363
- for (const directiveNode of astNode.directives) {
364
- if (directiveNode.name.value === directiveName) {
365
- result.push(getArgumentValues(schemaDirective, directiveNode));
366
- }
367
- }
368
- }
369
- }
370
- if (!result.length) {
371
- return undefined;
372
- }
373
- return result;
374
- }
375
-
376
- function parseDirectiveValue(value) {
377
- switch (value.kind) {
378
- case graphql.Kind.INT:
379
- return parseInt(value.value);
380
- case graphql.Kind.FLOAT:
381
- return parseFloat(value.value);
382
- case graphql.Kind.BOOLEAN:
383
- return Boolean(value.value);
384
- case graphql.Kind.STRING:
385
- case graphql.Kind.ENUM:
386
- return value.value;
387
- case graphql.Kind.LIST:
388
- return value.values.map(v => parseDirectiveValue(v));
389
- case graphql.Kind.OBJECT:
390
- return value.fields.reduce((prev, v) => ({ ...prev, [v.name.value]: parseDirectiveValue(v.value) }), {});
391
- case graphql.Kind.NULL:
392
- return null;
393
- default:
394
- return null;
395
- }
396
- }
397
- function getFieldsWithDirectives(documentNode, options = {}) {
398
- const result = {};
399
- let selected = ['ObjectTypeDefinition', 'ObjectTypeExtension'];
400
- if (options.includeInputTypes) {
401
- selected = [...selected, 'InputObjectTypeDefinition', 'InputObjectTypeExtension'];
402
- }
403
- const allTypes = documentNode.definitions.filter(obj => selected.includes(obj.kind));
404
- for (const type of allTypes) {
405
- const typeName = type.name.value;
406
- if (type.fields == null) {
407
- continue;
408
- }
409
- for (const field of type.fields) {
410
- if (field.directives && field.directives.length > 0) {
411
- const fieldName = field.name.value;
412
- const key = `${typeName}.${fieldName}`;
413
- const directives = field.directives.map(d => ({
414
- name: d.name.value,
415
- args: (d.arguments || []).reduce((prev, arg) => ({ ...prev, [arg.name.value]: parseDirectiveValue(arg.value) }), {}),
416
- }));
417
- result[key] = directives;
418
- }
419
- }
420
- }
421
- return result;
422
- }
423
-
424
- function getImplementingTypes(interfaceName, schema) {
425
- const allTypesMap = schema.getTypeMap();
426
- const result = [];
427
- for (const graphqlTypeName in allTypesMap) {
428
- const graphqlType = allTypesMap[graphqlTypeName];
429
- if (graphql.isObjectType(graphqlType)) {
430
- const allInterfaces = graphqlType.getInterfaces();
431
- if (allInterfaces.find(int => int.name === interfaceName)) {
432
- result.push(graphqlType.name);
433
- }
434
- }
435
- }
436
- return result;
437
- }
438
-
439
- function astFromType(type) {
440
- if (graphql.isNonNullType(type)) {
441
- const innerType = astFromType(type.ofType);
442
- if (innerType.kind === graphql.Kind.NON_NULL_TYPE) {
443
- throw new Error(`Invalid type node ${inspect(type)}. Inner type of non-null type cannot be a non-null type.`);
444
- }
445
- return {
446
- kind: graphql.Kind.NON_NULL_TYPE,
447
- type: innerType,
448
- };
449
- }
450
- else if (graphql.isListType(type)) {
451
- return {
452
- kind: graphql.Kind.LIST_TYPE,
453
- type: astFromType(type.ofType),
454
- };
455
- }
456
- return {
457
- kind: graphql.Kind.NAMED_TYPE,
458
- name: {
459
- kind: graphql.Kind.NAME,
460
- value: type.name,
461
- },
462
- };
463
- }
464
-
465
- /**
466
- * Produces a GraphQL Value AST given a JavaScript object.
467
- * Function will match JavaScript/JSON values to GraphQL AST schema format
468
- * by using the following mapping.
469
- *
470
- * | JSON Value | GraphQL Value |
471
- * | ------------- | -------------------- |
472
- * | Object | Input Object |
473
- * | Array | List |
474
- * | Boolean | Boolean |
475
- * | String | String |
476
- * | Number | Int / Float |
477
- * | null | NullValue |
478
- *
479
- */
480
- function astFromValueUntyped(value) {
481
- // only explicit null, not undefined, NaN
482
- if (value === null) {
483
- return { kind: graphql.Kind.NULL };
484
- }
485
- // undefined
486
- if (value === undefined) {
487
- return null;
488
- }
489
- // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
490
- // the value is not an array, convert the value using the list's item type.
491
- if (Array.isArray(value)) {
492
- const valuesNodes = [];
493
- for (const item of value) {
494
- const itemNode = astFromValueUntyped(item);
495
- if (itemNode != null) {
496
- valuesNodes.push(itemNode);
497
- }
498
- }
499
- return { kind: graphql.Kind.LIST, values: valuesNodes };
500
- }
501
- if (typeof value === 'object') {
502
- const fieldNodes = [];
503
- for (const fieldName in value) {
504
- const fieldValue = value[fieldName];
505
- const ast = astFromValueUntyped(fieldValue);
506
- if (ast) {
507
- fieldNodes.push({
508
- kind: graphql.Kind.OBJECT_FIELD,
509
- name: { kind: graphql.Kind.NAME, value: fieldName },
510
- value: ast,
511
- });
512
- }
513
- }
514
- return { kind: graphql.Kind.OBJECT, fields: fieldNodes };
515
- }
516
- // Others serialize based on their corresponding JavaScript scalar types.
517
- if (typeof value === 'boolean') {
518
- return { kind: graphql.Kind.BOOLEAN, value };
519
- }
520
- // JavaScript numbers can be Int or Float values.
521
- if (typeof value === 'number' && isFinite(value)) {
522
- const stringNum = String(value);
523
- return integerStringRegExp.test(stringNum)
524
- ? { kind: graphql.Kind.INT, value: stringNum }
525
- : { kind: graphql.Kind.FLOAT, value: stringNum };
526
- }
527
- if (typeof value === 'string') {
528
- return { kind: graphql.Kind.STRING, value };
529
- }
530
- throw new TypeError(`Cannot convert value to AST: ${value}.`);
531
- }
532
- /**
533
- * IntValue:
534
- * - NegativeSign? 0
535
- * - NegativeSign? NonZeroDigit ( Digit+ )?
536
- */
537
- const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;
538
-
539
- function memoize1(fn) {
540
- const memoize1cache = new WeakMap();
541
- return function memoized(a1) {
542
- const cachedValue = memoize1cache.get(a1);
543
- if (cachedValue === undefined) {
544
- const newValue = fn(a1);
545
- memoize1cache.set(a1, newValue);
546
- return newValue;
547
- }
548
- return cachedValue;
549
- };
550
- }
551
- function memoize2(fn) {
552
- const memoize2cache = new WeakMap();
553
- return function memoized(a1, a2) {
554
- let cache2 = memoize2cache.get(a1);
555
- if (!cache2) {
556
- cache2 = new WeakMap();
557
- memoize2cache.set(a1, cache2);
558
- const newValue = fn(a1, a2);
559
- cache2.set(a2, newValue);
560
- return newValue;
561
- }
562
- const cachedValue = cache2.get(a2);
563
- if (cachedValue === undefined) {
564
- const newValue = fn(a1, a2);
565
- cache2.set(a2, newValue);
566
- return newValue;
567
- }
568
- return cachedValue;
569
- };
570
- }
571
- function memoize3(fn) {
572
- const memoize3Cache = new WeakMap();
573
- return function memoized(a1, a2, a3) {
574
- let cache2 = memoize3Cache.get(a1);
575
- if (!cache2) {
576
- cache2 = new WeakMap();
577
- memoize3Cache.set(a1, cache2);
578
- const cache3 = new WeakMap();
579
- cache2.set(a2, cache3);
580
- const newValue = fn(a1, a2, a3);
581
- cache3.set(a3, newValue);
582
- return newValue;
583
- }
584
- let cache3 = cache2.get(a2);
585
- if (!cache3) {
586
- cache3 = new WeakMap();
587
- cache2.set(a2, cache3);
588
- const newValue = fn(a1, a2, a3);
589
- cache3.set(a3, newValue);
590
- return newValue;
591
- }
592
- const cachedValue = cache3.get(a3);
593
- if (cachedValue === undefined) {
594
- const newValue = fn(a1, a2, a3);
595
- cache3.set(a3, newValue);
596
- return newValue;
597
- }
598
- return cachedValue;
599
- };
600
- }
601
- function memoize4(fn) {
602
- const memoize4Cache = new WeakMap();
603
- return function memoized(a1, a2, a3, a4) {
604
- let cache2 = memoize4Cache.get(a1);
605
- if (!cache2) {
606
- cache2 = new WeakMap();
607
- memoize4Cache.set(a1, cache2);
608
- const cache3 = new WeakMap();
609
- cache2.set(a2, cache3);
610
- const cache4 = new WeakMap();
611
- cache3.set(a3, cache4);
612
- const newValue = fn(a1, a2, a3, a4);
613
- cache4.set(a4, newValue);
614
- return newValue;
615
- }
616
- let cache3 = cache2.get(a2);
617
- if (!cache3) {
618
- cache3 = new WeakMap();
619
- cache2.set(a2, cache3);
620
- const cache4 = new WeakMap();
621
- cache3.set(a3, cache4);
622
- const newValue = fn(a1, a2, a3, a4);
623
- cache4.set(a4, newValue);
624
- return newValue;
625
- }
626
- const cache4 = cache3.get(a3);
627
- if (!cache4) {
628
- const cache4 = new WeakMap();
629
- cache3.set(a3, cache4);
630
- const newValue = fn(a1, a2, a3, a4);
631
- cache4.set(a4, newValue);
632
- return newValue;
633
- }
634
- const cachedValue = cache4.get(a4);
635
- if (cachedValue === undefined) {
636
- const newValue = fn(a1, a2, a3, a4);
637
- cache4.set(a4, newValue);
638
- return newValue;
639
- }
640
- return cachedValue;
641
- };
642
- }
643
- function memoize5(fn) {
644
- const memoize5Cache = new WeakMap();
645
- return function memoized(a1, a2, a3, a4, a5) {
646
- let cache2 = memoize5Cache.get(a1);
647
- if (!cache2) {
648
- cache2 = new WeakMap();
649
- memoize5Cache.set(a1, cache2);
650
- const cache3 = new WeakMap();
651
- cache2.set(a2, cache3);
652
- const cache4 = new WeakMap();
653
- cache3.set(a3, cache4);
654
- const cache5 = new WeakMap();
655
- cache4.set(a4, cache5);
656
- const newValue = fn(a1, a2, a3, a4, a5);
657
- cache5.set(a5, newValue);
658
- return newValue;
659
- }
660
- let cache3 = cache2.get(a2);
661
- if (!cache3) {
662
- cache3 = new WeakMap();
663
- cache2.set(a2, cache3);
664
- const cache4 = new WeakMap();
665
- cache3.set(a3, cache4);
666
- const cache5 = new WeakMap();
667
- cache4.set(a4, cache5);
668
- const newValue = fn(a1, a2, a3, a4, a5);
669
- cache5.set(a5, newValue);
670
- return newValue;
671
- }
672
- let cache4 = cache3.get(a3);
673
- if (!cache4) {
674
- cache4 = new WeakMap();
675
- cache3.set(a3, cache4);
676
- const cache5 = new WeakMap();
677
- cache4.set(a4, cache5);
678
- const newValue = fn(a1, a2, a3, a4, a5);
679
- cache5.set(a5, newValue);
680
- return newValue;
681
- }
682
- let cache5 = cache4.get(a4);
683
- if (!cache5) {
684
- cache5 = new WeakMap();
685
- cache4.set(a4, cache5);
686
- const newValue = fn(a1, a2, a3, a4, a5);
687
- cache5.set(a5, newValue);
688
- return newValue;
689
- }
690
- const cachedValue = cache5.get(a5);
691
- if (cachedValue === undefined) {
692
- const newValue = fn(a1, a2, a3, a4, a5);
693
- cache5.set(a5, newValue);
694
- return newValue;
695
- }
696
- return cachedValue;
697
- };
698
- }
699
- const memoize2of4cache = new WeakMap();
700
- function memoize2of4(fn) {
701
- return function memoized(a1, a2, a3, a4) {
702
- let cache2 = memoize2of4cache.get(a1);
703
- if (!cache2) {
704
- cache2 = new WeakMap();
705
- memoize2of4cache.set(a1, cache2);
706
- const newValue = fn(a1, a2, a3, a4);
707
- cache2.set(a2, newValue);
708
- return newValue;
709
- }
710
- const cachedValue = cache2.get(a2);
711
- if (cachedValue === undefined) {
712
- const newValue = fn(a1, a2, a3, a4);
713
- cache2.set(a2, newValue);
714
- return newValue;
715
- }
716
- return cachedValue;
717
- };
718
- }
719
-
720
- function getDefinedRootType(schema, operation) {
721
- const rootTypeMap = getRootTypeMap(schema);
722
- const rootType = rootTypeMap.get(operation);
723
- if (rootType == null) {
724
- throw new Error(`Root type for operation "${operation}" not defined by the given schema.`);
725
- }
726
- return rootType;
727
- }
728
- const getRootTypeNames = memoize1(function getRootTypeNames(schema) {
729
- const rootTypes = getRootTypes(schema);
730
- return new Set([...rootTypes].map(type => type.name));
731
- });
732
- const getRootTypes = memoize1(function getRootTypes(schema) {
733
- const rootTypeMap = getRootTypeMap(schema);
734
- return new Set(rootTypeMap.values());
735
- });
736
- const getRootTypeMap = memoize1(function getRootTypeMap(schema) {
737
- const rootTypeMap = new Map();
738
- const queryType = schema.getQueryType();
739
- if (queryType) {
740
- rootTypeMap.set('query', queryType);
741
- }
742
- const mutationType = schema.getMutationType();
743
- if (mutationType) {
744
- rootTypeMap.set('mutation', mutationType);
745
- }
746
- const subscriptionType = schema.getSubscriptionType();
747
- if (subscriptionType) {
748
- rootTypeMap.set('subscription', subscriptionType);
749
- }
750
- return rootTypeMap;
751
- });
752
-
753
- function getDocumentNodeFromSchema(schema, options = {}) {
754
- const pathToDirectivesInExtensions = options.pathToDirectivesInExtensions;
755
- const typesMap = schema.getTypeMap();
756
- const schemaNode = astFromSchema(schema, pathToDirectivesInExtensions);
757
- const definitions = schemaNode != null ? [schemaNode] : [];
758
- const directives = schema.getDirectives();
759
- for (const directive of directives) {
760
- if (graphql.isSpecifiedDirective(directive)) {
761
- continue;
762
- }
763
- definitions.push(astFromDirective(directive, schema, pathToDirectivesInExtensions));
764
- }
765
- for (const typeName in typesMap) {
766
- const type = typesMap[typeName];
767
- const isPredefinedScalar = graphql.isSpecifiedScalarType(type);
768
- const isIntrospection = graphql.isIntrospectionType(type);
769
- if (isPredefinedScalar || isIntrospection) {
770
- continue;
771
- }
772
- if (graphql.isObjectType(type)) {
773
- definitions.push(astFromObjectType(type, schema, pathToDirectivesInExtensions));
774
- }
775
- else if (graphql.isInterfaceType(type)) {
776
- definitions.push(astFromInterfaceType(type, schema, pathToDirectivesInExtensions));
777
- }
778
- else if (graphql.isUnionType(type)) {
779
- definitions.push(astFromUnionType(type, schema, pathToDirectivesInExtensions));
780
- }
781
- else if (graphql.isInputObjectType(type)) {
782
- definitions.push(astFromInputObjectType(type, schema, pathToDirectivesInExtensions));
783
- }
784
- else if (graphql.isEnumType(type)) {
785
- definitions.push(astFromEnumType(type, schema, pathToDirectivesInExtensions));
786
- }
787
- else if (graphql.isScalarType(type)) {
788
- definitions.push(astFromScalarType(type, schema, pathToDirectivesInExtensions));
789
- }
790
- else {
791
- throw new Error(`Unknown type ${type}.`);
792
- }
793
- }
794
- return {
795
- kind: graphql.Kind.DOCUMENT,
796
- definitions,
797
- };
798
- }
799
- // this approach uses the default schema printer rather than a custom solution, so may be more backwards compatible
800
- // currently does not allow customization of printSchema options having to do with comments.
801
- function printSchemaWithDirectives(schema, options = {}) {
802
- const documentNode = getDocumentNodeFromSchema(schema, options);
803
- return graphql.print(documentNode);
804
- }
805
- function astFromSchema(schema, pathToDirectivesInExtensions) {
806
- var _a, _b;
807
- const operationTypeMap = new Map([
808
- ['query', undefined],
809
- ['mutation', undefined],
810
- ['subscription', undefined],
811
- ]);
812
- const nodes = [];
813
- if (schema.astNode != null) {
814
- nodes.push(schema.astNode);
815
- }
816
- if (schema.extensionASTNodes != null) {
817
- for (const extensionASTNode of schema.extensionASTNodes) {
818
- nodes.push(extensionASTNode);
819
- }
820
- }
821
- for (const node of nodes) {
822
- if (node.operationTypes) {
823
- for (const operationTypeDefinitionNode of node.operationTypes) {
824
- operationTypeMap.set(operationTypeDefinitionNode.operation, operationTypeDefinitionNode);
825
- }
826
- }
827
- }
828
- const rootTypeMap = getRootTypeMap(schema);
829
- for (const [operationTypeNode, operationTypeDefinitionNode] of operationTypeMap) {
830
- const rootType = rootTypeMap.get(operationTypeNode);
831
- if (rootType != null) {
832
- const rootTypeAST = astFromType(rootType);
833
- if (operationTypeDefinitionNode != null) {
834
- operationTypeDefinitionNode.type = rootTypeAST;
835
- }
836
- else {
837
- operationTypeMap.set(operationTypeNode, {
838
- kind: graphql.Kind.OPERATION_TYPE_DEFINITION,
839
- operation: operationTypeNode,
840
- type: rootTypeAST,
841
- });
842
- }
843
- }
844
- }
845
- const operationTypes = [...operationTypeMap.values()].filter(isSome);
846
- const directives = getDirectiveNodes(schema, schema, pathToDirectivesInExtensions);
847
- if (!operationTypes.length && !directives.length) {
848
- return null;
849
- }
850
- const schemaNode = {
851
- kind: operationTypes != null ? graphql.Kind.SCHEMA_DEFINITION : graphql.Kind.SCHEMA_EXTENSION,
852
- operationTypes,
853
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
854
- directives: directives,
855
- };
856
- // This code is so weird because it needs to support GraphQL.js 14
857
- // In GraphQL.js 14 there is no `description` value on schemaNode
858
- schemaNode.description =
859
- ((_b = (_a = schema.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : schema.description != null)
860
- ? {
861
- kind: graphql.Kind.STRING,
862
- value: schema.description,
863
- block: true,
864
- }
865
- : undefined;
866
- return schemaNode;
867
- }
868
- function astFromDirective(directive, schema, pathToDirectivesInExtensions) {
869
- var _a, _b, _c, _d;
870
- return {
871
- kind: graphql.Kind.DIRECTIVE_DEFINITION,
872
- description: (_b = (_a = directive.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (directive.description
873
- ? {
874
- kind: graphql.Kind.STRING,
875
- value: directive.description,
876
- }
877
- : undefined),
878
- name: {
879
- kind: graphql.Kind.NAME,
880
- value: directive.name,
881
- },
882
- arguments: (_c = directive.args) === null || _c === void 0 ? void 0 : _c.map(arg => astFromArg(arg, schema, pathToDirectivesInExtensions)),
883
- repeatable: directive.isRepeatable,
884
- locations: ((_d = directive.locations) === null || _d === void 0 ? void 0 : _d.map(location => ({
885
- kind: graphql.Kind.NAME,
886
- value: location,
887
- }))) || [],
888
- };
889
- }
890
- function getDirectiveNodes(entity, schema, pathToDirectivesInExtensions) {
891
- const directivesInExtensions = getDirectivesInExtensions(entity, pathToDirectivesInExtensions);
892
- let nodes = [];
893
- if (entity.astNode != null) {
894
- nodes.push(entity.astNode);
895
- }
896
- if ('extensionASTNodes' in entity && entity.extensionASTNodes != null) {
897
- nodes = nodes.concat(entity.extensionASTNodes);
898
- }
899
- let directives;
900
- if (directivesInExtensions != null) {
901
- directives = makeDirectiveNodes(schema, directivesInExtensions);
902
- }
903
- else {
904
- directives = [];
905
- for (const node of nodes) {
906
- if (node.directives) {
907
- directives.push(...node.directives);
908
- }
909
- }
910
- }
911
- return directives;
912
- }
913
- function getDeprecatableDirectiveNodes(entity, schema, pathToDirectivesInExtensions) {
914
- var _a, _b;
915
- let directiveNodesBesidesDeprecated = [];
916
- let deprecatedDirectiveNode = null;
917
- const directivesInExtensions = getDirectivesInExtensions(entity, pathToDirectivesInExtensions);
918
- let directives;
919
- if (directivesInExtensions != null) {
920
- directives = makeDirectiveNodes(schema, directivesInExtensions);
921
- }
922
- else {
923
- directives = (_a = entity.astNode) === null || _a === void 0 ? void 0 : _a.directives;
924
- }
925
- if (directives != null) {
926
- directiveNodesBesidesDeprecated = directives.filter(directive => directive.name.value !== 'deprecated');
927
- if (entity.deprecationReason != null) {
928
- deprecatedDirectiveNode = (_b = directives.filter(directive => directive.name.value === 'deprecated')) === null || _b === void 0 ? void 0 : _b[0];
929
- }
930
- }
931
- if (entity.deprecationReason != null &&
932
- deprecatedDirectiveNode == null) {
933
- deprecatedDirectiveNode = makeDeprecatedDirective(entity.deprecationReason);
934
- }
935
- return deprecatedDirectiveNode == null
936
- ? directiveNodesBesidesDeprecated
937
- : [deprecatedDirectiveNode].concat(directiveNodesBesidesDeprecated);
938
- }
939
- function astFromArg(arg, schema, pathToDirectivesInExtensions) {
940
- var _a, _b, _c;
941
- return {
942
- kind: graphql.Kind.INPUT_VALUE_DEFINITION,
943
- description: (_b = (_a = arg.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (arg.description
944
- ? {
945
- kind: graphql.Kind.STRING,
946
- value: arg.description,
947
- block: true,
948
- }
949
- : undefined),
950
- name: {
951
- kind: graphql.Kind.NAME,
952
- value: arg.name,
953
- },
954
- type: astFromType(arg.type),
955
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
956
- defaultValue: arg.defaultValue !== undefined ? (_c = graphql.astFromValue(arg.defaultValue, arg.type)) !== null && _c !== void 0 ? _c : undefined : undefined,
957
- directives: getDeprecatableDirectiveNodes(arg, schema, pathToDirectivesInExtensions),
958
- };
959
- }
960
- function astFromObjectType(type, schema, pathToDirectivesInExtensions) {
961
- var _a, _b;
962
- return {
963
- kind: graphql.Kind.OBJECT_TYPE_DEFINITION,
964
- description: (_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (type.description
965
- ? {
966
- kind: graphql.Kind.STRING,
967
- value: type.description,
968
- block: true,
969
- }
970
- : undefined),
971
- name: {
972
- kind: graphql.Kind.NAME,
973
- value: type.name,
974
- },
975
- fields: Object.values(type.getFields()).map(field => astFromField(field, schema, pathToDirectivesInExtensions)),
976
- interfaces: Object.values(type.getInterfaces()).map(iFace => astFromType(iFace)),
977
- directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),
978
- };
979
- }
980
- function astFromInterfaceType(type, schema, pathToDirectivesInExtensions) {
981
- var _a, _b;
982
- const node = {
983
- kind: graphql.Kind.INTERFACE_TYPE_DEFINITION,
984
- description: (_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (type.description
985
- ? {
986
- kind: graphql.Kind.STRING,
987
- value: type.description,
988
- block: true,
989
- }
990
- : undefined),
991
- name: {
992
- kind: graphql.Kind.NAME,
993
- value: type.name,
994
- },
995
- fields: Object.values(type.getFields()).map(field => astFromField(field, schema, pathToDirectivesInExtensions)),
996
- directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),
997
- };
998
- if ('getInterfaces' in type) {
999
- node.interfaces = Object.values(type.getInterfaces()).map(iFace => astFromType(iFace));
1000
- }
1001
- return node;
1002
- }
1003
- function astFromUnionType(type, schema, pathToDirectivesInExtensions) {
1004
- var _a, _b;
1005
- return {
1006
- kind: graphql.Kind.UNION_TYPE_DEFINITION,
1007
- description: (_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (type.description
1008
- ? {
1009
- kind: graphql.Kind.STRING,
1010
- value: type.description,
1011
- block: true,
1012
- }
1013
- : undefined),
1014
- name: {
1015
- kind: graphql.Kind.NAME,
1016
- value: type.name,
1017
- },
1018
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
1019
- directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),
1020
- types: type.getTypes().map(type => astFromType(type)),
1021
- };
1022
- }
1023
- function astFromInputObjectType(type, schema, pathToDirectivesInExtensions) {
1024
- var _a, _b;
1025
- return {
1026
- kind: graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION,
1027
- description: (_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (type.description
1028
- ? {
1029
- kind: graphql.Kind.STRING,
1030
- value: type.description,
1031
- block: true,
1032
- }
1033
- : undefined),
1034
- name: {
1035
- kind: graphql.Kind.NAME,
1036
- value: type.name,
1037
- },
1038
- fields: Object.values(type.getFields()).map(field => astFromInputField(field, schema, pathToDirectivesInExtensions)),
1039
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
1040
- directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),
1041
- };
1042
- }
1043
- function astFromEnumType(type, schema, pathToDirectivesInExtensions) {
1044
- var _a, _b;
1045
- return {
1046
- kind: graphql.Kind.ENUM_TYPE_DEFINITION,
1047
- description: (_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (type.description
1048
- ? {
1049
- kind: graphql.Kind.STRING,
1050
- value: type.description,
1051
- block: true,
1052
- }
1053
- : undefined),
1054
- name: {
1055
- kind: graphql.Kind.NAME,
1056
- value: type.name,
1057
- },
1058
- values: Object.values(type.getValues()).map(value => astFromEnumValue(value, schema, pathToDirectivesInExtensions)),
1059
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
1060
- directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),
1061
- };
1062
- }
1063
- function astFromScalarType(type, schema, pathToDirectivesInExtensions) {
1064
- var _a, _b, _c;
1065
- const directivesInExtensions = getDirectivesInExtensions(type, pathToDirectivesInExtensions);
1066
- const directives = directivesInExtensions
1067
- ? makeDirectiveNodes(schema, directivesInExtensions)
1068
- : ((_a = type.astNode) === null || _a === void 0 ? void 0 : _a.directives) || [];
1069
- const specifiedByValue = (type['specifiedByUrl'] || type['specifiedByURL']);
1070
- if (specifiedByValue && !directives.some(directiveNode => directiveNode.name.value === 'specifiedBy')) {
1071
- const specifiedByArgs = {
1072
- url: specifiedByValue,
1073
- };
1074
- directives.push(makeDirectiveNode('specifiedBy', specifiedByArgs));
1075
- }
1076
- return {
1077
- kind: graphql.Kind.SCALAR_TYPE_DEFINITION,
1078
- description: (_c = (_b = type.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : (type.description
1079
- ? {
1080
- kind: graphql.Kind.STRING,
1081
- value: type.description,
1082
- block: true,
1083
- }
1084
- : undefined),
1085
- name: {
1086
- kind: graphql.Kind.NAME,
1087
- value: type.name,
1088
- },
1089
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
1090
- directives: directives,
1091
- };
1092
- }
1093
- function astFromField(field, schema, pathToDirectivesInExtensions) {
1094
- var _a, _b;
1095
- return {
1096
- kind: graphql.Kind.FIELD_DEFINITION,
1097
- description: (_b = (_a = field.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (field.description
1098
- ? {
1099
- kind: graphql.Kind.STRING,
1100
- value: field.description,
1101
- block: true,
1102
- }
1103
- : undefined),
1104
- name: {
1105
- kind: graphql.Kind.NAME,
1106
- value: field.name,
1107
- },
1108
- arguments: field.args.map(arg => astFromArg(arg, schema, pathToDirectivesInExtensions)),
1109
- type: astFromType(field.type),
1110
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
1111
- directives: getDeprecatableDirectiveNodes(field, schema, pathToDirectivesInExtensions),
1112
- };
1113
- }
1114
- function astFromInputField(field, schema, pathToDirectivesInExtensions) {
1115
- var _a, _b, _c;
1116
- return {
1117
- kind: graphql.Kind.INPUT_VALUE_DEFINITION,
1118
- description: (_b = (_a = field.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (field.description
1119
- ? {
1120
- kind: graphql.Kind.STRING,
1121
- value: field.description,
1122
- block: true,
1123
- }
1124
- : undefined),
1125
- name: {
1126
- kind: graphql.Kind.NAME,
1127
- value: field.name,
1128
- },
1129
- type: astFromType(field.type),
1130
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
1131
- directives: getDeprecatableDirectiveNodes(field, schema, pathToDirectivesInExtensions),
1132
- defaultValue: (_c = graphql.astFromValue(field.defaultValue, field.type)) !== null && _c !== void 0 ? _c : undefined,
1133
- };
1134
- }
1135
- function astFromEnumValue(value, schema, pathToDirectivesInExtensions) {
1136
- var _a, _b;
1137
- return {
1138
- kind: graphql.Kind.ENUM_VALUE_DEFINITION,
1139
- description: (_b = (_a = value.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (value.description
1140
- ? {
1141
- kind: graphql.Kind.STRING,
1142
- value: value.description,
1143
- block: true,
1144
- }
1145
- : undefined),
1146
- name: {
1147
- kind: graphql.Kind.NAME,
1148
- value: value.name,
1149
- },
1150
- // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
1151
- directives: getDeprecatableDirectiveNodes(value, schema, pathToDirectivesInExtensions),
1152
- };
1153
- }
1154
- function makeDeprecatedDirective(deprecationReason) {
1155
- return makeDirectiveNode('deprecated', { reason: deprecationReason }, graphql.GraphQLDeprecatedDirective);
1156
- }
1157
- function makeDirectiveNode(name, args, directive) {
1158
- const directiveArguments = [];
1159
- if (directive != null) {
1160
- for (const arg of directive.args) {
1161
- const argName = arg.name;
1162
- const argValue = args[argName];
1163
- if (argValue !== undefined) {
1164
- const value = graphql.astFromValue(argValue, arg.type);
1165
- if (value) {
1166
- directiveArguments.push({
1167
- kind: graphql.Kind.ARGUMENT,
1168
- name: {
1169
- kind: graphql.Kind.NAME,
1170
- value: argName,
1171
- },
1172
- value,
1173
- });
1174
- }
1175
- }
1176
- }
1177
- }
1178
- else {
1179
- for (const argName in args) {
1180
- const argValue = args[argName];
1181
- const value = astFromValueUntyped(argValue);
1182
- if (value) {
1183
- directiveArguments.push({
1184
- kind: graphql.Kind.ARGUMENT,
1185
- name: {
1186
- kind: graphql.Kind.NAME,
1187
- value: argName,
1188
- },
1189
- value,
1190
- });
1191
- }
1192
- }
1193
- }
1194
- return {
1195
- kind: graphql.Kind.DIRECTIVE,
1196
- name: {
1197
- kind: graphql.Kind.NAME,
1198
- value: name,
1199
- },
1200
- arguments: directiveArguments,
1201
- };
1202
- }
1203
- function makeDirectiveNodes(schema, directiveValues) {
1204
- const directiveNodes = [];
1205
- for (const directiveName in directiveValues) {
1206
- const arrayOrSingleValue = directiveValues[directiveName];
1207
- const directive = schema === null || schema === void 0 ? void 0 : schema.getDirective(directiveName);
1208
- if (Array.isArray(arrayOrSingleValue)) {
1209
- for (const value of arrayOrSingleValue) {
1210
- directiveNodes.push(makeDirectiveNode(directiveName, value, directive));
1211
- }
1212
- }
1213
- else {
1214
- directiveNodes.push(makeDirectiveNode(directiveName, arrayOrSingleValue, directive));
1215
- }
1216
- }
1217
- return directiveNodes;
1218
- }
1219
-
1220
- async function validateGraphQlDocuments(schema, documentFiles, effectiveRules = createDefaultRules()) {
1221
- const allFragmentMap = new Map();
1222
- const documentFileObjectsToValidate = [];
1223
- for (const documentFile of documentFiles) {
1224
- if (documentFile.document) {
1225
- const definitionsToValidate = [];
1226
- for (const definitionNode of documentFile.document.definitions) {
1227
- if (definitionNode.kind === graphql.Kind.FRAGMENT_DEFINITION) {
1228
- allFragmentMap.set(definitionNode.name.value, definitionNode);
1229
- }
1230
- else {
1231
- definitionsToValidate.push(definitionNode);
1232
- }
1233
- }
1234
- documentFileObjectsToValidate.push({
1235
- location: documentFile.location,
1236
- document: {
1237
- kind: graphql.Kind.DOCUMENT,
1238
- definitions: definitionsToValidate,
1239
- },
1240
- });
1241
- }
1242
- }
1243
- const allErrors = [];
1244
- const allFragmentsDocument = {
1245
- kind: graphql.Kind.DOCUMENT,
1246
- definitions: [...allFragmentMap.values()],
1247
- };
1248
- await Promise.all(documentFileObjectsToValidate.map(async (documentFile) => {
1249
- const documentToValidate = graphql.concatAST([allFragmentsDocument, documentFile.document]);
1250
- const errors = graphql.validate(schema, documentToValidate, effectiveRules);
1251
- if (errors.length > 0) {
1252
- allErrors.push({
1253
- filePath: documentFile.location,
1254
- errors,
1255
- });
1256
- }
1257
- }));
1258
- return allErrors;
1259
- }
1260
- function checkValidationErrors(loadDocumentErrors) {
1261
- if (loadDocumentErrors.length > 0) {
1262
- const errors = [];
1263
- for (const loadDocumentError of loadDocumentErrors) {
1264
- for (const graphQLError of loadDocumentError.errors) {
1265
- const error = new Error();
1266
- error.name = 'GraphQLDocumentError';
1267
- error.message = `${error.name}: ${graphQLError.message}`;
1268
- error.stack = error.message;
1269
- if (graphQLError.locations) {
1270
- for (const location of graphQLError.locations) {
1271
- error.stack += `\n at ${loadDocumentError.filePath}:${location.line}:${location.column}`;
1272
- }
1273
- }
1274
- errors.push(error);
1275
- }
1276
- }
1277
- throw new exports.AggregateError(errors, `GraphQL Document Validation failed with ${errors.length} errors;
1278
- ${errors.map((error, index) => `Error ${index}: ${error.stack}`).join('\n\n')}`);
1279
- }
1280
- }
1281
- function createDefaultRules() {
1282
- let ignored = ['NoUnusedFragmentsRule', 'NoUnusedVariablesRule', 'KnownDirectivesRule'];
1283
- if (graphql.versionInfo.major < 15) {
1284
- ignored = ignored.map(rule => rule.replace(/Rule$/, ''));
1285
- }
1286
- return graphql.specifiedRules.filter((f) => !ignored.includes(f.name));
1287
- }
1288
-
1289
- function stripBOM(content) {
1290
- content = content.toString();
1291
- // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
1292
- // because the buffer-to-string conversion in `fs.readFileSync()`
1293
- // translates it to FEFF, the UTF-16 BOM.
1294
- if (content.charCodeAt(0) === 0xfeff) {
1295
- content = content.slice(1);
1296
- }
1297
- return content;
1298
- }
1299
- function parseBOM(content) {
1300
- return JSON.parse(stripBOM(content));
1301
- }
1302
- function parseGraphQLJSON(location, jsonContent, options) {
1303
- let parsedJson = parseBOM(jsonContent);
1304
- if (parsedJson.data) {
1305
- parsedJson = parsedJson.data;
1306
- }
1307
- if (parsedJson.kind === 'Document') {
1308
- return {
1309
- location,
1310
- document: parsedJson,
1311
- };
1312
- }
1313
- else if (parsedJson.__schema) {
1314
- const schema = graphql.buildClientSchema(parsedJson, options);
1315
- return {
1316
- location,
1317
- schema,
1318
- };
1319
- }
1320
- else if (typeof parsedJson === 'string') {
1321
- return {
1322
- location,
1323
- rawSDL: parsedJson,
1324
- };
1325
- }
1326
- throw new Error(`Not valid JSON content`);
1327
- }
1328
-
1329
- const MAX_LINE_LENGTH = 80;
1330
- let commentsRegistry = {};
1331
- function resetComments() {
1332
- commentsRegistry = {};
1333
- }
1334
- function collectComment(node) {
1335
- var _a;
1336
- const entityName = (_a = node.name) === null || _a === void 0 ? void 0 : _a.value;
1337
- if (entityName == null) {
1338
- return;
1339
- }
1340
- pushComment(node, entityName);
1341
- switch (node.kind) {
1342
- case 'EnumTypeDefinition':
1343
- if (node.values) {
1344
- for (const value of node.values) {
1345
- pushComment(value, entityName, value.name.value);
1346
- }
1347
- }
1348
- break;
1349
- case 'ObjectTypeDefinition':
1350
- case 'InputObjectTypeDefinition':
1351
- case 'InterfaceTypeDefinition':
1352
- if (node.fields) {
1353
- for (const field of node.fields) {
1354
- pushComment(field, entityName, field.name.value);
1355
- if (isFieldDefinitionNode(field) && field.arguments) {
1356
- for (const arg of field.arguments) {
1357
- pushComment(arg, entityName, field.name.value, arg.name.value);
1358
- }
1359
- }
1360
- }
1361
- }
1362
- break;
1363
- }
1364
- }
1365
- function pushComment(node, entity, field, argument) {
1366
- const comment = getComment(node);
1367
- if (typeof comment !== 'string' || comment.length === 0) {
1368
- return;
1369
- }
1370
- const keys = [entity];
1371
- if (field) {
1372
- keys.push(field);
1373
- if (argument) {
1374
- keys.push(argument);
1375
- }
1376
- }
1377
- const path = keys.join('.');
1378
- if (!commentsRegistry[path]) {
1379
- commentsRegistry[path] = [];
1380
- }
1381
- commentsRegistry[path].push(comment);
1382
- }
1383
- function printComment(comment) {
1384
- return '\n# ' + comment.replace(/\n/g, '\n# ');
1385
- }
1386
- /**
1387
- * Copyright (c) 2015-present, Facebook, Inc.
1388
- *
1389
- * This source code is licensed under the MIT license found in the
1390
- * LICENSE file in the root directory of this source tree.
1391
- */
1392
- /**
1393
- * NOTE: ==> This file has been modified just to add comments to the printed AST
1394
- * This is a temp measure, we will move to using the original non modified printer.js ASAP.
1395
- */
1396
- /**
1397
- * Given maybeArray, print an empty string if it is null or empty, otherwise
1398
- * print all items together separated by separator if provided
1399
- */
1400
- function join(maybeArray, separator) {
1401
- return maybeArray ? maybeArray.filter(x => x).join(separator || '') : '';
1402
- }
1403
- function hasMultilineItems(maybeArray) {
1404
- var _a;
1405
- return (_a = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.some(str => str.includes('\n'))) !== null && _a !== void 0 ? _a : false;
1406
- }
1407
- function addDescription(cb) {
1408
- return (node, _key, _parent, path, ancestors) => {
1409
- var _a;
1410
- const keys = [];
1411
- const parent = path.reduce((prev, key) => {
1412
- if (['fields', 'arguments', 'values'].includes(key) && prev.name) {
1413
- keys.push(prev.name.value);
1414
- }
1415
- return prev[key];
1416
- }, ancestors[0]);
1417
- const key = [...keys, (_a = parent === null || parent === void 0 ? void 0 : parent.name) === null || _a === void 0 ? void 0 : _a.value].filter(Boolean).join('.');
1418
- const items = [];
1419
- if (node.kind.includes('Definition') && commentsRegistry[key]) {
1420
- items.push(...commentsRegistry[key]);
1421
- }
1422
- return join([...items.map(printComment), node.description, cb(node, _key, _parent, path, ancestors)], '\n');
1423
- };
1424
- }
1425
- function indent(maybeString) {
1426
- return maybeString && ` ${maybeString.replace(/\n/g, '\n ')}`;
1427
- }
1428
- /**
1429
- * Given array, print each item on its own line, wrapped in an
1430
- * indented "{ }" block.
1431
- */
1432
- function block(array) {
1433
- return array && array.length !== 0 ? `{\n${indent(join(array, '\n'))}\n}` : '';
1434
- }
1435
- /**
1436
- * If maybeString is not null or empty, then wrap with start and end, otherwise
1437
- * print an empty string.
1438
- */
1439
- function wrap(start, maybeString, end) {
1440
- return maybeString ? start + maybeString + (end || '') : '';
1441
- }
1442
- /**
1443
- * Print a block string in the indented block form by adding a leading and
1444
- * trailing blank line. However, if a block string starts with whitespace and is
1445
- * a single-line, adding a leading blank line would strip that whitespace.
1446
- */
1447
- function printBlockString(value, isDescription = false) {
1448
- const escaped = value.replace(/"""/g, '\\"""');
1449
- return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1
1450
- ? `"""${escaped.replace(/"$/, '"\n')}"""`
1451
- : `"""\n${isDescription ? escaped : indent(escaped)}\n"""`;
1452
- }
1453
- const printDocASTReducer = {
1454
- Name: { leave: node => node.value },
1455
- Variable: { leave: node => '$' + node.name },
1456
- // Document
1457
- Document: {
1458
- leave: node => join(node.definitions, '\n\n'),
1459
- },
1460
- OperationDefinition: {
1461
- leave: node => {
1462
- const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
1463
- const prefix = join([node.operation, join([node.name, varDefs]), join(node.directives, ' ')], ' ');
1464
- // the query short form.
1465
- return prefix + ' ' + node.selectionSet;
1466
- },
1467
- },
1468
- VariableDefinition: {
1469
- leave: ({ variable, type, defaultValue, directives }) => variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')),
1470
- },
1471
- SelectionSet: { leave: ({ selections }) => block(selections) },
1472
- Field: {
1473
- leave({ alias, name, arguments: args, directives, selectionSet }) {
1474
- const prefix = wrap('', alias, ': ') + name;
1475
- let argsLine = prefix + wrap('(', join(args, ', '), ')');
1476
- if (argsLine.length > MAX_LINE_LENGTH) {
1477
- argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)');
1478
- }
1479
- return join([argsLine, join(directives, ' '), selectionSet], ' ');
1480
- },
1481
- },
1482
- Argument: { leave: ({ name, value }) => name + ': ' + value },
1483
- // Fragments
1484
- FragmentSpread: {
1485
- leave: ({ name, directives }) => '...' + name + wrap(' ', join(directives, ' ')),
1486
- },
1487
- InlineFragment: {
1488
- leave: ({ typeCondition, directives, selectionSet }) => join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' '),
1489
- },
1490
- FragmentDefinition: {
1491
- leave: ({ name, typeCondition, variableDefinitions, directives, selectionSet }) =>
1492
- // Note: fragment variable definitions are experimental and may be changed
1493
- // or removed in the future.
1494
- `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` +
1495
- `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` +
1496
- selectionSet,
1497
- },
1498
- // Value
1499
- IntValue: { leave: ({ value }) => value },
1500
- FloatValue: { leave: ({ value }) => value },
1501
- StringValue: {
1502
- leave: ({ value, block: isBlockString }) => {
1503
- if (isBlockString) {
1504
- return printBlockString(value);
1505
- }
1506
- return JSON.stringify(value);
1507
- },
1508
- },
1509
- BooleanValue: { leave: ({ value }) => (value ? 'true' : 'false') },
1510
- NullValue: { leave: () => 'null' },
1511
- EnumValue: { leave: ({ value }) => value },
1512
- ListValue: { leave: ({ values }) => '[' + join(values, ', ') + ']' },
1513
- ObjectValue: { leave: ({ fields }) => '{' + join(fields, ', ') + '}' },
1514
- ObjectField: { leave: ({ name, value }) => name + ': ' + value },
1515
- // Directive
1516
- Directive: {
1517
- leave: ({ name, arguments: args }) => '@' + name + wrap('(', join(args, ', '), ')'),
1518
- },
1519
- // Type
1520
- NamedType: { leave: ({ name }) => name },
1521
- ListType: { leave: ({ type }) => '[' + type + ']' },
1522
- NonNullType: { leave: ({ type }) => type + '!' },
1523
- // Type System Definitions
1524
- SchemaDefinition: {
1525
- leave: ({ directives, operationTypes }) => join(['schema', join(directives, ' '), block(operationTypes)], ' '),
1526
- },
1527
- OperationTypeDefinition: {
1528
- leave: ({ operation, type }) => operation + ': ' + type,
1529
- },
1530
- ScalarTypeDefinition: {
1531
- leave: ({ name, directives }) => join(['scalar', name, join(directives, ' ')], ' '),
1532
- },
1533
- ObjectTypeDefinition: {
1534
- leave: ({ name, interfaces, directives, fields }) => join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '),
1535
- },
1536
- FieldDefinition: {
1537
- leave: ({ name, arguments: args, type, directives }) => name +
1538
- (hasMultilineItems(args)
1539
- ? wrap('(\n', indent(join(args, '\n')), '\n)')
1540
- : wrap('(', join(args, ', '), ')')) +
1541
- ': ' +
1542
- type +
1543
- wrap(' ', join(directives, ' ')),
1544
- },
1545
- InputValueDefinition: {
1546
- leave: ({ name, type, defaultValue, directives }) => join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '),
1547
- },
1548
- InterfaceTypeDefinition: {
1549
- leave: ({ name, interfaces, directives, fields }) => join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '),
1550
- },
1551
- UnionTypeDefinition: {
1552
- leave: ({ name, directives, types }) => join(['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' '),
1553
- },
1554
- EnumTypeDefinition: {
1555
- leave: ({ name, directives, values }) => join(['enum', name, join(directives, ' '), block(values)], ' '),
1556
- },
1557
- EnumValueDefinition: {
1558
- leave: ({ name, directives }) => join([name, join(directives, ' ')], ' '),
1559
- },
1560
- InputObjectTypeDefinition: {
1561
- leave: ({ name, directives, fields }) => join(['input', name, join(directives, ' '), block(fields)], ' '),
1562
- },
1563
- DirectiveDefinition: {
1564
- leave: ({ name, arguments: args, repeatable, locations }) => 'directive @' +
1565
- name +
1566
- (hasMultilineItems(args)
1567
- ? wrap('(\n', indent(join(args, '\n')), '\n)')
1568
- : wrap('(', join(args, ', '), ')')) +
1569
- (repeatable ? ' repeatable' : '') +
1570
- ' on ' +
1571
- join(locations, ' | '),
1572
- },
1573
- SchemaExtension: {
1574
- leave: ({ directives, operationTypes }) => join(['extend schema', join(directives, ' '), block(operationTypes)], ' '),
1575
- },
1576
- ScalarTypeExtension: {
1577
- leave: ({ name, directives }) => join(['extend scalar', name, join(directives, ' ')], ' '),
1578
- },
1579
- ObjectTypeExtension: {
1580
- leave: ({ name, interfaces, directives, fields }) => join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '),
1581
- },
1582
- InterfaceTypeExtension: {
1583
- leave: ({ name, interfaces, directives, fields }) => join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '),
1584
- },
1585
- UnionTypeExtension: {
1586
- leave: ({ name, directives, types }) => join(['extend union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' '),
1587
- },
1588
- EnumTypeExtension: {
1589
- leave: ({ name, directives, values }) => join(['extend enum', name, join(directives, ' '), block(values)], ' '),
1590
- },
1591
- InputObjectTypeExtension: {
1592
- leave: ({ name, directives, fields }) => join(['extend input', name, join(directives, ' '), block(fields)], ' '),
1593
- },
1594
- };
1595
- const printDocASTReducerWithComments = Object.keys(printDocASTReducer).reduce((prev, key) => ({
1596
- ...prev,
1597
- [key]: {
1598
- leave: addDescription(printDocASTReducer[key].leave),
1599
- },
1600
- }), {});
1601
- /**
1602
- * Converts an AST into a string, using one set of reasonable
1603
- * formatting rules.
1604
- */
1605
- function printWithComments(ast) {
1606
- return graphql.visit(ast, printDocASTReducerWithComments);
1607
- }
1608
- function isFieldDefinitionNode(node) {
1609
- return node.kind === 'FieldDefinition';
1610
- }
1611
- // graphql < v13 and > v15 does not export getDescription
1612
- function getDescription(node, options) {
1613
- if (node.description != null) {
1614
- return node.description.value;
1615
- }
1616
- if (options === null || options === void 0 ? void 0 : options.commentDescriptions) {
1617
- return getComment(node);
1618
- }
1619
- }
1620
- function getComment(node) {
1621
- const rawValue = getLeadingCommentBlock(node);
1622
- if (rawValue !== undefined) {
1623
- return dedentBlockStringValue(`\n${rawValue}`);
1624
- }
1625
- }
1626
- function getLeadingCommentBlock(node) {
1627
- const loc = node.loc;
1628
- if (!loc) {
1629
- return;
1630
- }
1631
- const comments = [];
1632
- let token = loc.startToken.prev;
1633
- while (token != null &&
1634
- token.kind === graphql.TokenKind.COMMENT &&
1635
- token.next != null &&
1636
- token.prev != null &&
1637
- token.line + 1 === token.next.line &&
1638
- token.line !== token.prev.line) {
1639
- const value = String(token.value);
1640
- comments.push(value);
1641
- token = token.prev;
1642
- }
1643
- return comments.length > 0 ? comments.reverse().join('\n') : undefined;
1644
- }
1645
- function dedentBlockStringValue(rawString) {
1646
- // Expand a block string's raw value into independent lines.
1647
- const lines = rawString.split(/\r\n|[\n\r]/g);
1648
- // Remove common indentation from all lines but first.
1649
- const commonIndent = getBlockStringIndentation(lines);
1650
- if (commonIndent !== 0) {
1651
- for (let i = 1; i < lines.length; i++) {
1652
- lines[i] = lines[i].slice(commonIndent);
1653
- }
1654
- }
1655
- // Remove leading and trailing blank lines.
1656
- while (lines.length > 0 && isBlank(lines[0])) {
1657
- lines.shift();
1658
- }
1659
- while (lines.length > 0 && isBlank(lines[lines.length - 1])) {
1660
- lines.pop();
1661
- }
1662
- // Return a string of the lines joined with U+000A.
1663
- return lines.join('\n');
1664
- }
1665
- /**
1666
- * @internal
1667
- */
1668
- function getBlockStringIndentation(lines) {
1669
- let commonIndent = null;
1670
- for (let i = 1; i < lines.length; i++) {
1671
- const line = lines[i];
1672
- const indent = leadingWhitespace(line);
1673
- if (indent === line.length) {
1674
- continue; // skip empty lines
1675
- }
1676
- if (commonIndent === null || indent < commonIndent) {
1677
- commonIndent = indent;
1678
- if (commonIndent === 0) {
1679
- break;
1680
- }
1681
- }
1682
- }
1683
- return commonIndent === null ? 0 : commonIndent;
1684
- }
1685
- function leadingWhitespace(str) {
1686
- let i = 0;
1687
- while (i < str.length && (str[i] === ' ' || str[i] === '\t')) {
1688
- i++;
1689
- }
1690
- return i;
1691
- }
1692
- function isBlank(str) {
1693
- return leadingWhitespace(str) === str.length;
1694
- }
1695
-
1696
- function parseGraphQLSDL(location, rawSDL, options = {}) {
1697
- let document;
1698
- try {
1699
- if (options.commentDescriptions && rawSDL.includes('#')) {
1700
- document = transformCommentsToDescriptions(rawSDL, options);
1701
- // If noLocation=true, we need to make sure to print and parse it again, to remove locations,
1702
- // since `transformCommentsToDescriptions` must have locations set in order to transform the comments
1703
- // into descriptions.
1704
- if (options.noLocation) {
1705
- document = graphql.parse(graphql.print(document), options);
1706
- }
1707
- }
1708
- else {
1709
- document = graphql.parse(new graphql.Source(rawSDL, location), options);
1710
- }
1711
- }
1712
- catch (e) {
1713
- if (e.message.includes('EOF') && rawSDL.replace(/(\#[^*]*)/g, '').trim() === '') {
1714
- document = {
1715
- kind: graphql.Kind.DOCUMENT,
1716
- definitions: [],
1717
- };
1718
- }
1719
- else {
1720
- throw e;
1721
- }
1722
- }
1723
- return {
1724
- location,
1725
- document,
1726
- };
1727
- }
1728
- function transformCommentsToDescriptions(sourceSdl, options = {}) {
1729
- const parsedDoc = graphql.parse(sourceSdl, {
1730
- ...options,
1731
- noLocation: false,
1732
- });
1733
- const modifiedDoc = graphql.visit(parsedDoc, {
1734
- leave: (node) => {
1735
- if (isDescribable(node)) {
1736
- const rawValue = getLeadingCommentBlock(node);
1737
- if (rawValue !== undefined) {
1738
- const commentsBlock = dedentBlockStringValue('\n' + rawValue);
1739
- const isBlock = commentsBlock.includes('\n');
1740
- if (!node.description) {
1741
- return {
1742
- ...node,
1743
- description: {
1744
- kind: graphql.Kind.STRING,
1745
- value: commentsBlock,
1746
- block: isBlock,
1747
- },
1748
- };
1749
- }
1750
- else {
1751
- return {
1752
- ...node,
1753
- description: {
1754
- ...node.description,
1755
- value: node.description.value + '\n' + commentsBlock,
1756
- block: true,
1757
- },
1758
- };
1759
- }
1760
- }
1761
- }
1762
- },
1763
- });
1764
- return modifiedDoc;
1765
- }
1766
- function isDescribable(node) {
1767
- return (graphql.isTypeSystemDefinitionNode(node) ||
1768
- node.kind === graphql.Kind.FIELD_DEFINITION ||
1769
- node.kind === graphql.Kind.INPUT_VALUE_DEFINITION ||
1770
- node.kind === graphql.Kind.ENUM_VALUE_DEFINITION);
1771
- }
1772
-
1773
- let operationVariables = [];
1774
- let fieldTypeMap = new Map();
1775
- function addOperationVariable(variable) {
1776
- operationVariables.push(variable);
1777
- }
1778
- function resetOperationVariables() {
1779
- operationVariables = [];
1780
- }
1781
- function resetFieldMap() {
1782
- fieldTypeMap = new Map();
1783
- }
1784
- function buildOperationNodeForField({ schema, kind, field, models, ignore = [], depthLimit, circularReferenceDepth, argNames, selectedFields = true, }) {
1785
- resetOperationVariables();
1786
- resetFieldMap();
1787
- const rootTypeNames = getRootTypeNames(schema);
1788
- const operationNode = buildOperationAndCollectVariables({
1789
- schema,
1790
- fieldName: field,
1791
- kind,
1792
- models: models || [],
1793
- ignore,
1794
- depthLimit: depthLimit || Infinity,
1795
- circularReferenceDepth: circularReferenceDepth || 1,
1796
- argNames,
1797
- selectedFields,
1798
- rootTypeNames,
1799
- });
1800
- // attach variables
1801
- operationNode.variableDefinitions = [...operationVariables];
1802
- resetOperationVariables();
1803
- resetFieldMap();
1804
- return operationNode;
1805
- }
1806
- function buildOperationAndCollectVariables({ schema, fieldName, kind, models, ignore, depthLimit, circularReferenceDepth, argNames, selectedFields, rootTypeNames, }) {
1807
- const type = getDefinedRootType(schema, kind);
1808
- const field = type.getFields()[fieldName];
1809
- const operationName = `${fieldName}_${kind}`;
1810
- if (field.args) {
1811
- for (const arg of field.args) {
1812
- const argName = arg.name;
1813
- if (!argNames || argNames.includes(argName)) {
1814
- addOperationVariable(resolveVariable(arg, argName));
1815
- }
1816
- }
1817
- }
1818
- return {
1819
- kind: graphql.Kind.OPERATION_DEFINITION,
1820
- operation: kind,
1821
- name: {
1822
- kind: graphql.Kind.NAME,
1823
- value: operationName,
1824
- },
1825
- variableDefinitions: [],
1826
- selectionSet: {
1827
- kind: graphql.Kind.SELECTION_SET,
1828
- selections: [
1829
- resolveField({
1830
- type,
1831
- field,
1832
- models,
1833
- firstCall: true,
1834
- path: [],
1835
- ancestors: [],
1836
- ignore,
1837
- depthLimit,
1838
- circularReferenceDepth,
1839
- schema,
1840
- depth: 0,
1841
- argNames,
1842
- selectedFields,
1843
- rootTypeNames,
1844
- }),
1845
- ],
1846
- },
1847
- };
1848
- }
1849
- function resolveSelectionSet({ parent, type, models, firstCall, path, ancestors, ignore, depthLimit, circularReferenceDepth, schema, depth, argNames, selectedFields, rootTypeNames, }) {
1850
- if (typeof selectedFields === 'boolean' && depth > depthLimit) {
1851
- return;
1852
- }
1853
- if (graphql.isUnionType(type)) {
1854
- const types = type.getTypes();
1855
- return {
1856
- kind: graphql.Kind.SELECTION_SET,
1857
- selections: types
1858
- .filter(t => !hasCircularRef([...ancestors, t], {
1859
- depth: circularReferenceDepth,
1860
- }))
1861
- .map(t => {
1862
- return {
1863
- kind: graphql.Kind.INLINE_FRAGMENT,
1864
- typeCondition: {
1865
- kind: graphql.Kind.NAMED_TYPE,
1866
- name: {
1867
- kind: graphql.Kind.NAME,
1868
- value: t.name,
1869
- },
1870
- },
1871
- selectionSet: resolveSelectionSet({
1872
- parent: type,
1873
- type: t,
1874
- models,
1875
- path,
1876
- ancestors,
1877
- ignore,
1878
- depthLimit,
1879
- circularReferenceDepth,
1880
- schema,
1881
- depth,
1882
- argNames,
1883
- selectedFields,
1884
- rootTypeNames,
1885
- }),
1886
- };
1887
- })
1888
- .filter(fragmentNode => { var _a, _b; return ((_b = (_a = fragmentNode === null || fragmentNode === void 0 ? void 0 : fragmentNode.selectionSet) === null || _a === void 0 ? void 0 : _a.selections) === null || _b === void 0 ? void 0 : _b.length) > 0; }),
1889
- };
1890
- }
1891
- if (graphql.isInterfaceType(type)) {
1892
- const types = Object.values(schema.getTypeMap()).filter((t) => graphql.isObjectType(t) && t.getInterfaces().includes(type));
1893
- return {
1894
- kind: graphql.Kind.SELECTION_SET,
1895
- selections: types
1896
- .filter(t => !hasCircularRef([...ancestors, t], {
1897
- depth: circularReferenceDepth,
1898
- }))
1899
- .map(t => {
1900
- return {
1901
- kind: graphql.Kind.INLINE_FRAGMENT,
1902
- typeCondition: {
1903
- kind: graphql.Kind.NAMED_TYPE,
1904
- name: {
1905
- kind: graphql.Kind.NAME,
1906
- value: t.name,
1907
- },
1908
- },
1909
- selectionSet: resolveSelectionSet({
1910
- parent: type,
1911
- type: t,
1912
- models,
1913
- path,
1914
- ancestors,
1915
- ignore,
1916
- depthLimit,
1917
- circularReferenceDepth,
1918
- schema,
1919
- depth,
1920
- argNames,
1921
- selectedFields,
1922
- rootTypeNames,
1923
- }),
1924
- };
1925
- })
1926
- .filter(fragmentNode => { var _a, _b; return ((_b = (_a = fragmentNode === null || fragmentNode === void 0 ? void 0 : fragmentNode.selectionSet) === null || _a === void 0 ? void 0 : _a.selections) === null || _b === void 0 ? void 0 : _b.length) > 0; }),
1927
- };
1928
- }
1929
- if (graphql.isObjectType(type) && !rootTypeNames.has(type.name)) {
1930
- const isIgnored = ignore.includes(type.name) || ignore.includes(`${parent.name}.${path[path.length - 1]}`);
1931
- const isModel = models.includes(type.name);
1932
- if (!firstCall && isModel && !isIgnored) {
1933
- return {
1934
- kind: graphql.Kind.SELECTION_SET,
1935
- selections: [
1936
- {
1937
- kind: graphql.Kind.FIELD,
1938
- name: {
1939
- kind: graphql.Kind.NAME,
1940
- value: 'id',
1941
- },
1942
- },
1943
- ],
1944
- };
1945
- }
1946
- const fields = type.getFields();
1947
- return {
1948
- kind: graphql.Kind.SELECTION_SET,
1949
- selections: Object.keys(fields)
1950
- .filter(fieldName => {
1951
- return !hasCircularRef([...ancestors, graphql.getNamedType(fields[fieldName].type)], {
1952
- depth: circularReferenceDepth,
1953
- });
1954
- })
1955
- .map(fieldName => {
1956
- const selectedSubFields = typeof selectedFields === 'object' ? selectedFields[fieldName] : true;
1957
- if (selectedSubFields) {
1958
- return resolveField({
1959
- type: type,
1960
- field: fields[fieldName],
1961
- models,
1962
- path: [...path, fieldName],
1963
- ancestors,
1964
- ignore,
1965
- depthLimit,
1966
- circularReferenceDepth,
1967
- schema,
1968
- depth,
1969
- argNames,
1970
- selectedFields: selectedSubFields,
1971
- rootTypeNames,
1972
- });
1973
- }
1974
- return null;
1975
- })
1976
- .filter((f) => {
1977
- var _a, _b;
1978
- if (f == null) {
1979
- return false;
1980
- }
1981
- else if ('selectionSet' in f) {
1982
- return !!((_b = (_a = f.selectionSet) === null || _a === void 0 ? void 0 : _a.selections) === null || _b === void 0 ? void 0 : _b.length);
1983
- }
1984
- return true;
1985
- }),
1986
- };
1987
- }
1988
- }
1989
- function resolveVariable(arg, name) {
1990
- function resolveVariableType(type) {
1991
- if (graphql.isListType(type)) {
1992
- return {
1993
- kind: graphql.Kind.LIST_TYPE,
1994
- type: resolveVariableType(type.ofType),
1995
- };
1996
- }
1997
- if (graphql.isNonNullType(type)) {
1998
- return {
1999
- kind: graphql.Kind.NON_NULL_TYPE,
2000
- // for v16 compatibility
2001
- type: resolveVariableType(type.ofType),
2002
- };
2003
- }
2004
- return {
2005
- kind: graphql.Kind.NAMED_TYPE,
2006
- name: {
2007
- kind: graphql.Kind.NAME,
2008
- value: type.name,
2009
- },
2010
- };
2011
- }
2012
- return {
2013
- kind: graphql.Kind.VARIABLE_DEFINITION,
2014
- variable: {
2015
- kind: graphql.Kind.VARIABLE,
2016
- name: {
2017
- kind: graphql.Kind.NAME,
2018
- value: name || arg.name,
2019
- },
2020
- },
2021
- type: resolveVariableType(arg.type),
2022
- };
2023
- }
2024
- function getArgumentName(name, path) {
2025
- return [...path, name].join('_');
2026
- }
2027
- function resolveField({ type, field, models, firstCall, path, ancestors, ignore, depthLimit, circularReferenceDepth, schema, depth, argNames, selectedFields, rootTypeNames, }) {
2028
- const namedType = graphql.getNamedType(field.type);
2029
- let args = [];
2030
- let removeField = false;
2031
- if (field.args && field.args.length) {
2032
- args = field.args
2033
- .map(arg => {
2034
- const argumentName = getArgumentName(arg.name, path);
2035
- if (argNames && !argNames.includes(argumentName)) {
2036
- if (graphql.isNonNullType(arg.type)) {
2037
- removeField = true;
2038
- }
2039
- return null;
2040
- }
2041
- if (!firstCall) {
2042
- addOperationVariable(resolveVariable(arg, argumentName));
2043
- }
2044
- return {
2045
- kind: graphql.Kind.ARGUMENT,
2046
- name: {
2047
- kind: graphql.Kind.NAME,
2048
- value: arg.name,
2049
- },
2050
- value: {
2051
- kind: graphql.Kind.VARIABLE,
2052
- name: {
2053
- kind: graphql.Kind.NAME,
2054
- value: getArgumentName(arg.name, path),
2055
- },
2056
- },
2057
- };
2058
- })
2059
- .filter(Boolean);
2060
- }
2061
- if (removeField) {
2062
- return null;
2063
- }
2064
- const fieldPath = [...path, field.name];
2065
- const fieldPathStr = fieldPath.join('.');
2066
- let fieldName = field.name;
2067
- if (fieldTypeMap.has(fieldPathStr) && fieldTypeMap.get(fieldPathStr) !== field.type.toString()) {
2068
- fieldName += field.type.toString().replace('!', 'NonNull');
2069
- }
2070
- fieldTypeMap.set(fieldPathStr, field.type.toString());
2071
- if (!graphql.isScalarType(namedType) && !graphql.isEnumType(namedType)) {
2072
- return {
2073
- kind: graphql.Kind.FIELD,
2074
- name: {
2075
- kind: graphql.Kind.NAME,
2076
- value: field.name,
2077
- },
2078
- ...(fieldName !== field.name && { alias: { kind: graphql.Kind.NAME, value: fieldName } }),
2079
- selectionSet: resolveSelectionSet({
2080
- parent: type,
2081
- type: namedType,
2082
- models,
2083
- firstCall,
2084
- path: fieldPath,
2085
- ancestors: [...ancestors, type],
2086
- ignore,
2087
- depthLimit,
2088
- circularReferenceDepth,
2089
- schema,
2090
- depth: depth + 1,
2091
- argNames,
2092
- selectedFields,
2093
- rootTypeNames,
2094
- }) || undefined,
2095
- arguments: args,
2096
- };
2097
- }
2098
- return {
2099
- kind: graphql.Kind.FIELD,
2100
- name: {
2101
- kind: graphql.Kind.NAME,
2102
- value: field.name,
2103
- },
2104
- ...(fieldName !== field.name && { alias: { kind: graphql.Kind.NAME, value: fieldName } }),
2105
- arguments: args,
2106
- };
2107
- }
2108
- function hasCircularRef(types, config = {
2109
- depth: 1,
2110
- }) {
2111
- const type = types[types.length - 1];
2112
- if (graphql.isScalarType(type)) {
2113
- return false;
2114
- }
2115
- const size = types.filter(t => t.name === type.name).length;
2116
- return size > config.depth;
2117
- }
2118
-
2119
- (function (DirectiveLocation) {
2120
- /** Request Definitions */
2121
- DirectiveLocation["QUERY"] = "QUERY";
2122
- DirectiveLocation["MUTATION"] = "MUTATION";
2123
- DirectiveLocation["SUBSCRIPTION"] = "SUBSCRIPTION";
2124
- DirectiveLocation["FIELD"] = "FIELD";
2125
- DirectiveLocation["FRAGMENT_DEFINITION"] = "FRAGMENT_DEFINITION";
2126
- DirectiveLocation["FRAGMENT_SPREAD"] = "FRAGMENT_SPREAD";
2127
- DirectiveLocation["INLINE_FRAGMENT"] = "INLINE_FRAGMENT";
2128
- DirectiveLocation["VARIABLE_DEFINITION"] = "VARIABLE_DEFINITION";
2129
- /** Type System Definitions */
2130
- DirectiveLocation["SCHEMA"] = "SCHEMA";
2131
- DirectiveLocation["SCALAR"] = "SCALAR";
2132
- DirectiveLocation["OBJECT"] = "OBJECT";
2133
- DirectiveLocation["FIELD_DEFINITION"] = "FIELD_DEFINITION";
2134
- DirectiveLocation["ARGUMENT_DEFINITION"] = "ARGUMENT_DEFINITION";
2135
- DirectiveLocation["INTERFACE"] = "INTERFACE";
2136
- DirectiveLocation["UNION"] = "UNION";
2137
- DirectiveLocation["ENUM"] = "ENUM";
2138
- DirectiveLocation["ENUM_VALUE"] = "ENUM_VALUE";
2139
- DirectiveLocation["INPUT_OBJECT"] = "INPUT_OBJECT";
2140
- DirectiveLocation["INPUT_FIELD_DEFINITION"] = "INPUT_FIELD_DEFINITION";
2141
- })(exports.DirectiveLocation || (exports.DirectiveLocation = {}));
2142
-
2143
- (function (MapperKind) {
2144
- MapperKind["TYPE"] = "MapperKind.TYPE";
2145
- MapperKind["SCALAR_TYPE"] = "MapperKind.SCALAR_TYPE";
2146
- MapperKind["ENUM_TYPE"] = "MapperKind.ENUM_TYPE";
2147
- MapperKind["COMPOSITE_TYPE"] = "MapperKind.COMPOSITE_TYPE";
2148
- MapperKind["OBJECT_TYPE"] = "MapperKind.OBJECT_TYPE";
2149
- MapperKind["INPUT_OBJECT_TYPE"] = "MapperKind.INPUT_OBJECT_TYPE";
2150
- MapperKind["ABSTRACT_TYPE"] = "MapperKind.ABSTRACT_TYPE";
2151
- MapperKind["UNION_TYPE"] = "MapperKind.UNION_TYPE";
2152
- MapperKind["INTERFACE_TYPE"] = "MapperKind.INTERFACE_TYPE";
2153
- MapperKind["ROOT_OBJECT"] = "MapperKind.ROOT_OBJECT";
2154
- MapperKind["QUERY"] = "MapperKind.QUERY";
2155
- MapperKind["MUTATION"] = "MapperKind.MUTATION";
2156
- MapperKind["SUBSCRIPTION"] = "MapperKind.SUBSCRIPTION";
2157
- MapperKind["DIRECTIVE"] = "MapperKind.DIRECTIVE";
2158
- MapperKind["FIELD"] = "MapperKind.FIELD";
2159
- MapperKind["COMPOSITE_FIELD"] = "MapperKind.COMPOSITE_FIELD";
2160
- MapperKind["OBJECT_FIELD"] = "MapperKind.OBJECT_FIELD";
2161
- MapperKind["ROOT_FIELD"] = "MapperKind.ROOT_FIELD";
2162
- MapperKind["QUERY_ROOT_FIELD"] = "MapperKind.QUERY_ROOT_FIELD";
2163
- MapperKind["MUTATION_ROOT_FIELD"] = "MapperKind.MUTATION_ROOT_FIELD";
2164
- MapperKind["SUBSCRIPTION_ROOT_FIELD"] = "MapperKind.SUBSCRIPTION_ROOT_FIELD";
2165
- MapperKind["INTERFACE_FIELD"] = "MapperKind.INTERFACE_FIELD";
2166
- MapperKind["INPUT_OBJECT_FIELD"] = "MapperKind.INPUT_OBJECT_FIELD";
2167
- MapperKind["ARGUMENT"] = "MapperKind.ARGUMENT";
2168
- MapperKind["ENUM_VALUE"] = "MapperKind.ENUM_VALUE";
2169
- })(exports.MapperKind || (exports.MapperKind = {}));
2170
-
2171
- function getObjectTypeFromTypeMap(typeMap, type) {
2172
- if (type) {
2173
- const maybeObjectType = typeMap[type.name];
2174
- if (graphql.isObjectType(maybeObjectType)) {
2175
- return maybeObjectType;
2176
- }
2177
- }
2178
- }
2179
-
2180
- function createNamedStub(name, type) {
2181
- let constructor;
2182
- if (type === 'object') {
2183
- constructor = graphql.GraphQLObjectType;
2184
- }
2185
- else if (type === 'interface') {
2186
- constructor = graphql.GraphQLInterfaceType;
2187
- }
2188
- else {
2189
- constructor = graphql.GraphQLInputObjectType;
2190
- }
2191
- return new constructor({
2192
- name,
2193
- fields: {
2194
- _fake: {
2195
- type: graphql.GraphQLString,
2196
- },
2197
- },
2198
- });
2199
- }
2200
- function createStub(node, type) {
2201
- switch (node.kind) {
2202
- case graphql.Kind.LIST_TYPE:
2203
- return new graphql.GraphQLList(createStub(node.type, type));
2204
- case graphql.Kind.NON_NULL_TYPE:
2205
- return new graphql.GraphQLNonNull(createStub(node.type, type));
2206
- default:
2207
- if (type === 'output') {
2208
- return createNamedStub(node.name.value, 'object');
2209
- }
2210
- return createNamedStub(node.name.value, 'input');
2211
- }
2212
- }
2213
- function isNamedStub(type) {
2214
- if ('getFields' in type) {
2215
- const fields = type.getFields();
2216
- // eslint-disable-next-line no-unreachable-loop
2217
- for (const fieldName in fields) {
2218
- const field = fields[fieldName];
2219
- return field.name === '_fake';
2220
- }
2221
- }
2222
- return false;
2223
- }
2224
- function getBuiltInForStub(type) {
2225
- switch (type.name) {
2226
- case graphql.GraphQLInt.name:
2227
- return graphql.GraphQLInt;
2228
- case graphql.GraphQLFloat.name:
2229
- return graphql.GraphQLFloat;
2230
- case graphql.GraphQLString.name:
2231
- return graphql.GraphQLString;
2232
- case graphql.GraphQLBoolean.name:
2233
- return graphql.GraphQLBoolean;
2234
- case graphql.GraphQLID.name:
2235
- return graphql.GraphQLID;
2236
- default:
2237
- return type;
2238
- }
2239
- }
2240
-
2241
- function rewireTypes(originalTypeMap, directives) {
2242
- const referenceTypeMap = Object.create(null);
2243
- for (const typeName in originalTypeMap) {
2244
- referenceTypeMap[typeName] = originalTypeMap[typeName];
2245
- }
2246
- const newTypeMap = Object.create(null);
2247
- for (const typeName in referenceTypeMap) {
2248
- const namedType = referenceTypeMap[typeName];
2249
- if (namedType == null || typeName.startsWith('__')) {
2250
- continue;
2251
- }
2252
- const newName = namedType.name;
2253
- if (newName.startsWith('__')) {
2254
- continue;
2255
- }
2256
- if (newTypeMap[newName] != null) {
2257
- throw new Error(`Duplicate schema type name ${newName}`);
2258
- }
2259
- newTypeMap[newName] = namedType;
2260
- }
2261
- for (const typeName in newTypeMap) {
2262
- newTypeMap[typeName] = rewireNamedType(newTypeMap[typeName]);
2263
- }
2264
- const newDirectives = directives.map(directive => rewireDirective(directive));
2265
- return {
2266
- typeMap: newTypeMap,
2267
- directives: newDirectives,
2268
- };
2269
- function rewireDirective(directive) {
2270
- if (graphql.isSpecifiedDirective(directive)) {
2271
- return directive;
2272
- }
2273
- const directiveConfig = directive.toConfig();
2274
- directiveConfig.args = rewireArgs(directiveConfig.args);
2275
- return new graphql.GraphQLDirective(directiveConfig);
2276
- }
2277
- function rewireArgs(args) {
2278
- const rewiredArgs = {};
2279
- for (const argName in args) {
2280
- const arg = args[argName];
2281
- const rewiredArgType = rewireType(arg.type);
2282
- if (rewiredArgType != null) {
2283
- arg.type = rewiredArgType;
2284
- rewiredArgs[argName] = arg;
2285
- }
2286
- }
2287
- return rewiredArgs;
2288
- }
2289
- function rewireNamedType(type) {
2290
- if (graphql.isObjectType(type)) {
2291
- const config = type.toConfig();
2292
- const newConfig = {
2293
- ...config,
2294
- fields: () => rewireFields(config.fields),
2295
- interfaces: () => rewireNamedTypes(config.interfaces),
2296
- };
2297
- return new graphql.GraphQLObjectType(newConfig);
2298
- }
2299
- else if (graphql.isInterfaceType(type)) {
2300
- const config = type.toConfig();
2301
- const newConfig = {
2302
- ...config,
2303
- fields: () => rewireFields(config.fields),
2304
- };
2305
- if ('interfaces' in newConfig) {
2306
- newConfig.interfaces = () => rewireNamedTypes(config.interfaces);
2307
- }
2308
- return new graphql.GraphQLInterfaceType(newConfig);
2309
- }
2310
- else if (graphql.isUnionType(type)) {
2311
- const config = type.toConfig();
2312
- const newConfig = {
2313
- ...config,
2314
- types: () => rewireNamedTypes(config.types),
2315
- };
2316
- return new graphql.GraphQLUnionType(newConfig);
2317
- }
2318
- else if (graphql.isInputObjectType(type)) {
2319
- const config = type.toConfig();
2320
- const newConfig = {
2321
- ...config,
2322
- fields: () => rewireInputFields(config.fields),
2323
- };
2324
- return new graphql.GraphQLInputObjectType(newConfig);
2325
- }
2326
- else if (graphql.isEnumType(type)) {
2327
- const enumConfig = type.toConfig();
2328
- return new graphql.GraphQLEnumType(enumConfig);
2329
- }
2330
- else if (graphql.isScalarType(type)) {
2331
- if (graphql.isSpecifiedScalarType(type)) {
2332
- return type;
2333
- }
2334
- const scalarConfig = type.toConfig();
2335
- return new graphql.GraphQLScalarType(scalarConfig);
2336
- }
2337
- throw new Error(`Unexpected schema type: ${type}`);
2338
- }
2339
- function rewireFields(fields) {
2340
- const rewiredFields = {};
2341
- for (const fieldName in fields) {
2342
- const field = fields[fieldName];
2343
- const rewiredFieldType = rewireType(field.type);
2344
- if (rewiredFieldType != null && field.args) {
2345
- field.type = rewiredFieldType;
2346
- field.args = rewireArgs(field.args);
2347
- rewiredFields[fieldName] = field;
2348
- }
2349
- }
2350
- return rewiredFields;
2351
- }
2352
- function rewireInputFields(fields) {
2353
- const rewiredFields = {};
2354
- for (const fieldName in fields) {
2355
- const field = fields[fieldName];
2356
- const rewiredFieldType = rewireType(field.type);
2357
- if (rewiredFieldType != null) {
2358
- field.type = rewiredFieldType;
2359
- rewiredFields[fieldName] = field;
2360
- }
2361
- }
2362
- return rewiredFields;
2363
- }
2364
- function rewireNamedTypes(namedTypes) {
2365
- const rewiredTypes = [];
2366
- for (const namedType of namedTypes) {
2367
- const rewiredType = rewireType(namedType);
2368
- if (rewiredType != null) {
2369
- rewiredTypes.push(rewiredType);
2370
- }
2371
- }
2372
- return rewiredTypes;
2373
- }
2374
- function rewireType(type) {
2375
- if (graphql.isListType(type)) {
2376
- const rewiredType = rewireType(type.ofType);
2377
- return rewiredType != null ? new graphql.GraphQLList(rewiredType) : null;
2378
- }
2379
- else if (graphql.isNonNullType(type)) {
2380
- const rewiredType = rewireType(type.ofType);
2381
- return rewiredType != null ? new graphql.GraphQLNonNull(rewiredType) : null;
2382
- }
2383
- else if (graphql.isNamedType(type)) {
2384
- let rewiredType = referenceTypeMap[type.name];
2385
- if (rewiredType === undefined) {
2386
- rewiredType = isNamedStub(type) ? getBuiltInForStub(type) : rewireNamedType(type);
2387
- newTypeMap[rewiredType.name] = referenceTypeMap[type.name] = rewiredType;
2388
- }
2389
- return rewiredType != null ? newTypeMap[rewiredType.name] : null;
2390
- }
2391
- return null;
2392
- }
2393
- }
2394
-
2395
- function transformInputValue(type, value, inputLeafValueTransformer = null, inputObjectValueTransformer = null) {
2396
- if (value == null) {
2397
- return value;
2398
- }
2399
- const nullableType = graphql.getNullableType(type);
2400
- if (graphql.isLeafType(nullableType)) {
2401
- return inputLeafValueTransformer != null ? inputLeafValueTransformer(nullableType, value) : value;
2402
- }
2403
- else if (graphql.isListType(nullableType)) {
2404
- return value.map((listMember) => transformInputValue(nullableType.ofType, listMember, inputLeafValueTransformer, inputObjectValueTransformer));
2405
- }
2406
- else if (graphql.isInputObjectType(nullableType)) {
2407
- const fields = nullableType.getFields();
2408
- const newValue = {};
2409
- for (const key in value) {
2410
- const field = fields[key];
2411
- if (field != null) {
2412
- newValue[key] = transformInputValue(field.type, value[key], inputLeafValueTransformer, inputObjectValueTransformer);
2413
- }
2414
- }
2415
- return inputObjectValueTransformer != null ? inputObjectValueTransformer(nullableType, newValue) : newValue;
2416
- }
2417
- // unreachable, no other possible return value
2418
- }
2419
- function serializeInputValue(type, value) {
2420
- return transformInputValue(type, value, (t, v) => {
2421
- try {
2422
- return t.serialize(v);
2423
- }
2424
- catch (_a) {
2425
- return v;
2426
- }
2427
- });
2428
- }
2429
- function parseInputValue(type, value) {
2430
- return transformInputValue(type, value, (t, v) => {
2431
- try {
2432
- return t.parseValue(v);
2433
- }
2434
- catch (_a) {
2435
- return v;
2436
- }
2437
- });
2438
- }
2439
- function parseInputValueLiteral(type, value) {
2440
- return transformInputValue(type, value, (t, v) => t.parseLiteral(v, {}));
2441
- }
2442
-
2443
- function mapSchema(schema, schemaMapper = {}) {
2444
- const newTypeMap = mapArguments(mapFields(mapTypes(mapDefaultValues(mapEnumValues(mapTypes(mapDefaultValues(schema.getTypeMap(), schema, serializeInputValue), schema, schemaMapper, type => graphql.isLeafType(type)), schema, schemaMapper), schema, parseInputValue), schema, schemaMapper, type => !graphql.isLeafType(type)), schema, schemaMapper), schema, schemaMapper);
2445
- const originalDirectives = schema.getDirectives();
2446
- const newDirectives = mapDirectives(originalDirectives, schema, schemaMapper);
2447
- const { typeMap, directives } = rewireTypes(newTypeMap, newDirectives);
2448
- return new graphql.GraphQLSchema({
2449
- ...schema.toConfig(),
2450
- query: getObjectTypeFromTypeMap(typeMap, getObjectTypeFromTypeMap(newTypeMap, schema.getQueryType())),
2451
- mutation: getObjectTypeFromTypeMap(typeMap, getObjectTypeFromTypeMap(newTypeMap, schema.getMutationType())),
2452
- subscription: getObjectTypeFromTypeMap(typeMap, getObjectTypeFromTypeMap(newTypeMap, schema.getSubscriptionType())),
2453
- types: Object.values(typeMap),
2454
- directives,
2455
- });
2456
- }
2457
- function mapTypes(originalTypeMap, schema, schemaMapper, testFn = () => true) {
2458
- const newTypeMap = {};
2459
- for (const typeName in originalTypeMap) {
2460
- if (!typeName.startsWith('__')) {
2461
- const originalType = originalTypeMap[typeName];
2462
- if (originalType == null || !testFn(originalType)) {
2463
- newTypeMap[typeName] = originalType;
2464
- continue;
2465
- }
2466
- const typeMapper = getTypeMapper(schema, schemaMapper, typeName);
2467
- if (typeMapper == null) {
2468
- newTypeMap[typeName] = originalType;
2469
- continue;
2470
- }
2471
- const maybeNewType = typeMapper(originalType, schema);
2472
- if (maybeNewType === undefined) {
2473
- newTypeMap[typeName] = originalType;
2474
- continue;
2475
- }
2476
- newTypeMap[typeName] = maybeNewType;
2477
- }
2478
- }
2479
- return newTypeMap;
2480
- }
2481
- function mapEnumValues(originalTypeMap, schema, schemaMapper) {
2482
- const enumValueMapper = getEnumValueMapper(schemaMapper);
2483
- if (!enumValueMapper) {
2484
- return originalTypeMap;
2485
- }
2486
- return mapTypes(originalTypeMap, schema, {
2487
- [exports.MapperKind.ENUM_TYPE]: type => {
2488
- const config = type.toConfig();
2489
- const originalEnumValueConfigMap = config.values;
2490
- const newEnumValueConfigMap = {};
2491
- for (const externalValue in originalEnumValueConfigMap) {
2492
- const originalEnumValueConfig = originalEnumValueConfigMap[externalValue];
2493
- const mappedEnumValue = enumValueMapper(originalEnumValueConfig, type.name, schema, externalValue);
2494
- if (mappedEnumValue === undefined) {
2495
- newEnumValueConfigMap[externalValue] = originalEnumValueConfig;
2496
- }
2497
- else if (Array.isArray(mappedEnumValue)) {
2498
- const [newExternalValue, newEnumValueConfig] = mappedEnumValue;
2499
- newEnumValueConfigMap[newExternalValue] =
2500
- newEnumValueConfig === undefined ? originalEnumValueConfig : newEnumValueConfig;
2501
- }
2502
- else if (mappedEnumValue !== null) {
2503
- newEnumValueConfigMap[externalValue] = mappedEnumValue;
2504
- }
2505
- }
2506
- return correctASTNodes(new graphql.GraphQLEnumType({
2507
- ...config,
2508
- values: newEnumValueConfigMap,
2509
- }));
2510
- },
2511
- }, type => graphql.isEnumType(type));
2512
- }
2513
- function mapDefaultValues(originalTypeMap, schema, fn) {
2514
- const newTypeMap = mapArguments(originalTypeMap, schema, {
2515
- [exports.MapperKind.ARGUMENT]: argumentConfig => {
2516
- if (argumentConfig.defaultValue === undefined) {
2517
- return argumentConfig;
2518
- }
2519
- const maybeNewType = getNewType(originalTypeMap, argumentConfig.type);
2520
- if (maybeNewType != null) {
2521
- return {
2522
- ...argumentConfig,
2523
- defaultValue: fn(maybeNewType, argumentConfig.defaultValue),
2524
- };
2525
- }
2526
- },
2527
- });
2528
- return mapFields(newTypeMap, schema, {
2529
- [exports.MapperKind.INPUT_OBJECT_FIELD]: inputFieldConfig => {
2530
- if (inputFieldConfig.defaultValue === undefined) {
2531
- return inputFieldConfig;
2532
- }
2533
- const maybeNewType = getNewType(newTypeMap, inputFieldConfig.type);
2534
- if (maybeNewType != null) {
2535
- return {
2536
- ...inputFieldConfig,
2537
- defaultValue: fn(maybeNewType, inputFieldConfig.defaultValue),
2538
- };
2539
- }
2540
- },
2541
- });
2542
- }
2543
- function getNewType(newTypeMap, type) {
2544
- if (graphql.isListType(type)) {
2545
- const newType = getNewType(newTypeMap, type.ofType);
2546
- return newType != null ? new graphql.GraphQLList(newType) : null;
2547
- }
2548
- else if (graphql.isNonNullType(type)) {
2549
- const newType = getNewType(newTypeMap, type.ofType);
2550
- return newType != null ? new graphql.GraphQLNonNull(newType) : null;
2551
- }
2552
- else if (graphql.isNamedType(type)) {
2553
- const newType = newTypeMap[type.name];
2554
- return newType != null ? newType : null;
2555
- }
2556
- return null;
2557
- }
2558
- function mapFields(originalTypeMap, schema, schemaMapper) {
2559
- const newTypeMap = {};
2560
- for (const typeName in originalTypeMap) {
2561
- if (!typeName.startsWith('__')) {
2562
- const originalType = originalTypeMap[typeName];
2563
- if (!graphql.isObjectType(originalType) && !graphql.isInterfaceType(originalType) && !graphql.isInputObjectType(originalType)) {
2564
- newTypeMap[typeName] = originalType;
2565
- continue;
2566
- }
2567
- const fieldMapper = getFieldMapper(schema, schemaMapper, typeName);
2568
- if (fieldMapper == null) {
2569
- newTypeMap[typeName] = originalType;
2570
- continue;
2571
- }
2572
- const config = originalType.toConfig();
2573
- const originalFieldConfigMap = config.fields;
2574
- const newFieldConfigMap = {};
2575
- for (const fieldName in originalFieldConfigMap) {
2576
- const originalFieldConfig = originalFieldConfigMap[fieldName];
2577
- const mappedField = fieldMapper(originalFieldConfig, fieldName, typeName, schema);
2578
- if (mappedField === undefined) {
2579
- newFieldConfigMap[fieldName] = originalFieldConfig;
2580
- }
2581
- else if (Array.isArray(mappedField)) {
2582
- const [newFieldName, newFieldConfig] = mappedField;
2583
- if (newFieldConfig.astNode != null) {
2584
- newFieldConfig.astNode = {
2585
- ...newFieldConfig.astNode,
2586
- name: {
2587
- ...newFieldConfig.astNode.name,
2588
- value: newFieldName,
2589
- },
2590
- };
2591
- }
2592
- newFieldConfigMap[newFieldName] = newFieldConfig === undefined ? originalFieldConfig : newFieldConfig;
2593
- }
2594
- else if (mappedField !== null) {
2595
- newFieldConfigMap[fieldName] = mappedField;
2596
- }
2597
- }
2598
- if (graphql.isObjectType(originalType)) {
2599
- newTypeMap[typeName] = correctASTNodes(new graphql.GraphQLObjectType({
2600
- ...config,
2601
- fields: newFieldConfigMap,
2602
- }));
2603
- }
2604
- else if (graphql.isInterfaceType(originalType)) {
2605
- newTypeMap[typeName] = correctASTNodes(new graphql.GraphQLInterfaceType({
2606
- ...config,
2607
- fields: newFieldConfigMap,
2608
- }));
2609
- }
2610
- else {
2611
- newTypeMap[typeName] = correctASTNodes(new graphql.GraphQLInputObjectType({
2612
- ...config,
2613
- fields: newFieldConfigMap,
2614
- }));
2615
- }
2616
- }
2617
- }
2618
- return newTypeMap;
2619
- }
2620
- function mapArguments(originalTypeMap, schema, schemaMapper) {
2621
- const newTypeMap = {};
2622
- for (const typeName in originalTypeMap) {
2623
- if (!typeName.startsWith('__')) {
2624
- const originalType = originalTypeMap[typeName];
2625
- if (!graphql.isObjectType(originalType) && !graphql.isInterfaceType(originalType)) {
2626
- newTypeMap[typeName] = originalType;
2627
- continue;
2628
- }
2629
- const argumentMapper = getArgumentMapper(schemaMapper);
2630
- if (argumentMapper == null) {
2631
- newTypeMap[typeName] = originalType;
2632
- continue;
2633
- }
2634
- const config = originalType.toConfig();
2635
- const originalFieldConfigMap = config.fields;
2636
- const newFieldConfigMap = {};
2637
- for (const fieldName in originalFieldConfigMap) {
2638
- const originalFieldConfig = originalFieldConfigMap[fieldName];
2639
- const originalArgumentConfigMap = originalFieldConfig.args;
2640
- if (originalArgumentConfigMap == null) {
2641
- newFieldConfigMap[fieldName] = originalFieldConfig;
2642
- continue;
2643
- }
2644
- const argumentNames = Object.keys(originalArgumentConfigMap);
2645
- if (!argumentNames.length) {
2646
- newFieldConfigMap[fieldName] = originalFieldConfig;
2647
- continue;
2648
- }
2649
- const newArgumentConfigMap = {};
2650
- for (const argumentName of argumentNames) {
2651
- const originalArgumentConfig = originalArgumentConfigMap[argumentName];
2652
- const mappedArgument = argumentMapper(originalArgumentConfig, fieldName, typeName, schema);
2653
- if (mappedArgument === undefined) {
2654
- newArgumentConfigMap[argumentName] = originalArgumentConfig;
2655
- }
2656
- else if (Array.isArray(mappedArgument)) {
2657
- const [newArgumentName, newArgumentConfig] = mappedArgument;
2658
- newArgumentConfigMap[newArgumentName] = newArgumentConfig;
2659
- }
2660
- else if (mappedArgument !== null) {
2661
- newArgumentConfigMap[argumentName] = mappedArgument;
2662
- }
2663
- }
2664
- newFieldConfigMap[fieldName] = {
2665
- ...originalFieldConfig,
2666
- args: newArgumentConfigMap,
2667
- };
2668
- }
2669
- if (graphql.isObjectType(originalType)) {
2670
- newTypeMap[typeName] = new graphql.GraphQLObjectType({
2671
- ...config,
2672
- fields: newFieldConfigMap,
2673
- });
2674
- }
2675
- else if (graphql.isInterfaceType(originalType)) {
2676
- newTypeMap[typeName] = new graphql.GraphQLInterfaceType({
2677
- ...config,
2678
- fields: newFieldConfigMap,
2679
- });
2680
- }
2681
- else {
2682
- newTypeMap[typeName] = new graphql.GraphQLInputObjectType({
2683
- ...config,
2684
- fields: newFieldConfigMap,
2685
- });
2686
- }
2687
- }
2688
- }
2689
- return newTypeMap;
2690
- }
2691
- function mapDirectives(originalDirectives, schema, schemaMapper) {
2692
- const directiveMapper = getDirectiveMapper(schemaMapper);
2693
- if (directiveMapper == null) {
2694
- return originalDirectives.slice();
2695
- }
2696
- const newDirectives = [];
2697
- for (const directive of originalDirectives) {
2698
- const mappedDirective = directiveMapper(directive, schema);
2699
- if (mappedDirective === undefined) {
2700
- newDirectives.push(directive);
2701
- }
2702
- else if (mappedDirective !== null) {
2703
- newDirectives.push(mappedDirective);
2704
- }
2705
- }
2706
- return newDirectives;
2707
- }
2708
- function getTypeSpecifiers(schema, typeName) {
2709
- var _a, _b, _c;
2710
- const type = schema.getType(typeName);
2711
- const specifiers = [exports.MapperKind.TYPE];
2712
- if (graphql.isObjectType(type)) {
2713
- specifiers.push(exports.MapperKind.COMPOSITE_TYPE, exports.MapperKind.OBJECT_TYPE);
2714
- if (typeName === ((_a = schema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name)) {
2715
- specifiers.push(exports.MapperKind.ROOT_OBJECT, exports.MapperKind.QUERY);
2716
- }
2717
- else if (typeName === ((_b = schema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name)) {
2718
- specifiers.push(exports.MapperKind.ROOT_OBJECT, exports.MapperKind.MUTATION);
2719
- }
2720
- else if (typeName === ((_c = schema.getSubscriptionType()) === null || _c === void 0 ? void 0 : _c.name)) {
2721
- specifiers.push(exports.MapperKind.ROOT_OBJECT, exports.MapperKind.SUBSCRIPTION);
2722
- }
2723
- }
2724
- else if (graphql.isInputObjectType(type)) {
2725
- specifiers.push(exports.MapperKind.INPUT_OBJECT_TYPE);
2726
- }
2727
- else if (graphql.isInterfaceType(type)) {
2728
- specifiers.push(exports.MapperKind.COMPOSITE_TYPE, exports.MapperKind.ABSTRACT_TYPE, exports.MapperKind.INTERFACE_TYPE);
2729
- }
2730
- else if (graphql.isUnionType(type)) {
2731
- specifiers.push(exports.MapperKind.COMPOSITE_TYPE, exports.MapperKind.ABSTRACT_TYPE, exports.MapperKind.UNION_TYPE);
2732
- }
2733
- else if (graphql.isEnumType(type)) {
2734
- specifiers.push(exports.MapperKind.ENUM_TYPE);
2735
- }
2736
- else if (graphql.isScalarType(type)) {
2737
- specifiers.push(exports.MapperKind.SCALAR_TYPE);
2738
- }
2739
- return specifiers;
2740
- }
2741
- function getTypeMapper(schema, schemaMapper, typeName) {
2742
- const specifiers = getTypeSpecifiers(schema, typeName);
2743
- let typeMapper;
2744
- const stack = [...specifiers];
2745
- while (!typeMapper && stack.length > 0) {
2746
- // It is safe to use the ! operator here as we check the length.
2747
- const next = stack.pop();
2748
- typeMapper = schemaMapper[next];
2749
- }
2750
- return typeMapper != null ? typeMapper : null;
2751
- }
2752
- function getFieldSpecifiers(schema, typeName) {
2753
- var _a, _b, _c;
2754
- const type = schema.getType(typeName);
2755
- const specifiers = [exports.MapperKind.FIELD];
2756
- if (graphql.isObjectType(type)) {
2757
- specifiers.push(exports.MapperKind.COMPOSITE_FIELD, exports.MapperKind.OBJECT_FIELD);
2758
- if (typeName === ((_a = schema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name)) {
2759
- specifiers.push(exports.MapperKind.ROOT_FIELD, exports.MapperKind.QUERY_ROOT_FIELD);
2760
- }
2761
- else if (typeName === ((_b = schema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name)) {
2762
- specifiers.push(exports.MapperKind.ROOT_FIELD, exports.MapperKind.MUTATION_ROOT_FIELD);
2763
- }
2764
- else if (typeName === ((_c = schema.getSubscriptionType()) === null || _c === void 0 ? void 0 : _c.name)) {
2765
- specifiers.push(exports.MapperKind.ROOT_FIELD, exports.MapperKind.SUBSCRIPTION_ROOT_FIELD);
2766
- }
2767
- }
2768
- else if (graphql.isInterfaceType(type)) {
2769
- specifiers.push(exports.MapperKind.COMPOSITE_FIELD, exports.MapperKind.INTERFACE_FIELD);
2770
- }
2771
- else if (graphql.isInputObjectType(type)) {
2772
- specifiers.push(exports.MapperKind.INPUT_OBJECT_FIELD);
2773
- }
2774
- return specifiers;
2775
- }
2776
- function getFieldMapper(schema, schemaMapper, typeName) {
2777
- const specifiers = getFieldSpecifiers(schema, typeName);
2778
- let fieldMapper;
2779
- const stack = [...specifiers];
2780
- while (!fieldMapper && stack.length > 0) {
2781
- // It is safe to use the ! operator here as we check the length.
2782
- const next = stack.pop();
2783
- // TODO: fix this as unknown cast
2784
- fieldMapper = schemaMapper[next];
2785
- }
2786
- return fieldMapper !== null && fieldMapper !== void 0 ? fieldMapper : null;
2787
- }
2788
- function getArgumentMapper(schemaMapper) {
2789
- const argumentMapper = schemaMapper[exports.MapperKind.ARGUMENT];
2790
- return argumentMapper != null ? argumentMapper : null;
2791
- }
2792
- function getDirectiveMapper(schemaMapper) {
2793
- const directiveMapper = schemaMapper[exports.MapperKind.DIRECTIVE];
2794
- return directiveMapper != null ? directiveMapper : null;
2795
- }
2796
- function getEnumValueMapper(schemaMapper) {
2797
- const enumValueMapper = schemaMapper[exports.MapperKind.ENUM_VALUE];
2798
- return enumValueMapper != null ? enumValueMapper : null;
2799
- }
2800
- function correctASTNodes(type) {
2801
- if (graphql.isObjectType(type)) {
2802
- const config = type.toConfig();
2803
- if (config.astNode != null) {
2804
- const fields = [];
2805
- for (const fieldName in config.fields) {
2806
- const fieldConfig = config.fields[fieldName];
2807
- if (fieldConfig.astNode != null) {
2808
- fields.push(fieldConfig.astNode);
2809
- }
2810
- }
2811
- config.astNode = {
2812
- ...config.astNode,
2813
- kind: graphql.Kind.OBJECT_TYPE_DEFINITION,
2814
- fields,
2815
- };
2816
- }
2817
- if (config.extensionASTNodes != null) {
2818
- config.extensionASTNodes = config.extensionASTNodes.map(node => ({
2819
- ...node,
2820
- kind: graphql.Kind.OBJECT_TYPE_EXTENSION,
2821
- fields: undefined,
2822
- }));
2823
- }
2824
- return new graphql.GraphQLObjectType(config);
2825
- }
2826
- else if (graphql.isInterfaceType(type)) {
2827
- const config = type.toConfig();
2828
- if (config.astNode != null) {
2829
- const fields = [];
2830
- for (const fieldName in config.fields) {
2831
- const fieldConfig = config.fields[fieldName];
2832
- if (fieldConfig.astNode != null) {
2833
- fields.push(fieldConfig.astNode);
2834
- }
2835
- }
2836
- config.astNode = {
2837
- ...config.astNode,
2838
- kind: graphql.Kind.INTERFACE_TYPE_DEFINITION,
2839
- fields,
2840
- };
2841
- }
2842
- if (config.extensionASTNodes != null) {
2843
- config.extensionASTNodes = config.extensionASTNodes.map(node => ({
2844
- ...node,
2845
- kind: graphql.Kind.INTERFACE_TYPE_EXTENSION,
2846
- fields: undefined,
2847
- }));
2848
- }
2849
- return new graphql.GraphQLInterfaceType(config);
2850
- }
2851
- else if (graphql.isInputObjectType(type)) {
2852
- const config = type.toConfig();
2853
- if (config.astNode != null) {
2854
- const fields = [];
2855
- for (const fieldName in config.fields) {
2856
- const fieldConfig = config.fields[fieldName];
2857
- if (fieldConfig.astNode != null) {
2858
- fields.push(fieldConfig.astNode);
2859
- }
2860
- }
2861
- config.astNode = {
2862
- ...config.astNode,
2863
- kind: graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION,
2864
- fields,
2865
- };
2866
- }
2867
- if (config.extensionASTNodes != null) {
2868
- config.extensionASTNodes = config.extensionASTNodes.map(node => ({
2869
- ...node,
2870
- kind: graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION,
2871
- fields: undefined,
2872
- }));
2873
- }
2874
- return new graphql.GraphQLInputObjectType(config);
2875
- }
2876
- else if (graphql.isEnumType(type)) {
2877
- const config = type.toConfig();
2878
- if (config.astNode != null) {
2879
- const values = [];
2880
- for (const enumKey in config.values) {
2881
- const enumValueConfig = config.values[enumKey];
2882
- if (enumValueConfig.astNode != null) {
2883
- values.push(enumValueConfig.astNode);
2884
- }
2885
- }
2886
- config.astNode = {
2887
- ...config.astNode,
2888
- values,
2889
- };
2890
- }
2891
- if (config.extensionASTNodes != null) {
2892
- config.extensionASTNodes = config.extensionASTNodes.map(node => ({
2893
- ...node,
2894
- values: undefined,
2895
- }));
2896
- }
2897
- return new graphql.GraphQLEnumType(config);
2898
- }
2899
- else {
2900
- return type;
2901
- }
2902
- }
2903
-
2904
- function filterSchema({ schema, typeFilter = () => true, fieldFilter = undefined, rootFieldFilter = undefined, objectFieldFilter = undefined, interfaceFieldFilter = undefined, inputObjectFieldFilter = undefined, argumentFilter = undefined, }) {
2905
- const filteredSchema = mapSchema(schema, {
2906
- [exports.MapperKind.QUERY]: (type) => filterRootFields(type, 'Query', rootFieldFilter, argumentFilter),
2907
- [exports.MapperKind.MUTATION]: (type) => filterRootFields(type, 'Mutation', rootFieldFilter, argumentFilter),
2908
- [exports.MapperKind.SUBSCRIPTION]: (type) => filterRootFields(type, 'Subscription', rootFieldFilter, argumentFilter),
2909
- [exports.MapperKind.OBJECT_TYPE]: (type) => typeFilter(type.name, type)
2910
- ? filterElementFields(graphql.GraphQLObjectType, type, objectFieldFilter || fieldFilter, argumentFilter)
2911
- : null,
2912
- [exports.MapperKind.INTERFACE_TYPE]: (type) => typeFilter(type.name, type)
2913
- ? filterElementFields(graphql.GraphQLInterfaceType, type, interfaceFieldFilter || fieldFilter, argumentFilter)
2914
- : null,
2915
- [exports.MapperKind.INPUT_OBJECT_TYPE]: (type) => typeFilter(type.name, type)
2916
- ? filterElementFields(graphql.GraphQLInputObjectType, type, inputObjectFieldFilter || fieldFilter)
2917
- : null,
2918
- [exports.MapperKind.UNION_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),
2919
- [exports.MapperKind.ENUM_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),
2920
- [exports.MapperKind.SCALAR_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),
2921
- });
2922
- return filteredSchema;
2923
- }
2924
- function filterRootFields(type, operation, rootFieldFilter, argumentFilter) {
2925
- if (rootFieldFilter || argumentFilter) {
2926
- const config = type.toConfig();
2927
- for (const fieldName in config.fields) {
2928
- const field = config.fields[fieldName];
2929
- if (rootFieldFilter && !rootFieldFilter(operation, fieldName, config.fields[fieldName])) {
2930
- delete config.fields[fieldName];
2931
- }
2932
- else if (argumentFilter && field.args) {
2933
- for (const argName in field.args) {
2934
- if (!argumentFilter(operation, fieldName, argName, field.args[argName])) {
2935
- delete field.args[argName];
2936
- }
2937
- }
2938
- }
2939
- }
2940
- return new graphql.GraphQLObjectType(config);
2941
- }
2942
- return type;
2943
- }
2944
- function filterElementFields(ElementConstructor, type, fieldFilter, argumentFilter) {
2945
- if (fieldFilter || argumentFilter) {
2946
- const config = type.toConfig();
2947
- for (const fieldName in config.fields) {
2948
- const field = config.fields[fieldName];
2949
- if (fieldFilter && !fieldFilter(type.name, fieldName, config.fields[fieldName])) {
2950
- delete config.fields[fieldName];
2951
- }
2952
- else if (argumentFilter && 'args' in field) {
2953
- for (const argName in field.args) {
2954
- if (!argumentFilter(type.name, fieldName, argName, field.args[argName])) {
2955
- delete field.args[argName];
2956
- }
2957
- }
2958
- }
2959
- }
2960
- return new ElementConstructor(config);
2961
- }
2962
- }
2963
-
2964
- // Update any references to named schema types that disagree with the named
2965
- // types found in schema.getTypeMap().
2966
- //
2967
- // healSchema and its callers (visitSchema/visitSchemaDirectives) all modify the schema in place.
2968
- // Therefore, private variables (such as the stored implementation map and the proper root types)
2969
- // are not updated.
2970
- //
2971
- // If this causes issues, the schema could be more aggressively healed as follows:
2972
- //
2973
- // healSchema(schema);
2974
- // const config = schema.toConfig()
2975
- // const healedSchema = new GraphQLSchema({
2976
- // ...config,
2977
- // query: schema.getType('<desired new root query type name>'),
2978
- // mutation: schema.getType('<desired new root mutation type name>'),
2979
- // subscription: schema.getType('<desired new root subscription type name>'),
2980
- // });
2981
- //
2982
- // One can then also -- if necessary -- assign the correct private variables to the initial schema
2983
- // as follows:
2984
- // Object.assign(schema, healedSchema);
2985
- //
2986
- // These steps are not taken automatically to preserve backwards compatibility with graphql-tools v4.
2987
- // See https://github.com/ardatan/graphql-tools/issues/1462
2988
- //
2989
- // They were briefly taken in v5, but can now be phased out as they were only required when other
2990
- // areas of the codebase were using healSchema and visitSchema more extensively.
2991
- //
2992
- function healSchema(schema) {
2993
- healTypes(schema.getTypeMap(), schema.getDirectives());
2994
- return schema;
2995
- }
2996
- function healTypes(originalTypeMap, directives) {
2997
- const actualNamedTypeMap = Object.create(null);
2998
- // If any of the .name properties of the GraphQLNamedType objects in
2999
- // schema.getTypeMap() have changed, the keys of the type map need to
3000
- // be updated accordingly.
3001
- for (const typeName in originalTypeMap) {
3002
- const namedType = originalTypeMap[typeName];
3003
- if (namedType == null || typeName.startsWith('__')) {
3004
- continue;
3005
- }
3006
- const actualName = namedType.name;
3007
- if (actualName.startsWith('__')) {
3008
- continue;
3009
- }
3010
- if (actualName in actualNamedTypeMap) {
3011
- throw new Error(`Duplicate schema type name ${actualName}`);
3012
- }
3013
- actualNamedTypeMap[actualName] = namedType;
3014
- // Note: we are deliberately leaving namedType in the schema by its
3015
- // original name (which might be different from actualName), so that
3016
- // references by that name can be healed.
3017
- }
3018
- // Now add back every named type by its actual name.
3019
- for (const typeName in actualNamedTypeMap) {
3020
- const namedType = actualNamedTypeMap[typeName];
3021
- originalTypeMap[typeName] = namedType;
3022
- }
3023
- // Directive declaration argument types can refer to named types.
3024
- for (const decl of directives) {
3025
- decl.args = decl.args.filter(arg => {
3026
- arg.type = healType(arg.type);
3027
- return arg.type !== null;
3028
- });
3029
- }
3030
- for (const typeName in originalTypeMap) {
3031
- const namedType = originalTypeMap[typeName];
3032
- // Heal all named types, except for dangling references, kept only to redirect.
3033
- if (!typeName.startsWith('__') && typeName in actualNamedTypeMap) {
3034
- if (namedType != null) {
3035
- healNamedType(namedType);
3036
- }
3037
- }
3038
- }
3039
- for (const typeName in originalTypeMap) {
3040
- if (!typeName.startsWith('__') && !(typeName in actualNamedTypeMap)) {
3041
- delete originalTypeMap[typeName];
3042
- }
3043
- }
3044
- function healNamedType(type) {
3045
- if (graphql.isObjectType(type)) {
3046
- healFields(type);
3047
- healInterfaces(type);
3048
- return;
3049
- }
3050
- else if (graphql.isInterfaceType(type)) {
3051
- healFields(type);
3052
- if ('getInterfaces' in type) {
3053
- healInterfaces(type);
3054
- }
3055
- return;
3056
- }
3057
- else if (graphql.isUnionType(type)) {
3058
- healUnderlyingTypes(type);
3059
- return;
3060
- }
3061
- else if (graphql.isInputObjectType(type)) {
3062
- healInputFields(type);
3063
- return;
3064
- }
3065
- else if (graphql.isLeafType(type)) {
3066
- return;
3067
- }
3068
- throw new Error(`Unexpected schema type: ${type}`);
3069
- }
3070
- function healFields(type) {
3071
- const fieldMap = type.getFields();
3072
- for (const [key, field] of Object.entries(fieldMap)) {
3073
- field.args
3074
- .map(arg => {
3075
- arg.type = healType(arg.type);
3076
- return arg.type === null ? null : arg;
3077
- })
3078
- .filter(Boolean);
3079
- field.type = healType(field.type);
3080
- if (field.type === null) {
3081
- delete fieldMap[key];
3082
- }
3083
- }
3084
- }
3085
- function healInterfaces(type) {
3086
- if ('getInterfaces' in type) {
3087
- const interfaces = type.getInterfaces();
3088
- interfaces.push(...interfaces
3089
- .splice(0)
3090
- .map(iface => healType(iface))
3091
- .filter(Boolean));
3092
- }
3093
- }
3094
- function healInputFields(type) {
3095
- const fieldMap = type.getFields();
3096
- for (const [key, field] of Object.entries(fieldMap)) {
3097
- field.type = healType(field.type);
3098
- if (field.type === null) {
3099
- delete fieldMap[key];
3100
- }
3101
- }
3102
- }
3103
- function healUnderlyingTypes(type) {
3104
- const types = type.getTypes();
3105
- types.push(...types
3106
- .splice(0)
3107
- .map(t => healType(t))
3108
- .filter(Boolean));
3109
- }
3110
- function healType(type) {
3111
- // Unwrap the two known wrapper types
3112
- if (graphql.isListType(type)) {
3113
- const healedType = healType(type.ofType);
3114
- return healedType != null ? new graphql.GraphQLList(healedType) : null;
3115
- }
3116
- else if (graphql.isNonNullType(type)) {
3117
- const healedType = healType(type.ofType);
3118
- return healedType != null ? new graphql.GraphQLNonNull(healedType) : null;
3119
- }
3120
- else if (graphql.isNamedType(type)) {
3121
- // If a type annotation on a field or an argument or a union member is
3122
- // any `GraphQLNamedType` with a `name`, then it must end up identical
3123
- // to `schema.getType(name)`, since `schema.getTypeMap()` is the source
3124
- // of truth for all named schema types.
3125
- // Note that new types can still be simply added by adding a field, as
3126
- // the official type will be undefined, not null.
3127
- const officialType = originalTypeMap[type.name];
3128
- if (officialType && type !== officialType) {
3129
- return officialType;
3130
- }
3131
- }
3132
- return type;
3133
- }
3134
- }
3135
-
3136
- function getResolversFromSchema(schema,
3137
- // Include default merged resolvers
3138
- includeDefaultMergedResolver) {
3139
- var _a, _b;
3140
- const resolvers = Object.create(null);
3141
- const typeMap = schema.getTypeMap();
3142
- for (const typeName in typeMap) {
3143
- if (!typeName.startsWith('__')) {
3144
- const type = typeMap[typeName];
3145
- if (graphql.isScalarType(type)) {
3146
- if (!graphql.isSpecifiedScalarType(type)) {
3147
- const config = type.toConfig();
3148
- delete config.astNode; // avoid AST duplication elsewhere
3149
- resolvers[typeName] = new graphql.GraphQLScalarType(config);
3150
- }
3151
- }
3152
- else if (graphql.isEnumType(type)) {
3153
- resolvers[typeName] = {};
3154
- const values = type.getValues();
3155
- for (const value of values) {
3156
- resolvers[typeName][value.name] = value.value;
3157
- }
3158
- }
3159
- else if (graphql.isInterfaceType(type)) {
3160
- if (type.resolveType != null) {
3161
- resolvers[typeName] = {
3162
- __resolveType: type.resolveType,
3163
- };
3164
- }
3165
- }
3166
- else if (graphql.isUnionType(type)) {
3167
- if (type.resolveType != null) {
3168
- resolvers[typeName] = {
3169
- __resolveType: type.resolveType,
3170
- };
3171
- }
3172
- }
3173
- else if (graphql.isObjectType(type)) {
3174
- resolvers[typeName] = {};
3175
- if (type.isTypeOf != null) {
3176
- resolvers[typeName].__isTypeOf = type.isTypeOf;
3177
- }
3178
- const fields = type.getFields();
3179
- for (const fieldName in fields) {
3180
- const field = fields[fieldName];
3181
- if (field.subscribe != null) {
3182
- resolvers[typeName][fieldName] = resolvers[typeName][fieldName] || {};
3183
- resolvers[typeName][fieldName].subscribe = field.subscribe;
3184
- }
3185
- if (field.resolve != null && ((_a = field.resolve) === null || _a === void 0 ? void 0 : _a.name) !== 'defaultFieldResolver') {
3186
- switch ((_b = field.resolve) === null || _b === void 0 ? void 0 : _b.name) {
3187
- case 'defaultMergedResolver':
3188
- if (!includeDefaultMergedResolver) {
3189
- continue;
3190
- }
3191
- break;
3192
- case 'defaultFieldResolver':
3193
- continue;
3194
- }
3195
- resolvers[typeName][fieldName] = resolvers[typeName][fieldName] || {};
3196
- resolvers[typeName][fieldName].resolve = field.resolve;
3197
- }
3198
- }
3199
- }
3200
- }
3201
- }
3202
- return resolvers;
3203
- }
3204
-
3205
- function forEachField(schema, fn) {
3206
- const typeMap = schema.getTypeMap();
3207
- for (const typeName in typeMap) {
3208
- const type = typeMap[typeName];
3209
- // TODO: maybe have an option to include these?
3210
- if (!graphql.getNamedType(type).name.startsWith('__') && graphql.isObjectType(type)) {
3211
- const fields = type.getFields();
3212
- for (const fieldName in fields) {
3213
- const field = fields[fieldName];
3214
- fn(field, typeName, fieldName);
3215
- }
3216
- }
3217
- }
3218
- }
3219
-
3220
- function forEachDefaultValue(schema, fn) {
3221
- const typeMap = schema.getTypeMap();
3222
- for (const typeName in typeMap) {
3223
- const type = typeMap[typeName];
3224
- if (!graphql.getNamedType(type).name.startsWith('__')) {
3225
- if (graphql.isObjectType(type)) {
3226
- const fields = type.getFields();
3227
- for (const fieldName in fields) {
3228
- const field = fields[fieldName];
3229
- for (const arg of field.args) {
3230
- arg.defaultValue = fn(arg.type, arg.defaultValue);
3231
- }
3232
- }
3233
- }
3234
- else if (graphql.isInputObjectType(type)) {
3235
- const fields = type.getFields();
3236
- for (const fieldName in fields) {
3237
- const field = fields[fieldName];
3238
- field.defaultValue = fn(field.type, field.defaultValue);
3239
- }
3240
- }
3241
- }
3242
- }
3243
- }
3244
-
3245
- // addTypes uses toConfig to create a new schema with a new or replaced
3246
- function addTypes(schema, newTypesOrDirectives) {
3247
- const config = schema.toConfig();
3248
- const originalTypeMap = {};
3249
- for (const type of config.types) {
3250
- originalTypeMap[type.name] = type;
3251
- }
3252
- const originalDirectiveMap = {};
3253
- for (const directive of config.directives) {
3254
- originalDirectiveMap[directive.name] = directive;
3255
- }
3256
- for (const newTypeOrDirective of newTypesOrDirectives) {
3257
- if (graphql.isNamedType(newTypeOrDirective)) {
3258
- originalTypeMap[newTypeOrDirective.name] = newTypeOrDirective;
3259
- }
3260
- else if (graphql.isDirective(newTypeOrDirective)) {
3261
- originalDirectiveMap[newTypeOrDirective.name] = newTypeOrDirective;
3262
- }
3263
- }
3264
- const { typeMap, directives } = rewireTypes(originalTypeMap, Object.values(originalDirectiveMap));
3265
- return new graphql.GraphQLSchema({
3266
- ...config,
3267
- query: getObjectTypeFromTypeMap(typeMap, schema.getQueryType()),
3268
- mutation: getObjectTypeFromTypeMap(typeMap, schema.getMutationType()),
3269
- subscription: getObjectTypeFromTypeMap(typeMap, schema.getSubscriptionType()),
3270
- types: Object.values(typeMap),
3271
- directives,
3272
- });
3273
- }
3274
-
3275
- /**
3276
- * Prunes the provided schema, removing unused and empty types
3277
- * @param schema The schema to prune
3278
- * @param options Additional options for removing unused types from the schema
3279
- */
3280
- function pruneSchema(schema, options = {}) {
3281
- const { skipEmptyCompositeTypePruning, skipEmptyUnionPruning, skipPruning, skipUnimplementedInterfacesPruning, skipUnusedTypesPruning, } = options;
3282
- let prunedTypes = []; // Pruned types during mapping
3283
- let prunedSchema = schema;
3284
- do {
3285
- let visited = visitSchema(prunedSchema);
3286
- // Custom pruning was defined, so we need to pre-emptively revisit the schema accounting for this
3287
- if (skipPruning) {
3288
- const revisit = [];
3289
- for (const typeName in prunedSchema.getTypeMap()) {
3290
- if (typeName.startsWith('__')) {
3291
- continue;
3292
- }
3293
- const type = prunedSchema.getType(typeName);
3294
- // if we want to skip pruning for this type, add it to the list of types to revisit
3295
- if (type && skipPruning(type)) {
3296
- revisit.push(typeName);
3297
- }
3298
- }
3299
- visited = visitQueue(revisit, prunedSchema, visited); // visit again
3300
- }
3301
- prunedTypes = [];
3302
- prunedSchema = mapSchema(prunedSchema, {
3303
- [exports.MapperKind.TYPE]: type => {
3304
- if (!visited.has(type.name) && !graphql.isSpecifiedScalarType(type)) {
3305
- if (graphql.isUnionType(type) ||
3306
- graphql.isInputObjectType(type) ||
3307
- graphql.isInterfaceType(type) ||
3308
- graphql.isObjectType(type) ||
3309
- graphql.isScalarType(type)) {
3310
- // skipUnusedTypesPruning: skip pruning unused types
3311
- if (skipUnusedTypesPruning) {
3312
- return type;
3313
- }
3314
- // skipEmptyUnionPruning: skip pruning empty unions
3315
- if (graphql.isUnionType(type) && skipEmptyUnionPruning && !Object.keys(type.getTypes()).length) {
3316
- return type;
3317
- }
3318
- if (graphql.isInputObjectType(type) || graphql.isInterfaceType(type) || graphql.isObjectType(type)) {
3319
- // skipEmptyCompositeTypePruning: skip pruning object types or interfaces with no fields
3320
- if (skipEmptyCompositeTypePruning && !Object.keys(type.getFields()).length) {
3321
- return type;
3322
- }
3323
- }
3324
- // skipUnimplementedInterfacesPruning: skip pruning interfaces that are not implemented by any other types
3325
- if (graphql.isInterfaceType(type) && skipUnimplementedInterfacesPruning) {
3326
- return type;
3327
- }
3328
- }
3329
- prunedTypes.push(type.name);
3330
- visited.delete(type.name);
3331
- return null;
3332
- }
3333
- return type;
3334
- },
3335
- });
3336
- } while (prunedTypes.length); // Might have empty types and need to prune again
3337
- return prunedSchema;
3338
- }
3339
- function visitSchema(schema) {
3340
- const queue = []; // queue of nodes to visit
3341
- // Grab the root types and start there
3342
- for (const type of getRootTypes(schema)) {
3343
- queue.push(type.name);
3344
- }
3345
- return visitQueue(queue, schema);
3346
- }
3347
- function visitQueue(queue, schema, visited = new Set()) {
3348
- // Interfaces encountered that are field return types need to be revisited to add their implementations
3349
- const revisit = new Map();
3350
- // Navigate all types starting with pre-queued types (root types)
3351
- while (queue.length) {
3352
- const typeName = queue.pop();
3353
- // Skip types we already visited unless it is an interface type that needs revisiting
3354
- if (visited.has(typeName) && revisit[typeName] !== true) {
3355
- continue;
3356
- }
3357
- const type = schema.getType(typeName);
3358
- if (type) {
3359
- // Get types for union
3360
- if (graphql.isUnionType(type)) {
3361
- queue.push(...type.getTypes().map(type => type.name));
3362
- }
3363
- // If it is an interface and it is a returned type, grab all implementations so we can use proper __typename in fragments
3364
- if (graphql.isInterfaceType(type) && revisit[typeName] === true) {
3365
- queue.push(...getImplementingTypes(type.name, schema));
3366
- // No need to revisit this interface again
3367
- revisit[typeName] = false;
3368
- }
3369
- // Visit interfaces this type is implementing if they haven't been visited yet
3370
- if ('getInterfaces' in type) {
3371
- // Only pushes to queue to visit but not return types
3372
- queue.push(...type.getInterfaces().map(iface => iface.name));
3373
- }
3374
- // If the type has files visit those field types
3375
- if ('getFields' in type) {
3376
- const fields = type.getFields();
3377
- const entries = Object.entries(fields);
3378
- if (!entries.length) {
3379
- continue;
3380
- }
3381
- for (const [, field] of entries) {
3382
- if (graphql.isObjectType(type)) {
3383
- // Visit arg types
3384
- queue.push(...field.args.map(arg => graphql.getNamedType(arg.type).name));
3385
- }
3386
- const namedType = graphql.getNamedType(field.type);
3387
- queue.push(namedType.name);
3388
- // Interfaces returned on fields need to be revisited to add their implementations
3389
- if (graphql.isInterfaceType(namedType) && !(namedType.name in revisit)) {
3390
- revisit[namedType.name] = true;
3391
- }
3392
- }
3393
- }
3394
- visited.add(typeName); // Mark as visited (and therefore it is used and should be kept)
3395
- }
3396
- }
3397
- return visited;
3398
- }
3399
-
3400
- function mergeDeep(sources, respectPrototype = false) {
3401
- const target = sources[0] || {};
3402
- const output = {};
3403
- if (respectPrototype) {
3404
- Object.setPrototypeOf(output, Object.create(Object.getPrototypeOf(target)));
3405
- }
3406
- for (const source of sources) {
3407
- if (isObject(target) && isObject(source)) {
3408
- if (respectPrototype) {
3409
- const outputPrototype = Object.getPrototypeOf(output);
3410
- const sourcePrototype = Object.getPrototypeOf(source);
3411
- if (sourcePrototype) {
3412
- for (const key of Object.getOwnPropertyNames(sourcePrototype)) {
3413
- const descriptor = Object.getOwnPropertyDescriptor(sourcePrototype, key);
3414
- if (isSome(descriptor)) {
3415
- Object.defineProperty(outputPrototype, key, descriptor);
3416
- }
3417
- }
3418
- }
3419
- }
3420
- for (const key in source) {
3421
- if (isObject(source[key])) {
3422
- if (!(key in output)) {
3423
- Object.assign(output, { [key]: source[key] });
3424
- }
3425
- else {
3426
- output[key] = mergeDeep([output[key], source[key]], respectPrototype);
3427
- }
3428
- }
3429
- else {
3430
- Object.assign(output, { [key]: source[key] });
3431
- }
3432
- }
3433
- }
3434
- }
3435
- return output;
3436
- }
3437
- function isObject(item) {
3438
- return item && typeof item === 'object' && !Array.isArray(item);
3439
- }
3440
-
3441
- function parseSelectionSet(selectionSet, options) {
3442
- const query = graphql.parse(selectionSet, options).definitions[0];
3443
- return query.selectionSet;
3444
- }
3445
-
3446
- /**
3447
- * Get the key under which the result of this resolver will be placed in the response JSON. Basically, just
3448
- * resolves aliases.
3449
- * @param info The info argument to the resolver.
3450
- */
3451
- function getResponseKeyFromInfo(info) {
3452
- return info.fieldNodes[0].alias != null ? info.fieldNodes[0].alias.value : info.fieldName;
3453
- }
3454
-
3455
- function appendObjectFields(schema, typeName, additionalFields) {
3456
- if (schema.getType(typeName) == null) {
3457
- return addTypes(schema, [
3458
- new graphql.GraphQLObjectType({
3459
- name: typeName,
3460
- fields: additionalFields,
3461
- }),
3462
- ]);
3463
- }
3464
- return mapSchema(schema, {
3465
- [exports.MapperKind.OBJECT_TYPE]: type => {
3466
- if (type.name === typeName) {
3467
- const config = type.toConfig();
3468
- const originalFieldConfigMap = config.fields;
3469
- const newFieldConfigMap = {};
3470
- for (const fieldName in originalFieldConfigMap) {
3471
- newFieldConfigMap[fieldName] = originalFieldConfigMap[fieldName];
3472
- }
3473
- for (const fieldName in additionalFields) {
3474
- newFieldConfigMap[fieldName] = additionalFields[fieldName];
3475
- }
3476
- return correctASTNodes(new graphql.GraphQLObjectType({
3477
- ...config,
3478
- fields: newFieldConfigMap,
3479
- }));
3480
- }
3481
- },
3482
- });
3483
- }
3484
- function removeObjectFields(schema, typeName, testFn) {
3485
- const removedFields = {};
3486
- const newSchema = mapSchema(schema, {
3487
- [exports.MapperKind.OBJECT_TYPE]: type => {
3488
- if (type.name === typeName) {
3489
- const config = type.toConfig();
3490
- const originalFieldConfigMap = config.fields;
3491
- const newFieldConfigMap = {};
3492
- for (const fieldName in originalFieldConfigMap) {
3493
- const originalFieldConfig = originalFieldConfigMap[fieldName];
3494
- if (testFn(fieldName, originalFieldConfig)) {
3495
- removedFields[fieldName] = originalFieldConfig;
3496
- }
3497
- else {
3498
- newFieldConfigMap[fieldName] = originalFieldConfig;
3499
- }
3500
- }
3501
- return correctASTNodes(new graphql.GraphQLObjectType({
3502
- ...config,
3503
- fields: newFieldConfigMap,
3504
- }));
3505
- }
3506
- },
3507
- });
3508
- return [newSchema, removedFields];
3509
- }
3510
- function selectObjectFields(schema, typeName, testFn) {
3511
- const selectedFields = {};
3512
- mapSchema(schema, {
3513
- [exports.MapperKind.OBJECT_TYPE]: type => {
3514
- if (type.name === typeName) {
3515
- const config = type.toConfig();
3516
- const originalFieldConfigMap = config.fields;
3517
- for (const fieldName in originalFieldConfigMap) {
3518
- const originalFieldConfig = originalFieldConfigMap[fieldName];
3519
- if (testFn(fieldName, originalFieldConfig)) {
3520
- selectedFields[fieldName] = originalFieldConfig;
3521
- }
3522
- }
3523
- }
3524
- return undefined;
3525
- },
3526
- });
3527
- return selectedFields;
3528
- }
3529
- function modifyObjectFields(schema, typeName, testFn, newFields) {
3530
- const removedFields = {};
3531
- const newSchema = mapSchema(schema, {
3532
- [exports.MapperKind.OBJECT_TYPE]: type => {
3533
- if (type.name === typeName) {
3534
- const config = type.toConfig();
3535
- const originalFieldConfigMap = config.fields;
3536
- const newFieldConfigMap = {};
3537
- for (const fieldName in originalFieldConfigMap) {
3538
- const originalFieldConfig = originalFieldConfigMap[fieldName];
3539
- if (testFn(fieldName, originalFieldConfig)) {
3540
- removedFields[fieldName] = originalFieldConfig;
3541
- }
3542
- else {
3543
- newFieldConfigMap[fieldName] = originalFieldConfig;
3544
- }
3545
- }
3546
- for (const fieldName in newFields) {
3547
- const fieldConfig = newFields[fieldName];
3548
- newFieldConfigMap[fieldName] = fieldConfig;
3549
- }
3550
- return correctASTNodes(new graphql.GraphQLObjectType({
3551
- ...config,
3552
- fields: newFieldConfigMap,
3553
- }));
3554
- }
3555
- },
3556
- });
3557
- return [newSchema, removedFields];
3558
- }
3559
-
3560
- function renameType(type, newTypeName) {
3561
- if (graphql.isObjectType(type)) {
3562
- return new graphql.GraphQLObjectType({
3563
- ...type.toConfig(),
3564
- name: newTypeName,
3565
- astNode: type.astNode == null
3566
- ? type.astNode
3567
- : {
3568
- ...type.astNode,
3569
- name: {
3570
- ...type.astNode.name,
3571
- value: newTypeName,
3572
- },
3573
- },
3574
- extensionASTNodes: type.extensionASTNodes == null
3575
- ? type.extensionASTNodes
3576
- : type.extensionASTNodes.map(node => ({
3577
- ...node,
3578
- name: {
3579
- ...node.name,
3580
- value: newTypeName,
3581
- },
3582
- })),
3583
- });
3584
- }
3585
- else if (graphql.isInterfaceType(type)) {
3586
- return new graphql.GraphQLInterfaceType({
3587
- ...type.toConfig(),
3588
- name: newTypeName,
3589
- astNode: type.astNode == null
3590
- ? type.astNode
3591
- : {
3592
- ...type.astNode,
3593
- name: {
3594
- ...type.astNode.name,
3595
- value: newTypeName,
3596
- },
3597
- },
3598
- extensionASTNodes: type.extensionASTNodes == null
3599
- ? type.extensionASTNodes
3600
- : type.extensionASTNodes.map(node => ({
3601
- ...node,
3602
- name: {
3603
- ...node.name,
3604
- value: newTypeName,
3605
- },
3606
- })),
3607
- });
3608
- }
3609
- else if (graphql.isUnionType(type)) {
3610
- return new graphql.GraphQLUnionType({
3611
- ...type.toConfig(),
3612
- name: newTypeName,
3613
- astNode: type.astNode == null
3614
- ? type.astNode
3615
- : {
3616
- ...type.astNode,
3617
- name: {
3618
- ...type.astNode.name,
3619
- value: newTypeName,
3620
- },
3621
- },
3622
- extensionASTNodes: type.extensionASTNodes == null
3623
- ? type.extensionASTNodes
3624
- : type.extensionASTNodes.map(node => ({
3625
- ...node,
3626
- name: {
3627
- ...node.name,
3628
- value: newTypeName,
3629
- },
3630
- })),
3631
- });
3632
- }
3633
- else if (graphql.isInputObjectType(type)) {
3634
- return new graphql.GraphQLInputObjectType({
3635
- ...type.toConfig(),
3636
- name: newTypeName,
3637
- astNode: type.astNode == null
3638
- ? type.astNode
3639
- : {
3640
- ...type.astNode,
3641
- name: {
3642
- ...type.astNode.name,
3643
- value: newTypeName,
3644
- },
3645
- },
3646
- extensionASTNodes: type.extensionASTNodes == null
3647
- ? type.extensionASTNodes
3648
- : type.extensionASTNodes.map(node => ({
3649
- ...node,
3650
- name: {
3651
- ...node.name,
3652
- value: newTypeName,
3653
- },
3654
- })),
3655
- });
3656
- }
3657
- else if (graphql.isEnumType(type)) {
3658
- return new graphql.GraphQLEnumType({
3659
- ...type.toConfig(),
3660
- name: newTypeName,
3661
- astNode: type.astNode == null
3662
- ? type.astNode
3663
- : {
3664
- ...type.astNode,
3665
- name: {
3666
- ...type.astNode.name,
3667
- value: newTypeName,
3668
- },
3669
- },
3670
- extensionASTNodes: type.extensionASTNodes == null
3671
- ? type.extensionASTNodes
3672
- : type.extensionASTNodes.map(node => ({
3673
- ...node,
3674
- name: {
3675
- ...node.name,
3676
- value: newTypeName,
3677
- },
3678
- })),
3679
- });
3680
- }
3681
- else if (graphql.isScalarType(type)) {
3682
- return new graphql.GraphQLScalarType({
3683
- ...type.toConfig(),
3684
- name: newTypeName,
3685
- astNode: type.astNode == null
3686
- ? type.astNode
3687
- : {
3688
- ...type.astNode,
3689
- name: {
3690
- ...type.astNode.name,
3691
- value: newTypeName,
3692
- },
3693
- },
3694
- extensionASTNodes: type.extensionASTNodes == null
3695
- ? type.extensionASTNodes
3696
- : type.extensionASTNodes.map(node => ({
3697
- ...node,
3698
- name: {
3699
- ...node.name,
3700
- value: newTypeName,
3701
- },
3702
- })),
3703
- });
3704
- }
3705
- throw new Error(`Unknown type ${type}.`);
3706
- }
3707
-
3708
- /**
3709
- * Given an AsyncIterable and a callback function, return an AsyncIterator
3710
- * which produces values mapped via calling the callback function.
3711
- */
3712
- function mapAsyncIterator(iterator, callback, rejectCallback) {
3713
- let $return;
3714
- let abruptClose;
3715
- if (typeof iterator.return === 'function') {
3716
- $return = iterator.return;
3717
- abruptClose = (error) => {
3718
- const rethrow = () => Promise.reject(error);
3719
- return $return.call(iterator).then(rethrow, rethrow);
3720
- };
3721
- }
3722
- function mapResult(result) {
3723
- return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);
3724
- }
3725
- let mapReject;
3726
- if (rejectCallback) {
3727
- // Capture rejectCallback to ensure it cannot be null.
3728
- const reject = rejectCallback;
3729
- mapReject = (error) => asyncMapValue(error, reject).then(iteratorResult, abruptClose);
3730
- }
3731
- return {
3732
- next() {
3733
- return iterator.next().then(mapResult, mapReject);
3734
- },
3735
- return() {
3736
- return $return
3737
- ? $return.call(iterator).then(mapResult, mapReject)
3738
- : Promise.resolve({ value: undefined, done: true });
3739
- },
3740
- throw(error) {
3741
- if (typeof iterator.throw === 'function') {
3742
- return iterator.throw(error).then(mapResult, mapReject);
3743
- }
3744
- return Promise.reject(error).catch(abruptClose);
3745
- },
3746
- [Symbol.asyncIterator]() {
3747
- return this;
3748
- },
3749
- };
3750
- }
3751
- function asyncMapValue(value, callback) {
3752
- return new Promise(resolve => resolve(callback(value)));
3753
- }
3754
- function iteratorResult(value) {
3755
- return { value, done: false };
3756
- }
3757
-
3758
- function updateArgument(argumentNodes, variableDefinitionsMap, variableValues, argName, varName, type, value) {
3759
- argumentNodes[argName] = {
3760
- kind: graphql.Kind.ARGUMENT,
3761
- name: {
3762
- kind: graphql.Kind.NAME,
3763
- value: argName,
3764
- },
3765
- value: {
3766
- kind: graphql.Kind.VARIABLE,
3767
- name: {
3768
- kind: graphql.Kind.NAME,
3769
- value: varName,
3770
- },
3771
- },
3772
- };
3773
- variableDefinitionsMap[varName] = {
3774
- kind: graphql.Kind.VARIABLE_DEFINITION,
3775
- variable: {
3776
- kind: graphql.Kind.VARIABLE,
3777
- name: {
3778
- kind: graphql.Kind.NAME,
3779
- value: varName,
3780
- },
3781
- },
3782
- type: astFromType(type),
3783
- };
3784
- if (value !== undefined) {
3785
- variableValues[varName] = value;
3786
- return;
3787
- }
3788
- // including the variable in the map with value of `undefined`
3789
- // will actually be translated by graphql-js into `null`
3790
- // see https://github.com/graphql/graphql-js/issues/2533
3791
- if (varName in variableValues) {
3792
- delete variableValues[varName];
3793
- }
3794
- }
3795
- function createVariableNameGenerator(variableDefinitionMap) {
3796
- let varCounter = 0;
3797
- return (argName) => {
3798
- let varName;
3799
- do {
3800
- varName = `_v${(varCounter++).toString()}_${argName}`;
3801
- } while (varName in variableDefinitionMap);
3802
- return varName;
3803
- };
3804
- }
3805
-
3806
- function implementsAbstractType(schema, typeA, typeB) {
3807
- if (typeB == null || typeA == null) {
3808
- return false;
3809
- }
3810
- else if (typeA === typeB) {
3811
- return true;
3812
- }
3813
- else if (graphql.isCompositeType(typeA) && graphql.isCompositeType(typeB)) {
3814
- return graphql.doTypesOverlap(schema, typeA, typeB);
3815
- }
3816
- return false;
3817
- }
3818
-
3819
- function observableToAsyncIterable(observable) {
3820
- const pullQueue = [];
3821
- const pushQueue = [];
3822
- let listening = true;
3823
- const pushValue = (value) => {
3824
- if (pullQueue.length !== 0) {
3825
- // It is safe to use the ! operator here as we check the length.
3826
- pullQueue.shift()({ value, done: false });
3827
- }
3828
- else {
3829
- pushQueue.push({ value, done: false });
3830
- }
3831
- };
3832
- const pushError = (error) => {
3833
- if (pullQueue.length !== 0) {
3834
- // It is safe to use the ! operator here as we check the length.
3835
- pullQueue.shift()({ value: { errors: [error] }, done: false });
3836
- }
3837
- else {
3838
- pushQueue.push({ value: { errors: [error] }, done: false });
3839
- }
3840
- };
3841
- const pushDone = () => {
3842
- if (pullQueue.length !== 0) {
3843
- // It is safe to use the ! operator here as we check the length.
3844
- pullQueue.shift()({ done: true });
3845
- }
3846
- else {
3847
- pushQueue.push({ done: true });
3848
- }
3849
- };
3850
- const pullValue = () => new Promise(resolve => {
3851
- if (pushQueue.length !== 0) {
3852
- const element = pushQueue.shift();
3853
- // either {value: {errors: [...]}} or {value: ...}
3854
- resolve(element);
3855
- }
3856
- else {
3857
- pullQueue.push(resolve);
3858
- }
3859
- });
3860
- const subscription = observable.subscribe({
3861
- next(value) {
3862
- pushValue(value);
3863
- },
3864
- error(err) {
3865
- pushError(err);
3866
- },
3867
- complete() {
3868
- pushDone();
3869
- },
3870
- });
3871
- const emptyQueue = () => {
3872
- if (listening) {
3873
- listening = false;
3874
- subscription.unsubscribe();
3875
- for (const resolve of pullQueue) {
3876
- resolve({ value: undefined, done: true });
3877
- }
3878
- pullQueue.length = 0;
3879
- pushQueue.length = 0;
3880
- }
3881
- };
3882
- return {
3883
- next() {
3884
- // return is a defined method, so it is safe to call it.
3885
- return listening ? pullValue() : this.return();
3886
- },
3887
- return() {
3888
- emptyQueue();
3889
- return Promise.resolve({ value: undefined, done: true });
3890
- },
3891
- throw(error) {
3892
- emptyQueue();
3893
- return Promise.reject(error);
3894
- },
3895
- [Symbol.asyncIterator]() {
3896
- return this;
3897
- },
3898
- };
3899
- }
3900
-
3901
- function getOperationASTFromDocument(documentNode, operationName) {
3902
- const doc = graphql.getOperationAST(documentNode, operationName);
3903
- if (!doc) {
3904
- throw new Error(`Cannot infer operation ${operationName || ''}`);
3905
- }
3906
- return doc;
3907
- }
3908
- const getOperationASTFromRequest = memoize1(function getOperationASTFromRequest(request) {
3909
- return getOperationASTFromDocument(request.document, request.operationName);
3910
- });
3911
-
3912
- // Taken from GraphQL-JS v16 for backwards compat
3913
- function collectFields(schema, fragments, variableValues, runtimeType, selectionSet, fields, visitedFragmentNames) {
3914
- for (const selection of selectionSet.selections) {
3915
- switch (selection.kind) {
3916
- case graphql.Kind.FIELD: {
3917
- if (!shouldIncludeNode(variableValues, selection)) {
3918
- continue;
3919
- }
3920
- const name = getFieldEntryKey(selection);
3921
- const fieldList = fields.get(name);
3922
- if (fieldList !== undefined) {
3923
- fieldList.push(selection);
3924
- }
3925
- else {
3926
- fields.set(name, [selection]);
3927
- }
3928
- break;
3929
- }
3930
- case graphql.Kind.INLINE_FRAGMENT: {
3931
- if (!shouldIncludeNode(variableValues, selection) ||
3932
- !doesFragmentConditionMatch(schema, selection, runtimeType)) {
3933
- continue;
3934
- }
3935
- collectFields(schema, fragments, variableValues, runtimeType, selection.selectionSet, fields, visitedFragmentNames);
3936
- break;
3937
- }
3938
- case graphql.Kind.FRAGMENT_SPREAD: {
3939
- const fragName = selection.name.value;
3940
- if (visitedFragmentNames.has(fragName) || !shouldIncludeNode(variableValues, selection)) {
3941
- continue;
3942
- }
3943
- visitedFragmentNames.add(fragName);
3944
- const fragment = fragments[fragName];
3945
- if (!fragment || !doesFragmentConditionMatch(schema, fragment, runtimeType)) {
3946
- continue;
3947
- }
3948
- collectFields(schema, fragments, variableValues, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);
3949
- break;
3950
- }
3951
- }
3952
- }
3953
- return fields;
3954
- }
3955
- /**
3956
- * Determines if a field should be included based on the `@include` and `@skip`
3957
- * directives, where `@skip` has higher precedence than `@include`.
3958
- */
3959
- function shouldIncludeNode(variableValues, node) {
3960
- const skip = graphql.getDirectiveValues(graphql.GraphQLSkipDirective, node, variableValues);
3961
- if ((skip === null || skip === void 0 ? void 0 : skip['if']) === true) {
3962
- return false;
3963
- }
3964
- const include = graphql.getDirectiveValues(graphql.GraphQLIncludeDirective, node, variableValues);
3965
- if ((include === null || include === void 0 ? void 0 : include['if']) === false) {
3966
- return false;
3967
- }
3968
- return true;
3969
- }
3970
- /**
3971
- * Determines if a fragment is applicable to the given type.
3972
- */
3973
- function doesFragmentConditionMatch(schema, fragment, type) {
3974
- const typeConditionNode = fragment.typeCondition;
3975
- if (!typeConditionNode) {
3976
- return true;
3977
- }
3978
- const conditionalType = graphql.typeFromAST(schema, typeConditionNode);
3979
- if (conditionalType === type) {
3980
- return true;
3981
- }
3982
- if (graphql.isAbstractType(conditionalType)) {
3983
- const possibleTypes = schema.getPossibleTypes(conditionalType);
3984
- return possibleTypes.includes(type);
3985
- }
3986
- return false;
3987
- }
3988
- /**
3989
- * Implements the logic to compute the key of a given field's entry
3990
- */
3991
- function getFieldEntryKey(node) {
3992
- return node.alias ? node.alias.value : node.name.value;
3993
- }
3994
- const collectSubFields = memoize5(function collectSubFields(schema, fragments, variableValues, type, fieldNodes) {
3995
- const subFieldNodes = new Map();
3996
- const visitedFragmentNames = new Set();
3997
- for (const fieldNode of fieldNodes) {
3998
- if (fieldNode.selectionSet) {
3999
- collectFields(schema, fragments, variableValues, type, fieldNode.selectionSet, subFieldNodes, visitedFragmentNames);
4000
- }
4001
- }
4002
- return subFieldNodes;
4003
- });
4004
-
4005
- function visitData(data, enter, leave) {
4006
- if (Array.isArray(data)) {
4007
- return data.map(value => visitData(value, enter, leave));
4008
- }
4009
- else if (typeof data === 'object') {
4010
- const newData = enter != null ? enter(data) : data;
4011
- if (newData != null) {
4012
- for (const key in newData) {
4013
- const value = newData[key];
4014
- Object.defineProperty(newData, key, {
4015
- value: visitData(value, enter, leave),
4016
- });
4017
- }
4018
- }
4019
- return leave != null ? leave(newData) : newData;
4020
- }
4021
- return data;
4022
- }
4023
- function visitErrors(errors, visitor) {
4024
- return errors.map(error => visitor(error));
4025
- }
4026
- function visitResult(result, request, schema, resultVisitorMap, errorVisitorMap) {
4027
- const fragments = request.document.definitions.reduce((acc, def) => {
4028
- if (def.kind === graphql.Kind.FRAGMENT_DEFINITION) {
4029
- acc[def.name.value] = def;
4030
- }
4031
- return acc;
4032
- }, {});
4033
- const variableValues = request.variables || {};
4034
- const errorInfo = {
4035
- segmentInfoMap: new Map(),
4036
- unpathedErrors: new Set(),
4037
- };
4038
- const data = result.data;
4039
- const errors = result.errors;
4040
- const visitingErrors = errors != null && errorVisitorMap != null;
4041
- const operationDocumentNode = getOperationASTFromRequest(request);
4042
- if (data != null && operationDocumentNode != null) {
4043
- result.data = visitRoot(data, operationDocumentNode, schema, fragments, variableValues, resultVisitorMap, visitingErrors ? errors : undefined, errorInfo);
4044
- }
4045
- if (errors != null && errorVisitorMap) {
4046
- result.errors = visitErrorsByType(errors, errorVisitorMap, errorInfo);
4047
- }
4048
- return result;
4049
- }
4050
- function visitErrorsByType(errors, errorVisitorMap, errorInfo) {
4051
- const segmentInfoMap = errorInfo.segmentInfoMap;
4052
- const unpathedErrors = errorInfo.unpathedErrors;
4053
- const unpathedErrorVisitor = errorVisitorMap['__unpathed'];
4054
- return errors.map(originalError => {
4055
- const pathSegmentsInfo = segmentInfoMap.get(originalError);
4056
- const newError = pathSegmentsInfo == null
4057
- ? originalError
4058
- : pathSegmentsInfo.reduceRight((acc, segmentInfo) => {
4059
- const typeName = segmentInfo.type.name;
4060
- const typeVisitorMap = errorVisitorMap[typeName];
4061
- if (typeVisitorMap == null) {
4062
- return acc;
4063
- }
4064
- const errorVisitor = typeVisitorMap[segmentInfo.fieldName];
4065
- return errorVisitor == null ? acc : errorVisitor(acc, segmentInfo.pathIndex);
4066
- }, originalError);
4067
- if (unpathedErrorVisitor && unpathedErrors.has(originalError)) {
4068
- return unpathedErrorVisitor(newError);
4069
- }
4070
- return newError;
4071
- });
4072
- }
4073
- function getOperationRootType(schema, operationDef) {
4074
- switch (operationDef.operation) {
4075
- case 'query':
4076
- return schema.getQueryType();
4077
- case 'mutation':
4078
- return schema.getMutationType();
4079
- case 'subscription':
4080
- return schema.getSubscriptionType();
4081
- }
4082
- }
4083
- function visitRoot(root, operation, schema, fragments, variableValues, resultVisitorMap, errors, errorInfo) {
4084
- const operationRootType = getOperationRootType(schema, operation);
4085
- const collectedFields = collectFields(schema, fragments, variableValues, operationRootType, operation.selectionSet, new Map(), new Set());
4086
- return visitObjectValue(root, operationRootType, collectedFields, schema, fragments, variableValues, resultVisitorMap, 0, errors, errorInfo);
4087
- }
4088
- function visitObjectValue(object, type, fieldNodeMap, schema, fragments, variableValues, resultVisitorMap, pathIndex, errors, errorInfo) {
4089
- var _a;
4090
- const fieldMap = type.getFields();
4091
- const typeVisitorMap = resultVisitorMap === null || resultVisitorMap === void 0 ? void 0 : resultVisitorMap[type.name];
4092
- const enterObject = typeVisitorMap === null || typeVisitorMap === void 0 ? void 0 : typeVisitorMap.__enter;
4093
- const newObject = enterObject != null ? enterObject(object) : object;
4094
- let sortedErrors;
4095
- let errorMap = null;
4096
- if (errors != null) {
4097
- sortedErrors = sortErrorsByPathSegment(errors, pathIndex);
4098
- errorMap = sortedErrors.errorMap;
4099
- for (const error of sortedErrors.unpathedErrors) {
4100
- errorInfo.unpathedErrors.add(error);
4101
- }
4102
- }
4103
- for (const [responseKey, subFieldNodes] of fieldNodeMap) {
4104
- const fieldName = subFieldNodes[0].name.value;
4105
- const fieldType = fieldName === '__typename' ? graphql.TypeNameMetaFieldDef.type : (_a = fieldMap[fieldName]) === null || _a === void 0 ? void 0 : _a.type;
4106
- const newPathIndex = pathIndex + 1;
4107
- let fieldErrors;
4108
- if (errorMap) {
4109
- fieldErrors = errorMap[responseKey];
4110
- if (fieldErrors != null) {
4111
- delete errorMap[responseKey];
4112
- }
4113
- addPathSegmentInfo(type, fieldName, newPathIndex, fieldErrors, errorInfo);
4114
- }
4115
- const newValue = visitFieldValue(object[responseKey], fieldType, subFieldNodes, schema, fragments, variableValues, resultVisitorMap, newPathIndex, fieldErrors, errorInfo);
4116
- updateObject(newObject, responseKey, newValue, typeVisitorMap, fieldName);
4117
- }
4118
- const oldTypename = newObject.__typename;
4119
- if (oldTypename != null) {
4120
- updateObject(newObject, '__typename', oldTypename, typeVisitorMap, '__typename');
4121
- }
4122
- if (errorMap) {
4123
- for (const errorsKey in errorMap) {
4124
- const errors = errorMap[errorsKey];
4125
- for (const error of errors) {
4126
- errorInfo.unpathedErrors.add(error);
4127
- }
4128
- }
4129
- }
4130
- const leaveObject = typeVisitorMap === null || typeVisitorMap === void 0 ? void 0 : typeVisitorMap.__leave;
4131
- return leaveObject != null ? leaveObject(newObject) : newObject;
4132
- }
4133
- function updateObject(object, responseKey, newValue, typeVisitorMap, fieldName) {
4134
- if (typeVisitorMap == null) {
4135
- object[responseKey] = newValue;
4136
- return;
4137
- }
4138
- const fieldVisitor = typeVisitorMap[fieldName];
4139
- if (fieldVisitor == null) {
4140
- object[responseKey] = newValue;
4141
- return;
4142
- }
4143
- const visitedValue = fieldVisitor(newValue);
4144
- if (visitedValue === undefined) {
4145
- delete object[responseKey];
4146
- return;
4147
- }
4148
- object[responseKey] = visitedValue;
4149
- }
4150
- function visitListValue(list, returnType, fieldNodes, schema, fragments, variableValues, resultVisitorMap, pathIndex, errors, errorInfo) {
4151
- return list.map(listMember => visitFieldValue(listMember, returnType, fieldNodes, schema, fragments, variableValues, resultVisitorMap, pathIndex + 1, errors, errorInfo));
4152
- }
4153
- function visitFieldValue(value, returnType, fieldNodes, schema, fragments, variableValues, resultVisitorMap, pathIndex, errors = [], errorInfo) {
4154
- if (value == null) {
4155
- return value;
4156
- }
4157
- const nullableType = graphql.getNullableType(returnType);
4158
- if (graphql.isListType(nullableType)) {
4159
- return visitListValue(value, nullableType.ofType, fieldNodes, schema, fragments, variableValues, resultVisitorMap, pathIndex, errors, errorInfo);
4160
- }
4161
- else if (graphql.isAbstractType(nullableType)) {
4162
- const finalType = schema.getType(value.__typename);
4163
- const collectedFields = collectSubFields(schema, fragments, variableValues, finalType, fieldNodes);
4164
- return visitObjectValue(value, finalType, collectedFields, schema, fragments, variableValues, resultVisitorMap, pathIndex, errors, errorInfo);
4165
- }
4166
- else if (graphql.isObjectType(nullableType)) {
4167
- const collectedFields = collectSubFields(schema, fragments, variableValues, nullableType, fieldNodes);
4168
- return visitObjectValue(value, nullableType, collectedFields, schema, fragments, variableValues, resultVisitorMap, pathIndex, errors, errorInfo);
4169
- }
4170
- const typeVisitorMap = resultVisitorMap === null || resultVisitorMap === void 0 ? void 0 : resultVisitorMap[nullableType.name];
4171
- if (typeVisitorMap == null) {
4172
- return value;
4173
- }
4174
- const visitedValue = typeVisitorMap(value);
4175
- return visitedValue === undefined ? value : visitedValue;
4176
- }
4177
- function sortErrorsByPathSegment(errors, pathIndex) {
4178
- var _a;
4179
- const errorMap = Object.create(null);
4180
- const unpathedErrors = new Set();
4181
- for (const error of errors) {
4182
- const pathSegment = (_a = error.path) === null || _a === void 0 ? void 0 : _a[pathIndex];
4183
- if (pathSegment == null) {
4184
- unpathedErrors.add(error);
4185
- continue;
4186
- }
4187
- if (pathSegment in errorMap) {
4188
- errorMap[pathSegment].push(error);
4189
- }
4190
- else {
4191
- errorMap[pathSegment] = [error];
4192
- }
4193
- }
4194
- return {
4195
- errorMap,
4196
- unpathedErrors,
4197
- };
4198
- }
4199
- function addPathSegmentInfo(type, fieldName, pathIndex, errors = [], errorInfo) {
4200
- for (const error of errors) {
4201
- const segmentInfo = {
4202
- type,
4203
- fieldName,
4204
- pathIndex,
4205
- };
4206
- const pathSegmentsInfo = errorInfo.segmentInfoMap.get(error);
4207
- if (pathSegmentsInfo == null) {
4208
- errorInfo.segmentInfoMap.set(error, [segmentInfo]);
4209
- }
4210
- else {
4211
- pathSegmentsInfo.push(segmentInfo);
4212
- }
4213
- }
4214
- }
4215
-
4216
- function valueMatchesCriteria(value, criteria) {
4217
- if (value == null) {
4218
- return value === criteria;
4219
- }
4220
- else if (Array.isArray(value)) {
4221
- return Array.isArray(criteria) && value.every((val, index) => valueMatchesCriteria(val, criteria[index]));
4222
- }
4223
- else if (typeof value === 'object') {
4224
- return (typeof criteria === 'object' &&
4225
- criteria &&
4226
- Object.keys(criteria).every(propertyName => valueMatchesCriteria(value[propertyName], criteria[propertyName])));
4227
- }
4228
- else if (criteria instanceof RegExp) {
4229
- return criteria.test(value);
4230
- }
4231
- return value === criteria;
4232
- }
4233
-
4234
- function isAsyncIterable(value) {
4235
- return (typeof value === 'object' &&
4236
- value != null &&
4237
- Symbol.asyncIterator in value &&
4238
- typeof value[Symbol.asyncIterator] === 'function');
4239
- }
4240
-
4241
- function isDocumentNode(object) {
4242
- return object && typeof object === 'object' && 'kind' in object && object.kind === graphql.Kind.DOCUMENT;
4243
- }
4244
-
4245
- async function defaultAsyncIteratorReturn(value) {
4246
- return { value, done: true };
4247
- }
4248
- const proxyMethodFactory = memoize2(function proxyMethodFactory(target, targetMethod) {
4249
- return function proxyMethod(...args) {
4250
- return Reflect.apply(targetMethod, target, args);
4251
- };
4252
- });
4253
- function getAsyncIteratorWithCancel(asyncIterator, onCancel) {
4254
- return new Proxy(asyncIterator, {
4255
- has(asyncIterator, prop) {
4256
- if (prop === 'return') {
4257
- return true;
4258
- }
4259
- return Reflect.has(asyncIterator, prop);
4260
- },
4261
- get(asyncIterator, prop, receiver) {
4262
- const existingPropValue = Reflect.get(asyncIterator, prop, receiver);
4263
- if (prop === 'return') {
4264
- const existingReturn = existingPropValue || defaultAsyncIteratorReturn;
4265
- return async function returnWithCancel(value) {
4266
- const returnValue = await onCancel(value);
4267
- return Reflect.apply(existingReturn, asyncIterator, [returnValue]);
4268
- };
4269
- }
4270
- else if (typeof existingPropValue === 'function') {
4271
- return proxyMethodFactory(asyncIterator, existingPropValue);
4272
- }
4273
- return existingPropValue;
4274
- },
4275
- });
4276
- }
4277
- function getAsyncIterableWithCancel(asyncIterable, onCancel) {
4278
- return new Proxy(asyncIterable, {
4279
- get(asyncIterable, prop, receiver) {
4280
- const existingPropValue = Reflect.get(asyncIterable, prop, receiver);
4281
- if (Symbol.asyncIterator === prop) {
4282
- return function asyncIteratorFactory() {
4283
- const asyncIterator = Reflect.apply(existingPropValue, asyncIterable, []);
4284
- return getAsyncIteratorWithCancel(asyncIterator, onCancel);
4285
- };
4286
- }
4287
- else if (typeof existingPropValue === 'function') {
4288
- return proxyMethodFactory(asyncIterable, existingPropValue);
4289
- }
4290
- return existingPropValue;
4291
- },
4292
- });
4293
- }
4294
-
4295
- function buildFixedSchema(schema, options) {
4296
- const document = getDocumentNodeFromSchema(schema);
4297
- return graphql.buildASTSchema(document, {
4298
- ...(options || {}),
4299
- });
4300
- }
4301
- function fixSchemaAst(schema, options) {
4302
- // eslint-disable-next-line no-undef-init
4303
- let schemaWithValidAst = undefined;
4304
- if (!schema.astNode || !schema.extensionASTNodes) {
4305
- schemaWithValidAst = buildFixedSchema(schema, options);
4306
- }
4307
- if (!schema.astNode && (schemaWithValidAst === null || schemaWithValidAst === void 0 ? void 0 : schemaWithValidAst.astNode)) {
4308
- schema.astNode = schemaWithValidAst.astNode;
4309
- }
4310
- if (!schema.extensionASTNodes && (schemaWithValidAst === null || schemaWithValidAst === void 0 ? void 0 : schemaWithValidAst.astNode)) {
4311
- schema.extensionASTNodes = schemaWithValidAst.extensionASTNodes;
4312
- }
4313
- return schema;
4314
- }
4315
-
4316
- exports.addTypes = addTypes;
4317
- exports.appendObjectFields = appendObjectFields;
4318
- exports.asArray = asArray;
4319
- exports.assertSome = assertSome;
4320
- exports.astFromArg = astFromArg;
4321
- exports.astFromDirective = astFromDirective;
4322
- exports.astFromEnumType = astFromEnumType;
4323
- exports.astFromEnumValue = astFromEnumValue;
4324
- exports.astFromField = astFromField;
4325
- exports.astFromInputField = astFromInputField;
4326
- exports.astFromInputObjectType = astFromInputObjectType;
4327
- exports.astFromInterfaceType = astFromInterfaceType;
4328
- exports.astFromObjectType = astFromObjectType;
4329
- exports.astFromScalarType = astFromScalarType;
4330
- exports.astFromSchema = astFromSchema;
4331
- exports.astFromUnionType = astFromUnionType;
4332
- exports.astFromValueUntyped = astFromValueUntyped;
4333
- exports.buildOperationNodeForField = buildOperationNodeForField;
4334
- exports.checkValidationErrors = checkValidationErrors;
4335
- exports.collectComment = collectComment;
4336
- exports.collectFields = collectFields;
4337
- exports.collectSubFields = collectSubFields;
4338
- exports.compareNodes = compareNodes;
4339
- exports.compareStrings = compareStrings;
4340
- exports.correctASTNodes = correctASTNodes;
4341
- exports.createDefaultRules = createDefaultRules;
4342
- exports.createGraphQLError = createGraphQLError;
4343
- exports.createNamedStub = createNamedStub;
4344
- exports.createStub = createStub;
4345
- exports.createVariableNameGenerator = createVariableNameGenerator;
4346
- exports.dedentBlockStringValue = dedentBlockStringValue;
4347
- exports.filterSchema = filterSchema;
4348
- exports.fixSchemaAst = fixSchemaAst;
4349
- exports.forEachDefaultValue = forEachDefaultValue;
4350
- exports.forEachField = forEachField;
4351
- exports.getArgumentValues = getArgumentValues;
4352
- exports.getAsyncIterableWithCancel = getAsyncIterableWithCancel;
4353
- exports.getAsyncIteratorWithCancel = getAsyncIteratorWithCancel;
4354
- exports.getBlockStringIndentation = getBlockStringIndentation;
4355
- exports.getBuiltInForStub = getBuiltInForStub;
4356
- exports.getComment = getComment;
4357
- exports.getDefinedRootType = getDefinedRootType;
4358
- exports.getDeprecatableDirectiveNodes = getDeprecatableDirectiveNodes;
4359
- exports.getDescription = getDescription;
4360
- exports.getDirective = getDirective;
4361
- exports.getDirectiveInExtensions = getDirectiveInExtensions;
4362
- exports.getDirectiveNodes = getDirectiveNodes;
4363
- exports.getDirectives = getDirectives;
4364
- exports.getDirectivesInExtensions = getDirectivesInExtensions;
4365
- exports.getDocumentNodeFromSchema = getDocumentNodeFromSchema;
4366
- exports.getFieldsWithDirectives = getFieldsWithDirectives;
4367
- exports.getImplementingTypes = getImplementingTypes;
4368
- exports.getLeadingCommentBlock = getLeadingCommentBlock;
4369
- exports.getOperationASTFromDocument = getOperationASTFromDocument;
4370
- exports.getOperationASTFromRequest = getOperationASTFromRequest;
4371
- exports.getResolversFromSchema = getResolversFromSchema;
4372
- exports.getResponseKeyFromInfo = getResponseKeyFromInfo;
4373
- exports.getRootTypeMap = getRootTypeMap;
4374
- exports.getRootTypeNames = getRootTypeNames;
4375
- exports.getRootTypes = getRootTypes;
4376
- exports.healSchema = healSchema;
4377
- exports.healTypes = healTypes;
4378
- exports.implementsAbstractType = implementsAbstractType;
4379
- exports.inspect = inspect;
4380
- exports.isAggregateError = isAggregateError;
4381
- exports.isAsyncIterable = isAsyncIterable;
4382
- exports.isDescribable = isDescribable;
4383
- exports.isDocumentNode = isDocumentNode;
4384
- exports.isDocumentString = isDocumentString;
4385
- exports.isNamedStub = isNamedStub;
4386
- exports.isSome = isSome;
4387
- exports.isValidPath = isValidPath;
4388
- exports.makeDeprecatedDirective = makeDeprecatedDirective;
4389
- exports.makeDirectiveNode = makeDirectiveNode;
4390
- exports.makeDirectiveNodes = makeDirectiveNodes;
4391
- exports.mapAsyncIterator = mapAsyncIterator;
4392
- exports.mapSchema = mapSchema;
4393
- exports.memoize1 = memoize1;
4394
- exports.memoize2 = memoize2;
4395
- exports.memoize2of4 = memoize2of4;
4396
- exports.memoize3 = memoize3;
4397
- exports.memoize4 = memoize4;
4398
- exports.memoize5 = memoize5;
4399
- exports.mergeDeep = mergeDeep;
4400
- exports.modifyObjectFields = modifyObjectFields;
4401
- exports.nodeToString = nodeToString;
4402
- exports.observableToAsyncIterable = observableToAsyncIterable;
4403
- exports.parseGraphQLJSON = parseGraphQLJSON;
4404
- exports.parseGraphQLSDL = parseGraphQLSDL;
4405
- exports.parseInputValue = parseInputValue;
4406
- exports.parseInputValueLiteral = parseInputValueLiteral;
4407
- exports.parseSelectionSet = parseSelectionSet;
4408
- exports.printComment = printComment;
4409
- exports.printSchemaWithDirectives = printSchemaWithDirectives;
4410
- exports.printWithComments = printWithComments;
4411
- exports.pruneSchema = pruneSchema;
4412
- exports.pushComment = pushComment;
4413
- exports.relocatedError = relocatedError;
4414
- exports.removeObjectFields = removeObjectFields;
4415
- exports.renameType = renameType;
4416
- exports.resetComments = resetComments;
4417
- exports.rewireTypes = rewireTypes;
4418
- exports.selectObjectFields = selectObjectFields;
4419
- exports.serializeInputValue = serializeInputValue;
4420
- exports.transformCommentsToDescriptions = transformCommentsToDescriptions;
4421
- exports.transformInputValue = transformInputValue;
4422
- exports.updateArgument = updateArgument;
4423
- exports.validateGraphQlDocuments = validateGraphQlDocuments;
4424
- exports.valueMatchesCriteria = valueMatchesCriteria;
4425
- exports.visitData = visitData;
4426
- exports.visitErrors = visitErrors;
4427
- exports.visitResult = visitResult;
4428
- exports.withCancel = getAsyncIterableWithCancel;