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