@graphql-tools/delegate 9.0.0-alpha-e2ab84c8.0 → 9.0.0-alpha-25204a2f.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 (61) hide show
  1. package/README.md +0 -2
  2. package/cjs/Subschema.js +22 -0
  3. package/cjs/Transformer.js +45 -0
  4. package/cjs/applySchemaTransforms.js +11 -0
  5. package/cjs/checkResultAndHandleErrors.js +77 -0
  6. package/cjs/createRequest.js +125 -0
  7. package/cjs/defaultMergedResolver.js +29 -0
  8. package/cjs/delegateToSchema.js +148 -0
  9. package/cjs/finalizeGatewayRequest.js +317 -0
  10. package/cjs/getDocumentMetadata.js +25 -0
  11. package/cjs/index.js +13 -0
  12. package/cjs/mergeFields.js +87 -0
  13. package/cjs/package.json +1 -0
  14. package/cjs/prepareGatewayDocument.js +311 -0
  15. package/cjs/resolveExternalValue.js +103 -0
  16. package/cjs/subschemaConfig.js +31 -0
  17. package/cjs/symbols.js +6 -0
  18. package/cjs/types.js +3 -0
  19. package/esm/Subschema.js +17 -0
  20. package/esm/Transformer.js +41 -0
  21. package/esm/applySchemaTransforms.js +7 -0
  22. package/esm/checkResultAndHandleErrors.js +72 -0
  23. package/esm/createRequest.js +120 -0
  24. package/esm/defaultMergedResolver.js +25 -0
  25. package/esm/delegateToSchema.js +143 -0
  26. package/esm/finalizeGatewayRequest.js +313 -0
  27. package/esm/getDocumentMetadata.js +21 -0
  28. package/esm/index.js +10 -0
  29. package/esm/mergeFields.js +79 -0
  30. package/esm/prepareGatewayDocument.js +307 -0
  31. package/esm/resolveExternalValue.js +99 -0
  32. package/esm/subschemaConfig.js +26 -0
  33. package/esm/symbols.js +3 -0
  34. package/esm/types.js +1 -0
  35. package/package.json +40 -18
  36. package/{Subschema.d.ts → typings/Subschema.d.ts} +7 -3
  37. package/{Transformer.d.ts → typings/Transformer.d.ts} +3 -3
  38. package/{applySchemaTransforms.d.ts → typings/applySchemaTransforms.d.ts} +2 -2
  39. package/typings/checkResultAndHandleErrors.d.ts +8 -0
  40. package/{createRequest.d.ts → typings/createRequest.d.ts} +1 -2
  41. package/{defaultMergedResolver.d.ts → typings/defaultMergedResolver.d.ts} +2 -4
  42. package/typings/delegateToSchema.d.ts +6 -0
  43. package/typings/finalizeGatewayRequest.d.ts +3 -0
  44. package/{getDocumentMetadata.d.ts → typings/getDocumentMetadata.d.ts} +0 -0
  45. package/typings/index.d.ts +10 -0
  46. package/typings/mergeFields.d.ts +8 -0
  47. package/{prepareGatewayDocument.d.ts → typings/prepareGatewayDocument.d.ts} +0 -0
  48. package/typings/resolveExternalValue.d.ts +3 -0
  49. package/{subschemaConfig.d.ts → typings/subschemaConfig.d.ts} +1 -1
  50. package/typings/symbols.d.ts +3 -0
  51. package/{types.d.ts → typings/types.d.ts} +21 -40
  52. package/delegateToSchema.d.ts +0 -9
  53. package/externalObjects.d.ts +0 -11
  54. package/externalValues.d.ts +0 -4
  55. package/finalizeGatewayRequest.d.ts +0 -3
  56. package/getMergedParent.d.ts +0 -9
  57. package/index.d.ts +0 -11
  58. package/index.js +0 -1624
  59. package/index.mjs +0 -1590
  60. package/mergeDataAndErrors.d.ts +0 -5
  61. package/symbols.d.ts +0 -7
package/index.js DELETED
@@ -1,1624 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- const graphql = require('graphql');
8
- const utils = require('@graphql-tools/utils');
9
- const DataLoader = _interopDefault(require('dataloader'));
10
- const valueOrPromise = require('value-or-promise');
11
- const batchExecute = require('@graphql-tools/batch-execute');
12
-
13
- function applySchemaTransforms(originalWrappingSchema, subschemaConfig, transformedSchema) {
14
- const schemaTransforms = subschemaConfig.transforms;
15
- if (schemaTransforms == null) {
16
- return originalWrappingSchema;
17
- }
18
- return schemaTransforms.reduce((schema, transform) => transform.transformSchema != null
19
- ? transform.transformSchema(schema, subschemaConfig, transformedSchema)
20
- : schema, originalWrappingSchema);
21
- }
22
-
23
- function isSubschema(value) {
24
- return Boolean(value.transformedSchema);
25
- }
26
- class Subschema {
27
- constructor(config) {
28
- var _a;
29
- this.schema = config.schema;
30
- this.executor = config.executor;
31
- this.batch = config.batch;
32
- this.batchingOptions = config.batchingOptions;
33
- this.createProxyingResolver = config.createProxyingResolver;
34
- this.transforms = (_a = config.transforms) !== null && _a !== void 0 ? _a : [];
35
- this.transformedSchema = applySchemaTransforms(this.schema, config);
36
- this.merge = config.merge;
37
- }
38
- }
39
-
40
- function getDocumentMetadata(document) {
41
- const operations = [];
42
- const fragments = [];
43
- const fragmentNames = new Set();
44
- for (let i = 0; i < document.definitions.length; i++) {
45
- const def = document.definitions[i];
46
- if (def.kind === graphql.Kind.FRAGMENT_DEFINITION) {
47
- fragments.push(def);
48
- fragmentNames.add(def.name.value);
49
- }
50
- else if (def.kind === graphql.Kind.OPERATION_DEFINITION) {
51
- operations.push(def);
52
- }
53
- }
54
- return {
55
- operations,
56
- fragments,
57
- fragmentNames,
58
- };
59
- }
60
-
61
- function prepareGatewayDocument(originalDocument, transformedSchema, returnType, infoSchema) {
62
- const wrappedConcreteTypesDocument = wrapConcreteTypes(returnType, transformedSchema, originalDocument);
63
- if (infoSchema == null) {
64
- return wrappedConcreteTypesDocument;
65
- }
66
- const { possibleTypesMap, reversePossibleTypesMap, interfaceExtensionsMap, fieldNodesByType, fieldNodesByField, dynamicSelectionSetsByField, } = getSchemaMetaData(infoSchema, transformedSchema);
67
- const { operations, fragments, fragmentNames } = getDocumentMetadata(wrappedConcreteTypesDocument);
68
- const { expandedFragments, fragmentReplacements } = getExpandedFragments(fragments, fragmentNames, possibleTypesMap);
69
- const typeInfo = new graphql.TypeInfo(transformedSchema);
70
- const expandedDocument = {
71
- kind: graphql.Kind.DOCUMENT,
72
- definitions: [...operations, ...fragments, ...expandedFragments],
73
- };
74
- const visitorKeyMap = {
75
- Document: ['definitions'],
76
- OperationDefinition: ['selectionSet'],
77
- SelectionSet: ['selections'],
78
- Field: ['selectionSet'],
79
- InlineFragment: ['selectionSet'],
80
- FragmentDefinition: ['selectionSet'],
81
- };
82
- return graphql.visit(expandedDocument, graphql.visitWithTypeInfo(typeInfo, {
83
- [graphql.Kind.SELECTION_SET]: node => visitSelectionSet(node, fragmentReplacements, transformedSchema, typeInfo, possibleTypesMap, reversePossibleTypesMap, interfaceExtensionsMap, fieldNodesByType, fieldNodesByField, dynamicSelectionSetsByField),
84
- }),
85
- // visitorKeys argument usage a la https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js
86
- // empty keys cannot be removed only because of typescript errors
87
- // will hopefully be fixed in future version of graphql-js to be optional
88
- visitorKeyMap);
89
- }
90
- function visitSelectionSet(node, fragmentReplacements, schema, typeInfo, possibleTypesMap, reversePossibleTypesMap, interfaceExtensionsMap, fieldNodesByType, fieldNodesByField, dynamicSelectionSetsByField) {
91
- var _a, _b;
92
- const newSelections = new Set();
93
- const maybeType = typeInfo.getParentType();
94
- if (maybeType != null) {
95
- const parentType = graphql.getNamedType(maybeType);
96
- const parentTypeName = parentType.name;
97
- const fieldNodes = fieldNodesByType[parentTypeName];
98
- if (fieldNodes) {
99
- for (const fieldNode of fieldNodes) {
100
- newSelections.add(fieldNode);
101
- }
102
- }
103
- const interfaceExtensions = interfaceExtensionsMap[parentType.name];
104
- const interfaceExtensionFields = [];
105
- for (const selection of node.selections) {
106
- if (selection.kind === graphql.Kind.INLINE_FRAGMENT) {
107
- if (selection.typeCondition != null) {
108
- const possibleTypes = possibleTypesMap[selection.typeCondition.name.value];
109
- if (possibleTypes == null) {
110
- newSelections.add(selection);
111
- continue;
112
- }
113
- for (const possibleTypeName of possibleTypes) {
114
- const maybePossibleType = schema.getType(possibleTypeName);
115
- if (maybePossibleType != null && utils.implementsAbstractType(schema, parentType, maybePossibleType)) {
116
- newSelections.add(generateInlineFragment(possibleTypeName, selection.selectionSet));
117
- }
118
- }
119
- }
120
- }
121
- else if (selection.kind === graphql.Kind.FRAGMENT_SPREAD) {
122
- const fragmentName = selection.name.value;
123
- if (!fragmentReplacements[fragmentName]) {
124
- newSelections.add(selection);
125
- continue;
126
- }
127
- for (const replacement of fragmentReplacements[fragmentName]) {
128
- const typeName = replacement.typeName;
129
- const maybeReplacementType = schema.getType(typeName);
130
- if (maybeReplacementType != null && utils.implementsAbstractType(schema, parentType, maybeType)) {
131
- newSelections.add({
132
- kind: graphql.Kind.FRAGMENT_SPREAD,
133
- name: {
134
- kind: graphql.Kind.NAME,
135
- value: replacement.fragmentName,
136
- },
137
- });
138
- }
139
- }
140
- }
141
- else {
142
- const fieldName = selection.name.value;
143
- const fieldNodes = (_a = fieldNodesByField[parentTypeName]) === null || _a === void 0 ? void 0 : _a[fieldName];
144
- if (fieldNodes != null) {
145
- for (const fieldNode of fieldNodes) {
146
- newSelections.add(fieldNode);
147
- }
148
- }
149
- const dynamicSelectionSets = (_b = dynamicSelectionSetsByField[parentTypeName]) === null || _b === void 0 ? void 0 : _b[fieldName];
150
- if (dynamicSelectionSets != null) {
151
- for (const selectionSetFn of dynamicSelectionSets) {
152
- const selectionSet = selectionSetFn(selection);
153
- if (selectionSet != null) {
154
- for (const selection of selectionSet.selections) {
155
- newSelections.add(selection);
156
- }
157
- }
158
- }
159
- }
160
- if (interfaceExtensions === null || interfaceExtensions === void 0 ? void 0 : interfaceExtensions[fieldName]) {
161
- interfaceExtensionFields.push(selection);
162
- }
163
- else {
164
- newSelections.add(selection);
165
- }
166
- }
167
- }
168
- if (reversePossibleTypesMap[parentType.name]) {
169
- newSelections.add({
170
- kind: graphql.Kind.FIELD,
171
- name: {
172
- kind: graphql.Kind.NAME,
173
- value: '__typename',
174
- },
175
- });
176
- }
177
- if (interfaceExtensionFields.length) {
178
- const possibleTypes = possibleTypesMap[parentType.name];
179
- if (possibleTypes != null) {
180
- for (const possibleType of possibleTypes) {
181
- newSelections.add(generateInlineFragment(possibleType, {
182
- kind: graphql.Kind.SELECTION_SET,
183
- selections: interfaceExtensionFields,
184
- }));
185
- }
186
- }
187
- }
188
- return {
189
- ...node,
190
- selections: Array.from(newSelections),
191
- };
192
- }
193
- return node;
194
- }
195
- function generateInlineFragment(typeName, selectionSet) {
196
- return {
197
- kind: graphql.Kind.INLINE_FRAGMENT,
198
- typeCondition: {
199
- kind: graphql.Kind.NAMED_TYPE,
200
- name: {
201
- kind: graphql.Kind.NAME,
202
- value: typeName,
203
- },
204
- },
205
- selectionSet,
206
- };
207
- }
208
- const getSchemaMetaData = utils.memoize2((sourceSchema, targetSchema) => {
209
- var _a, _b, _c, _d;
210
- const typeMap = sourceSchema.getTypeMap();
211
- const targetTypeMap = targetSchema.getTypeMap();
212
- const possibleTypesMap = Object.create(null);
213
- const interfaceExtensionsMap = Object.create(null);
214
- for (const typeName in typeMap) {
215
- const type = typeMap[typeName];
216
- if (graphql.isAbstractType(type)) {
217
- const targetType = targetTypeMap[typeName];
218
- if (graphql.isInterfaceType(type) && graphql.isInterfaceType(targetType)) {
219
- const targetTypeFields = targetType.getFields();
220
- const sourceTypeFields = type.getFields();
221
- const extensionFields = Object.create(null);
222
- let isExtensionFieldsEmpty = true;
223
- for (const fieldName in sourceTypeFields) {
224
- if (!targetTypeFields[fieldName]) {
225
- extensionFields[fieldName] = true;
226
- isExtensionFieldsEmpty = false;
227
- }
228
- }
229
- if (!isExtensionFieldsEmpty) {
230
- interfaceExtensionsMap[typeName] = extensionFields;
231
- }
232
- }
233
- if (interfaceExtensionsMap[typeName] || !graphql.isAbstractType(targetType)) {
234
- const implementations = sourceSchema.getPossibleTypes(type);
235
- possibleTypesMap[typeName] = [];
236
- for (const impl of implementations) {
237
- if (targetTypeMap[impl.name]) {
238
- possibleTypesMap[typeName].push(impl.name);
239
- }
240
- }
241
- }
242
- }
243
- }
244
- const stitchingInfo = (_a = sourceSchema.extensions) === null || _a === void 0 ? void 0 : _a['stitchingInfo'];
245
- return {
246
- possibleTypesMap,
247
- reversePossibleTypesMap: reversePossibleTypesMap(possibleTypesMap),
248
- interfaceExtensionsMap,
249
- fieldNodesByType: (_b = stitchingInfo === null || stitchingInfo === void 0 ? void 0 : stitchingInfo.fieldNodesByType) !== null && _b !== void 0 ? _b : {},
250
- fieldNodesByField: (_c = stitchingInfo === null || stitchingInfo === void 0 ? void 0 : stitchingInfo.fieldNodesByField) !== null && _c !== void 0 ? _c : {},
251
- dynamicSelectionSetsByField: (_d = stitchingInfo === null || stitchingInfo === void 0 ? void 0 : stitchingInfo.dynamicSelectionSetsByField) !== null && _d !== void 0 ? _d : {},
252
- };
253
- });
254
- function reversePossibleTypesMap(possibleTypesMap) {
255
- const result = Object.create(null);
256
- for (const typeName in possibleTypesMap) {
257
- const toTypeNames = possibleTypesMap[typeName];
258
- for (const toTypeName of toTypeNames) {
259
- if (!result[toTypeName]) {
260
- result[toTypeName] = [];
261
- }
262
- result[toTypeName].push(typeName);
263
- }
264
- }
265
- return result;
266
- }
267
- function getExpandedFragments(fragments, fragmentNames, possibleTypesMap) {
268
- let fragmentCounter = 0;
269
- function generateFragmentName(typeName) {
270
- let fragmentName;
271
- do {
272
- fragmentName = `_${typeName}_Fragment${fragmentCounter.toString()}`;
273
- fragmentCounter++;
274
- } while (fragmentNames.has(fragmentName));
275
- return fragmentName;
276
- }
277
- const expandedFragments = [];
278
- const fragmentReplacements = Object.create(null);
279
- for (const fragment of fragments) {
280
- const possibleTypes = possibleTypesMap[fragment.typeCondition.name.value];
281
- if (possibleTypes != null) {
282
- const fragmentName = fragment.name.value;
283
- fragmentReplacements[fragmentName] = [];
284
- for (const possibleTypeName of possibleTypes) {
285
- const name = generateFragmentName(possibleTypeName);
286
- fragmentNames.add(name);
287
- expandedFragments.push({
288
- kind: graphql.Kind.FRAGMENT_DEFINITION,
289
- name: {
290
- kind: graphql.Kind.NAME,
291
- value: name,
292
- },
293
- typeCondition: {
294
- kind: graphql.Kind.NAMED_TYPE,
295
- name: {
296
- kind: graphql.Kind.NAME,
297
- value: possibleTypeName,
298
- },
299
- },
300
- selectionSet: fragment.selectionSet,
301
- });
302
- fragmentReplacements[fragmentName].push({
303
- fragmentName: name,
304
- typeName: possibleTypeName,
305
- });
306
- }
307
- }
308
- }
309
- return {
310
- expandedFragments,
311
- fragmentReplacements,
312
- };
313
- }
314
- function wrapConcreteTypes(returnType, targetSchema, document) {
315
- const namedType = graphql.getNamedType(returnType);
316
- if (!graphql.isObjectType(namedType)) {
317
- return document;
318
- }
319
- const rootTypeNames = utils.getRootTypeNames(targetSchema);
320
- const typeInfo = new graphql.TypeInfo(targetSchema);
321
- const visitorKeys = {
322
- Document: ['definitions'],
323
- OperationDefinition: ['selectionSet'],
324
- SelectionSet: ['selections'],
325
- InlineFragment: ['selectionSet'],
326
- FragmentDefinition: ['selectionSet'],
327
- };
328
- return graphql.visit(document, graphql.visitWithTypeInfo(typeInfo, {
329
- [graphql.Kind.FRAGMENT_DEFINITION]: (node) => {
330
- const typeName = node.typeCondition.name.value;
331
- if (!rootTypeNames.has(typeName)) {
332
- return false;
333
- }
334
- },
335
- [graphql.Kind.FIELD]: (node) => {
336
- const type = typeInfo.getType();
337
- if (type != null && graphql.isAbstractType(graphql.getNamedType(type))) {
338
- return {
339
- ...node,
340
- selectionSet: {
341
- kind: graphql.Kind.SELECTION_SET,
342
- selections: [
343
- {
344
- kind: graphql.Kind.INLINE_FRAGMENT,
345
- typeCondition: {
346
- kind: graphql.Kind.NAMED_TYPE,
347
- name: {
348
- kind: graphql.Kind.NAME,
349
- value: namedType.name,
350
- },
351
- },
352
- selectionSet: node.selectionSet,
353
- },
354
- ],
355
- },
356
- };
357
- }
358
- },
359
- }),
360
- // visitorKeys argument usage a la https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js
361
- // empty keys cannot be removed only because of typescript errors
362
- // will hopefully be fixed in future version of graphql-js to be optional
363
- visitorKeys);
364
- }
365
-
366
- function finalizeGatewayDocument(targetSchema, fragments, operations) {
367
- var _a;
368
- let usedVariables = [];
369
- let usedFragments = [];
370
- const newOperations = [];
371
- let newFragments = [];
372
- const validFragments = [];
373
- const validFragmentsWithType = Object.create(null);
374
- for (const fragment of fragments) {
375
- const typeName = fragment.typeCondition.name.value;
376
- const type = targetSchema.getType(typeName);
377
- if (type != null) {
378
- validFragments.push(fragment);
379
- validFragmentsWithType[fragment.name.value] = type;
380
- }
381
- }
382
- let fragmentSet = Object.create(null);
383
- for (const operation of operations) {
384
- const type = utils.getDefinedRootType(targetSchema, operation.operation);
385
- const { selectionSet, usedFragments: operationUsedFragments, usedVariables: operationUsedVariables, } = finalizeSelectionSet(targetSchema, type, validFragmentsWithType, operation.selectionSet);
386
- usedFragments = union(usedFragments, operationUsedFragments);
387
- const { usedVariables: collectedUsedVariables, newFragments: collectedNewFragments, fragmentSet: collectedFragmentSet, } = collectFragmentVariables(targetSchema, fragmentSet, validFragments, validFragmentsWithType, usedFragments);
388
- const operationOrFragmentVariables = union(operationUsedVariables, collectedUsedVariables);
389
- usedVariables = union(usedVariables, operationOrFragmentVariables);
390
- newFragments = collectedNewFragments;
391
- fragmentSet = collectedFragmentSet;
392
- const variableDefinitions = ((_a = operation.variableDefinitions) !== null && _a !== void 0 ? _a : []).filter((variable) => operationOrFragmentVariables.indexOf(variable.variable.name.value) !== -1);
393
- newOperations.push({
394
- kind: graphql.Kind.OPERATION_DEFINITION,
395
- operation: operation.operation,
396
- name: operation.name,
397
- directives: operation.directives,
398
- variableDefinitions,
399
- selectionSet,
400
- });
401
- }
402
- return {
403
- usedVariables,
404
- newDocument: {
405
- kind: graphql.Kind.DOCUMENT,
406
- definitions: [...newOperations, ...newFragments],
407
- },
408
- };
409
- }
410
- function finalizeGatewayRequest(originalRequest, delegationContext) {
411
- let { document, variables } = originalRequest;
412
- let { operations, fragments } = getDocumentMetadata(document);
413
- const { targetSchema, args } = delegationContext;
414
- if (args) {
415
- const requestWithNewVariables = addVariablesToRootFields(targetSchema, operations, args);
416
- operations = requestWithNewVariables.newOperations;
417
- variables = Object.assign({}, variables !== null && variables !== void 0 ? variables : {}, requestWithNewVariables.newVariables);
418
- }
419
- const { usedVariables, newDocument } = finalizeGatewayDocument(targetSchema, fragments, operations);
420
- const newVariables = {};
421
- if (variables != null) {
422
- for (const variableName of usedVariables) {
423
- const variableValue = variables[variableName];
424
- if (variableValue !== undefined) {
425
- newVariables[variableName] = variableValue;
426
- }
427
- }
428
- }
429
- return {
430
- ...originalRequest,
431
- document: newDocument,
432
- variables: newVariables,
433
- };
434
- }
435
- function addVariablesToRootFields(targetSchema, operations, args) {
436
- const newVariables = Object.create(null);
437
- const newOperations = operations.map((operation) => {
438
- var _a, _b;
439
- const variableDefinitionMap = ((_a = operation.variableDefinitions) !== null && _a !== void 0 ? _a : []).reduce((prev, def) => ({
440
- ...prev,
441
- [def.variable.name.value]: def,
442
- }), {});
443
- const type = utils.getDefinedRootType(targetSchema, operation.operation);
444
- const newSelectionSet = [];
445
- for (const selection of operation.selectionSet.selections) {
446
- if (selection.kind === graphql.Kind.FIELD) {
447
- const argumentNodes = (_b = selection.arguments) !== null && _b !== void 0 ? _b : [];
448
- const argumentNodeMap = argumentNodes.reduce((prev, argument) => ({
449
- ...prev,
450
- [argument.name.value]: argument,
451
- }), {});
452
- const targetField = type.getFields()[selection.name.value];
453
- // excludes __typename
454
- if (targetField != null) {
455
- updateArguments(targetField, argumentNodeMap, variableDefinitionMap, newVariables, args);
456
- }
457
- newSelectionSet.push({
458
- ...selection,
459
- arguments: Object.values(argumentNodeMap),
460
- });
461
- }
462
- else {
463
- newSelectionSet.push(selection);
464
- }
465
- }
466
- return {
467
- ...operation,
468
- variableDefinitions: Object.values(variableDefinitionMap),
469
- selectionSet: {
470
- kind: graphql.Kind.SELECTION_SET,
471
- selections: newSelectionSet,
472
- },
473
- };
474
- });
475
- return {
476
- newOperations,
477
- newVariables,
478
- };
479
- }
480
- function updateArguments(targetField, argumentNodeMap, variableDefinitionMap, variableValues, newArgs) {
481
- const generateVariableName = utils.createVariableNameGenerator(variableDefinitionMap);
482
- for (const argument of targetField.args) {
483
- const argName = argument.name;
484
- const argType = argument.type;
485
- if (argName in newArgs) {
486
- utils.updateArgument(argumentNodeMap, variableDefinitionMap, variableValues, argName, generateVariableName(argName), argType, utils.serializeInputValue(argType, newArgs[argName]));
487
- }
488
- }
489
- }
490
- function collectFragmentVariables(targetSchema, fragmentSet, validFragments, validFragmentsWithType, usedFragments) {
491
- let remainingFragments = usedFragments.slice();
492
- let usedVariables = [];
493
- const newFragments = [];
494
- while (remainingFragments.length !== 0) {
495
- const nextFragmentName = remainingFragments.pop();
496
- const fragment = validFragments.find(fr => fr.name.value === nextFragmentName);
497
- if (fragment != null) {
498
- const name = nextFragmentName;
499
- const typeName = fragment.typeCondition.name.value;
500
- const type = targetSchema.getType(typeName);
501
- if (type == null) {
502
- throw new Error(`Fragment reference type "${typeName}", but the type is not contained within the target schema.`);
503
- }
504
- const { selectionSet, usedFragments: fragmentUsedFragments, usedVariables: fragmentUsedVariables, } = finalizeSelectionSet(targetSchema, type, validFragmentsWithType, fragment.selectionSet);
505
- remainingFragments = union(remainingFragments, fragmentUsedFragments);
506
- usedVariables = union(usedVariables, fragmentUsedVariables);
507
- if (name && !(name in fragmentSet)) {
508
- fragmentSet[name] = true;
509
- newFragments.push({
510
- kind: graphql.Kind.FRAGMENT_DEFINITION,
511
- name: {
512
- kind: graphql.Kind.NAME,
513
- value: name,
514
- },
515
- typeCondition: fragment.typeCondition,
516
- selectionSet,
517
- });
518
- }
519
- }
520
- }
521
- return {
522
- usedVariables,
523
- newFragments,
524
- fragmentSet,
525
- };
526
- }
527
- const filteredSelectionSetVisitorKeys = {
528
- SelectionSet: ['selections'],
529
- Field: ['selectionSet'],
530
- InlineFragment: ['selectionSet'],
531
- FragmentDefinition: ['selectionSet'],
532
- };
533
- const variablesVisitorKeys = {
534
- SelectionSet: ['selections'],
535
- Field: ['arguments', 'directives', 'selectionSet'],
536
- Argument: ['value'],
537
- InlineFragment: ['directives', 'selectionSet'],
538
- FragmentSpread: ['directives'],
539
- FragmentDefinition: ['selectionSet'],
540
- ObjectValue: ['fields'],
541
- ObjectField: ['name', 'value'],
542
- Directive: ['arguments'],
543
- ListValue: ['values'],
544
- };
545
- function finalizeSelectionSet(schema, type, validFragments, selectionSet) {
546
- const usedFragments = [];
547
- const usedVariables = [];
548
- const typeInfo = graphql.versionInfo.major < 16 ? new graphql.TypeInfo(schema, undefined, type) : new graphql.TypeInfo(schema, type);
549
- const filteredSelectionSet = graphql.visit(selectionSet, graphql.visitWithTypeInfo(typeInfo, {
550
- [graphql.Kind.FIELD]: {
551
- enter: node => {
552
- const parentType = typeInfo.getParentType();
553
- if (graphql.isObjectType(parentType) || graphql.isInterfaceType(parentType)) {
554
- const fields = parentType.getFields();
555
- const field = node.name.value === '__typename' ? graphql.TypeNameMetaFieldDef : fields[node.name.value];
556
- if (!field) {
557
- return null;
558
- }
559
- const args = field.args != null ? field.args : [];
560
- const argsMap = Object.create(null);
561
- for (const arg of args) {
562
- argsMap[arg.name] = arg;
563
- }
564
- if (node.arguments != null) {
565
- const newArgs = [];
566
- for (const arg of node.arguments) {
567
- if (arg.name.value in argsMap) {
568
- newArgs.push(arg);
569
- }
570
- }
571
- if (newArgs.length !== node.arguments.length) {
572
- return {
573
- ...node,
574
- arguments: newArgs,
575
- };
576
- }
577
- }
578
- }
579
- },
580
- leave: node => {
581
- const type = typeInfo.getType();
582
- if (type == null) {
583
- throw new Error(`No type was found for field node ${utils.inspect(node)}.`);
584
- }
585
- const namedType = graphql.getNamedType(type);
586
- if (!schema.getType(namedType.name) == null) {
587
- return null;
588
- }
589
- if (graphql.isObjectType(namedType) || graphql.isInterfaceType(namedType)) {
590
- const selections = node.selectionSet != null ? node.selectionSet.selections : null;
591
- if (selections == null || selections.length === 0) {
592
- return null;
593
- }
594
- }
595
- },
596
- },
597
- [graphql.Kind.FRAGMENT_SPREAD]: {
598
- enter: node => {
599
- if (!(node.name.value in validFragments)) {
600
- return null;
601
- }
602
- const parentType = typeInfo.getParentType();
603
- const innerType = validFragments[node.name.value];
604
- if (!utils.implementsAbstractType(schema, parentType, innerType)) {
605
- return null;
606
- }
607
- usedFragments.push(node.name.value);
608
- },
609
- },
610
- [graphql.Kind.INLINE_FRAGMENT]: {
611
- enter: node => {
612
- if (node.typeCondition != null) {
613
- const parentType = typeInfo.getParentType();
614
- const innerType = schema.getType(node.typeCondition.name.value);
615
- if (!utils.implementsAbstractType(schema, parentType, innerType)) {
616
- return null;
617
- }
618
- }
619
- },
620
- },
621
- [graphql.Kind.SELECTION_SET]: {
622
- leave: node => {
623
- const parentType = typeInfo.getParentType();
624
- if (parentType != null && graphql.isAbstractType(parentType)) {
625
- const selections = node.selections.concat([
626
- {
627
- kind: graphql.Kind.FIELD,
628
- name: {
629
- kind: graphql.Kind.NAME,
630
- value: '__typename',
631
- },
632
- },
633
- ]);
634
- return {
635
- ...node,
636
- selections,
637
- };
638
- }
639
- },
640
- },
641
- }),
642
- // visitorKeys argument usage a la https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js
643
- // empty keys cannot be removed only because of typescript errors
644
- // will hopefully be fixed in future version of graphql-js to be optional
645
- filteredSelectionSetVisitorKeys);
646
- graphql.visit(filteredSelectionSet, {
647
- [graphql.Kind.VARIABLE]: variableNode => {
648
- usedVariables.push(variableNode.name.value);
649
- },
650
- },
651
- // visitorKeys argument usage a la https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js
652
- // empty keys cannot be removed only because of typescript errors
653
- // will hopefully be fixed in future version of graphql-js to be optional
654
- variablesVisitorKeys);
655
- return {
656
- selectionSet: filteredSelectionSet,
657
- usedFragments,
658
- usedVariables,
659
- };
660
- }
661
- function union(...arrays) {
662
- const cache = Object.create(null);
663
- const result = [];
664
- for (const array of arrays) {
665
- for (const item of array) {
666
- if (!(item in cache)) {
667
- cache[item] = true;
668
- result.push(item);
669
- }
670
- }
671
- }
672
- return result;
673
- }
674
-
675
- class Transformer {
676
- constructor(context) {
677
- this.transformations = [];
678
- this.delegationContext = context;
679
- const transforms = context.transforms;
680
- const delegationTransforms = transforms.slice().reverse();
681
- for (const transform of delegationTransforms) {
682
- this.addTransform(transform, {});
683
- }
684
- }
685
- addTransform(transform, context = {}) {
686
- this.transformations.push({ transform, context });
687
- }
688
- transformRequest(originalRequest) {
689
- var _a;
690
- let request = {
691
- ...originalRequest,
692
- document: prepareGatewayDocument(originalRequest.document, this.delegationContext.transformedSchema, this.delegationContext.returnType, (_a = this.delegationContext.info) === null || _a === void 0 ? void 0 : _a.schema),
693
- };
694
- for (const transformation of this.transformations) {
695
- if (transformation.transform.transformRequest) {
696
- request = transformation.transform.transformRequest(request, this.delegationContext, transformation.context);
697
- }
698
- }
699
- return finalizeGatewayRequest(request, this.delegationContext);
700
- }
701
- transformResult(originalResult) {
702
- let result = originalResult;
703
- // from rigth to left
704
- for (let i = this.transformations.length - 1; i >= 0; i--) {
705
- const transformation = this.transformations[i];
706
- if (transformation.transform.transformResult) {
707
- result = transformation.transform.transformResult(result, this.delegationContext, transformation.context);
708
- }
709
- }
710
- return result;
711
- }
712
- }
713
-
714
- function getDelegatingOperation(parentType, schema) {
715
- if (parentType === schema.getMutationType()) {
716
- return 'mutation';
717
- }
718
- else if (parentType === schema.getSubscriptionType()) {
719
- return 'subscription';
720
- }
721
- return 'query';
722
- }
723
- function createRequestFromInfo({ info, rootValue, operationName, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, selectionSet, fieldNodes = info.fieldNodes, context, }) {
724
- return createRequest({
725
- sourceSchema: info.schema,
726
- sourceParentType: info.parentType,
727
- sourceFieldName: info.fieldName,
728
- fragments: info.fragments,
729
- variableDefinitions: info.operation.variableDefinitions,
730
- variableValues: info.variableValues,
731
- targetRootValue: rootValue,
732
- targetOperationName: operationName,
733
- targetOperation: operation,
734
- targetFieldName: fieldName,
735
- selectionSet,
736
- fieldNodes,
737
- context,
738
- info,
739
- });
740
- }
741
- function createRequest({ sourceSchema, sourceParentType, sourceFieldName, fragments, variableDefinitions, variableValues, targetRootValue, targetOperationName, targetOperation, targetFieldName, selectionSet, fieldNodes, context, info, }) {
742
- var _a, _b;
743
- let newSelectionSet;
744
- const argumentNodeMap = Object.create(null);
745
- if (selectionSet != null) {
746
- newSelectionSet = selectionSet;
747
- }
748
- else {
749
- const selections = [];
750
- for (const fieldNode of fieldNodes || []) {
751
- if (fieldNode.selectionSet) {
752
- for (const selection of fieldNode.selectionSet.selections) {
753
- selections.push(selection);
754
- }
755
- }
756
- }
757
- newSelectionSet = selections.length
758
- ? {
759
- kind: graphql.Kind.SELECTION_SET,
760
- selections,
761
- }
762
- : undefined;
763
- const args = (_a = fieldNodes === null || fieldNodes === void 0 ? void 0 : fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments;
764
- if (args) {
765
- for (const argNode of args) {
766
- argumentNodeMap[argNode.name.value] = argNode;
767
- }
768
- }
769
- }
770
- const newVariables = Object.create(null);
771
- const variableDefinitionMap = Object.create(null);
772
- if (sourceSchema != null && variableDefinitions != null) {
773
- for (const def of variableDefinitions) {
774
- const varName = def.variable.name.value;
775
- variableDefinitionMap[varName] = def;
776
- const varType = graphql.typeFromAST(sourceSchema, def.type);
777
- const serializedValue = utils.serializeInputValue(varType, variableValues === null || variableValues === void 0 ? void 0 : variableValues[varName]);
778
- if (serializedValue !== undefined) {
779
- newVariables[varName] = serializedValue;
780
- }
781
- }
782
- }
783
- if (sourceParentType != null && sourceFieldName != null) {
784
- updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, newVariables);
785
- }
786
- const rootFieldName = targetFieldName !== null && targetFieldName !== void 0 ? targetFieldName : (_b = fieldNodes === null || fieldNodes === void 0 ? void 0 : fieldNodes[0]) === null || _b === void 0 ? void 0 : _b.name.value;
787
- if (rootFieldName === undefined) {
788
- throw new Error(`Either "targetFieldName" or a non empty "fieldNodes" array must be provided.`);
789
- }
790
- const rootfieldNode = {
791
- kind: graphql.Kind.FIELD,
792
- arguments: Object.values(argumentNodeMap),
793
- name: {
794
- kind: graphql.Kind.NAME,
795
- value: rootFieldName,
796
- },
797
- selectionSet: newSelectionSet,
798
- };
799
- const operationName = targetOperationName
800
- ? {
801
- kind: graphql.Kind.NAME,
802
- value: targetOperationName,
803
- }
804
- : undefined;
805
- const operationDefinition = {
806
- kind: graphql.Kind.OPERATION_DEFINITION,
807
- name: operationName,
808
- operation: targetOperation,
809
- variableDefinitions: Object.values(variableDefinitionMap),
810
- selectionSet: {
811
- kind: graphql.Kind.SELECTION_SET,
812
- selections: [rootfieldNode],
813
- },
814
- };
815
- const definitions = [operationDefinition];
816
- if (fragments != null) {
817
- for (const fragmentName in fragments) {
818
- const fragment = fragments[fragmentName];
819
- definitions.push(fragment);
820
- }
821
- }
822
- const document = {
823
- kind: graphql.Kind.DOCUMENT,
824
- definitions,
825
- };
826
- return {
827
- document,
828
- variables: newVariables,
829
- rootValue: targetRootValue,
830
- operationName: targetOperationName,
831
- operationType: targetOperation,
832
- context,
833
- info,
834
- };
835
- }
836
- function updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, variableValues) {
837
- const generateVariableName = utils.createVariableNameGenerator(variableDefinitionMap);
838
- const sourceField = sourceParentType.getFields()[sourceFieldName];
839
- for (const argument of sourceField.args) {
840
- const argName = argument.name;
841
- const sourceArgType = argument.type;
842
- if (argumentNodeMap[argName] === undefined) {
843
- const defaultValue = argument.defaultValue;
844
- if (defaultValue !== undefined) {
845
- utils.updateArgument(argumentNodeMap, variableDefinitionMap, variableValues, argName, generateVariableName(argName), sourceArgType, utils.serializeInputValue(sourceArgType, defaultValue));
846
- }
847
- }
848
- }
849
- }
850
-
851
- const INITIAL_PATH_SYMBOL = Symbol('initialPath');
852
- const UNPATHED_ERRORS_SYMBOL = Symbol('unpathedErrors');
853
- const OBJECT_SUBSCHEMA_SYMBOL = Symbol('initialSubschema');
854
- const INITIAL_POSSIBLE_FIELDS = Symbol('initialPossibleFields');
855
- const INFO_SYMBOL = Symbol('info');
856
- const RESPONSE_KEY_SUBSCHEMA_MAP_SYMBOL = Symbol('subschemaMap');
857
-
858
- function isExternalObject(data) {
859
- return (data === null || data === void 0 ? void 0 : data[UNPATHED_ERRORS_SYMBOL]) !== undefined;
860
- }
861
- function annotateExternalObject(object, errors, initialPath, subschema, info) {
862
- var _a, _b, _c;
863
- if (isExternalObject(object)) {
864
- return object;
865
- }
866
- const schema = subschema instanceof Subschema ? subschema.transformedSchema : (_b = (_a = subschema) === null || _a === void 0 ? void 0 : _a.schema) !== null && _b !== void 0 ? _b : subschema;
867
- const initialPossibleFields = (_c = schema.getType(object.__typename)) === null || _c === void 0 ? void 0 : _c.getFields();
868
- Object.defineProperties(object, {
869
- [INITIAL_PATH_SYMBOL]: { value: initialPath },
870
- [OBJECT_SUBSCHEMA_SYMBOL]: { value: subschema },
871
- [INITIAL_POSSIBLE_FIELDS]: { value: initialPossibleFields },
872
- [INFO_SYMBOL]: { value: info },
873
- [RESPONSE_KEY_SUBSCHEMA_MAP_SYMBOL]: { value: Object.create(null) },
874
- [UNPATHED_ERRORS_SYMBOL]: { value: errors },
875
- });
876
- return object;
877
- }
878
- function getInitialPath(object) {
879
- return object[INITIAL_PATH_SYMBOL];
880
- }
881
- function getInitialPossibleFields(object) {
882
- return object[INITIAL_POSSIBLE_FIELDS];
883
- }
884
- function getInfo(object) {
885
- return object[INFO_SYMBOL];
886
- }
887
- function getUnpathedErrors(object) {
888
- return object[UNPATHED_ERRORS_SYMBOL];
889
- }
890
- function getObjectSubchema(object) {
891
- return object[OBJECT_SUBSCHEMA_SYMBOL];
892
- }
893
- function getSubschemaMap(object) {
894
- return object[RESPONSE_KEY_SUBSCHEMA_MAP_SYMBOL];
895
- }
896
- function getSubschema(object, responseKey) {
897
- var _a;
898
- return (_a = object[RESPONSE_KEY_SUBSCHEMA_MAP_SYMBOL][responseKey]) !== null && _a !== void 0 ? _a : object[OBJECT_SUBSCHEMA_SYMBOL];
899
- }
900
-
901
- function mergeDataAndErrors(data, errors = [], onLocatedError = (originalError) => originalError, index = 1) {
902
- var _a;
903
- if (data == null) {
904
- if (!errors.length) {
905
- return { data: null, unpathedErrors: [] };
906
- }
907
- if (errors.length === 1) {
908
- const error = onLocatedError(errors[0]);
909
- const newPath = error.path === undefined ? [] : error.path.slice(1);
910
- const newError = utils.relocatedError(error, newPath);
911
- return { data: newError, unpathedErrors: [] };
912
- }
913
- const newErrors = errors.map(error => onLocatedError(error));
914
- const firstError = newErrors[0];
915
- const newPath = firstError.path === undefined ? [] : firstError.path.slice(1);
916
- // We cast path as any for GraphQL.js 14 compat
917
- // locatedError path argument must be defined, but it is just forwarded to a constructor that allows a undefined value
918
- // https://github.com/graphql/graphql-js/blob/b4bff0ba9c15c9d7245dd68556e754c41f263289/src/error/locatedError.js#L25
919
- // https://github.com/graphql/graphql-js/blob/b4bff0ba9c15c9d7245dd68556e754c41f263289/src/error/GraphQLError.js#L19
920
- const newError = graphql.locatedError(new utils.AggregateError(newErrors), undefined, newPath);
921
- return { data: newError, unpathedErrors: [] };
922
- }
923
- if (!errors.length) {
924
- return { data, unpathedErrors: [] };
925
- }
926
- const unpathedErrors = [];
927
- const errorMap = new Map();
928
- for (const error of errors) {
929
- const pathSegment = (_a = error.path) === null || _a === void 0 ? void 0 : _a[index];
930
- if (pathSegment != null) {
931
- let pathSegmentErrors = errorMap.get(pathSegment);
932
- if (pathSegmentErrors === undefined) {
933
- pathSegmentErrors = [error];
934
- errorMap.set(pathSegment, pathSegmentErrors);
935
- }
936
- else {
937
- pathSegmentErrors.push(error);
938
- }
939
- }
940
- else {
941
- unpathedErrors.push(error);
942
- }
943
- }
944
- for (const [pathSegment, pathSegmentErrors] of errorMap) {
945
- if (data[pathSegment] !== undefined) {
946
- const { data: newData, unpathedErrors: newErrors } = mergeDataAndErrors(data[pathSegment], pathSegmentErrors, onLocatedError, index + 1);
947
- data[pathSegment] = newData;
948
- unpathedErrors.push(...newErrors);
949
- }
950
- else {
951
- unpathedErrors.push(...pathSegmentErrors);
952
- }
953
- }
954
- return { data, unpathedErrors };
955
- }
956
-
957
- function externalValueFromResult({ result, schema, info, context, fieldName = getFieldName(info), returnType = getReturnType(info), onLocatedError = (error) => error, }) {
958
- var _a, _b;
959
- const data = (_a = result.data) === null || _a === void 0 ? void 0 : _a[fieldName];
960
- const errors = (_b = result.errors) !== null && _b !== void 0 ? _b : [];
961
- const initialPath = info ? graphql.responsePathAsArray(info.path) : [];
962
- const { data: newData, unpathedErrors } = mergeDataAndErrors(data, errors, onLocatedError);
963
- return createExternalValue(newData, unpathedErrors, initialPath, schema, context, info, returnType);
964
- }
965
- function createExternalValue(data, unpathedErrors, initialPath, subschema, context, info, returnType = getReturnType(info)) {
966
- const type = graphql.getNullableType(returnType);
967
- if (data instanceof graphql.GraphQLError) {
968
- return utils.relocatedError(data, data.path ? initialPath.concat(data.path) : initialPath);
969
- }
970
- if (data instanceof Error) {
971
- return data;
972
- }
973
- if (data == null) {
974
- return reportUnpathedErrorsViaNull(unpathedErrors);
975
- }
976
- if ('parseValue' in type) {
977
- return type.parseValue(data);
978
- }
979
- else if (graphql.isCompositeType(type)) {
980
- return annotateExternalObject(data, unpathedErrors, initialPath, subschema, info);
981
- }
982
- else if (graphql.isListType(type)) {
983
- return createExternalList(type, data, unpathedErrors, initialPath, subschema, context, info);
984
- }
985
- }
986
- function createExternalList(type, list, unpathedErrors, initialPath, subschema, context, info) {
987
- return list.map(listMember => createExternalListMember(graphql.getNullableType(type.ofType), listMember, unpathedErrors, initialPath, subschema, context, info));
988
- }
989
- function createExternalListMember(type, listMember, unpathedErrors, initialPath, subschema, context, info) {
990
- if (listMember instanceof graphql.GraphQLError) {
991
- return utils.relocatedError(listMember, listMember.path ? initialPath.concat(listMember.path) : initialPath);
992
- }
993
- if (listMember instanceof Error) {
994
- return listMember;
995
- }
996
- if (listMember == null) {
997
- return reportUnpathedErrorsViaNull(unpathedErrors);
998
- }
999
- if ('parseValue' in type) {
1000
- return type.parseValue(listMember);
1001
- }
1002
- else if (graphql.isCompositeType(type)) {
1003
- return annotateExternalObject(listMember, unpathedErrors, initialPath, subschema, info);
1004
- }
1005
- else if (graphql.isListType(type)) {
1006
- return createExternalList(type, listMember, unpathedErrors, initialPath, subschema, context, info);
1007
- }
1008
- }
1009
- const reportedErrors = new WeakMap();
1010
- function reportUnpathedErrorsViaNull(unpathedErrors) {
1011
- if (unpathedErrors.length) {
1012
- const unreportedErrors = [];
1013
- for (const error of unpathedErrors) {
1014
- if (!reportedErrors.has(error)) {
1015
- unreportedErrors.push(error);
1016
- reportedErrors.set(error, true);
1017
- }
1018
- }
1019
- if (unreportedErrors.length) {
1020
- if (unreportedErrors.length === 1) {
1021
- return unreportedErrors[0];
1022
- }
1023
- const combinedError = new utils.AggregateError(unreportedErrors);
1024
- // We cast path as any for GraphQL.js 14 compat
1025
- // locatedError path argument must be defined, but it is just forwarded to a constructor that allows a undefined value
1026
- // https://github.com/graphql/graphql-js/blob/b4bff0ba9c15c9d7245dd68556e754c41f263289/src/error/locatedError.js#L25
1027
- // https://github.com/graphql/graphql-js/blob/b4bff0ba9c15c9d7245dd68556e754c41f263289/src/error/GraphQLError.js#L19
1028
- return graphql.locatedError(combinedError, undefined, unreportedErrors[0].path);
1029
- }
1030
- }
1031
- return null;
1032
- }
1033
- function getFieldName(info) {
1034
- if (info == null) {
1035
- throw new Error(`Data cannot be extracted from result without an explicit key or source schema.`);
1036
- }
1037
- return info.fieldName;
1038
- }
1039
- function getReturnType(info) {
1040
- if (info == null) {
1041
- throw new Error(`Return type cannot be inferred without a source schema.`);
1042
- }
1043
- return info.returnType;
1044
- }
1045
-
1046
- const getMergedTypeInfo = utils.memoize1(function getMergedTypeInfo(info) {
1047
- var _a;
1048
- const schema = info.schema;
1049
- const stitchingInfo = (_a = schema.extensions) === null || _a === void 0 ? void 0 : _a['stitchingInfo'];
1050
- if (stitchingInfo == null) {
1051
- return;
1052
- }
1053
- const parentTypeName = info.parentType.name;
1054
- const mergedTypeInfo = stitchingInfo.mergedTypes[parentTypeName];
1055
- if (mergedTypeInfo === undefined) {
1056
- return;
1057
- }
1058
- return mergedTypeInfo;
1059
- });
1060
- const loaders = new WeakMap();
1061
- async function getMergedParent(parent, context, info) {
1062
- const mergedTypeInfo = getMergedTypeInfo(info);
1063
- if (!mergedTypeInfo) {
1064
- return parent;
1065
- }
1066
- // In the stitching context, all subschemas are compiled Subschema objects rather than SubschemaConfig objects
1067
- const sourceSubschema = getObjectSubchema(parent);
1068
- let loader = loaders.get(parent);
1069
- if (loader === undefined) {
1070
- loader = new DataLoader(fieldNodeArrays => getMergedParentsFromFieldNodes(parent, context, info.schema, fieldNodeArrays, mergedTypeInfo, sourceSubschema));
1071
- loaders.set(parent, loader);
1072
- }
1073
- return loader.load(info.fieldNodes);
1074
- }
1075
- async function getMergedParentsFromFieldNodes(parent, context, gatewaySchema, fieldNodeArrays, mergedTypeInfo, sourceSubschema) {
1076
- const { requiredKeys, delegationMaps, stageMap } = buildDelegationPlan(mergedTypeInfo, gatewaySchema, sourceSubschema, ...fieldNodeArrays);
1077
- if (!delegationMaps.length) {
1078
- return Array(fieldNodeArrays.length).fill(parent);
1079
- }
1080
- const promises = [];
1081
- const parentInfo = getInfo(parent);
1082
- const type = gatewaySchema.getType(parent.__typename);
1083
- const parentPath = graphql.responsePathAsArray(parentInfo.path);
1084
- let promise = executeDelegationStage(delegationMaps[0], gatewaySchema, type, mergedTypeInfo, context, parent, parentInfo, parentPath);
1085
- promises.push(promise);
1086
- for (let i = 1, delegationStage = delegationMaps[i]; i < delegationMaps.length; i++) {
1087
- promise = promise.then(parent => executeDelegationStage(delegationStage, gatewaySchema, type, mergedTypeInfo, context, parent, parentInfo, parentPath));
1088
- promises.push(promise);
1089
- }
1090
- return fieldNodeArrays.map(fieldNodeArray => {
1091
- const fieldName = fieldNodeArray[0].name.value;
1092
- const keys = requiredKeys[fieldName];
1093
- if (keys === undefined) {
1094
- const delegationStage = stageMap[fieldName];
1095
- if (delegationStage !== undefined) {
1096
- return promises[delegationStage];
1097
- }
1098
- return Promise.resolve(parent);
1099
- }
1100
- return Promise.all(Array.from(keys.values()).map(fieldName => {
1101
- const delegationStage = stageMap[fieldName];
1102
- if (delegationStage !== undefined) {
1103
- return promises[delegationStage];
1104
- }
1105
- return Promise.resolve(parent);
1106
- })).then(() => parent);
1107
- });
1108
- }
1109
- function sortSubschemasByProxiability(mergedTypeInfo, sourceSubschemas, targetSubschemas, fieldNodes) {
1110
- // 1. calculate if possible to delegate to given subschema
1111
- const proxiableSubschemas = [];
1112
- const nonProxiableSubschemas = [];
1113
- for (const t of targetSubschemas) {
1114
- const selectionSet = mergedTypeInfo.selectionSets.get(t);
1115
- const fieldSelectionSets = mergedTypeInfo.fieldSelectionSets.get(t);
1116
- if (selectionSet != null && !subschemaTypesContainSelectionSet(mergedTypeInfo, sourceSubschemas, selectionSet)) {
1117
- nonProxiableSubschemas.push(t);
1118
- }
1119
- else {
1120
- if (fieldSelectionSets == null ||
1121
- fieldNodes.every(fieldNode => {
1122
- const fieldName = fieldNode.name.value;
1123
- const fieldSelectionSet = fieldSelectionSets[fieldName];
1124
- return (fieldSelectionSet == null ||
1125
- subschemaTypesContainSelectionSet(mergedTypeInfo, sourceSubschemas, fieldSelectionSet));
1126
- })) {
1127
- proxiableSubschemas.push(t);
1128
- }
1129
- else {
1130
- nonProxiableSubschemas.push(t);
1131
- }
1132
- }
1133
- }
1134
- return {
1135
- proxiableSubschemas,
1136
- nonProxiableSubschemas,
1137
- };
1138
- }
1139
- function calculateDelegationStage(mergedTypeInfo, sourceSubschemas, targetSubschemas, fieldNodes) {
1140
- const { proxiableSubschemas, nonProxiableSubschemas } = sortSubschemasByProxiability(mergedTypeInfo, sourceSubschemas, targetSubschemas, fieldNodes);
1141
- const { delegationMap, proxiableFieldNodes, unproxiableFieldNodes } = buildDelegationStage(mergedTypeInfo, fieldNodes, proxiableSubschemas);
1142
- return {
1143
- proxiableSubschemas,
1144
- nonProxiableSubschemas,
1145
- delegationMap,
1146
- proxiableFieldNodes,
1147
- unproxiableFieldNodes,
1148
- };
1149
- }
1150
- const buildDelegationPlan = utils.memoize4ofMany(function buildDelegationPlan(mergedTypeInfo, gatewaySchema, sourceSubschema, ...fieldNodeArrays) {
1151
- var _a, _b, _c;
1152
- const requiredKeys = Object.create(null);
1153
- const delegationMaps = [];
1154
- const stageMap = Object.create(null);
1155
- const stitchingInfo = (_a = gatewaySchema.extensions) === null || _a === void 0 ? void 0 : _a['stitchingInfo'];
1156
- if (stitchingInfo == null) {
1157
- return { requiredKeys, delegationMaps, stageMap };
1158
- }
1159
- const targetSubschemas = mergedTypeInfo.targetSubschemas.get(sourceSubschema);
1160
- if (targetSubschemas === undefined || targetSubschemas.length === 0) {
1161
- return { requiredKeys, delegationMaps, stageMap };
1162
- }
1163
- const parentTypeName = mergedTypeInfo.typeName;
1164
- const sourceSubschemaParentType = sourceSubschema.transformedSchema.getType(parentTypeName);
1165
- const sourceSubschemaFields = sourceSubschemaParentType.getFields();
1166
- const subschemaFields = mergedTypeInfo.subschemaFields;
1167
- const typeFieldNodes = (_b = stitchingInfo.fieldNodesByField) === null || _b === void 0 ? void 0 : _b[parentTypeName];
1168
- const fieldNodeSet = new Set();
1169
- const fieldNodesByType = (_c = stitchingInfo.fieldNodesByType) === null || _c === void 0 ? void 0 : _c[parentTypeName];
1170
- if (fieldNodesByType !== undefined) {
1171
- for (const fieldNode of fieldNodesByType) {
1172
- const fieldName = fieldNode.name.value;
1173
- if (!sourceSubschemaFields[fieldName]) {
1174
- const fieldName = fieldNode.name.value;
1175
- if (!sourceSubschemaFields[fieldName]) {
1176
- fieldNodeSet.add(fieldNode);
1177
- }
1178
- }
1179
- }
1180
- }
1181
- for (const fieldNodeArray of fieldNodeArrays) {
1182
- const fieldName = fieldNodeArray[0].name.value;
1183
- if (subschemaFields[fieldName] !== undefined) {
1184
- // merged subschema field
1185
- for (const fieldNode of fieldNodeArray) {
1186
- const fieldName = fieldNode.name.value;
1187
- if (!sourceSubschemaFields[fieldName]) {
1188
- fieldNodeSet.add(fieldNode);
1189
- }
1190
- }
1191
- }
1192
- else {
1193
- // gateway field
1194
- if (requiredKeys[fieldName] === undefined) {
1195
- requiredKeys[fieldName] = new Set();
1196
- }
1197
- }
1198
- const keyFieldNodes = new Set();
1199
- const fieldNodesByField = typeFieldNodes === null || typeFieldNodes === void 0 ? void 0 : typeFieldNodes[fieldName];
1200
- if (fieldNodesByField !== undefined) {
1201
- for (const fieldNode of fieldNodesByField) {
1202
- keyFieldNodes.add(fieldNode);
1203
- }
1204
- }
1205
- if (requiredKeys[fieldName] !== undefined) {
1206
- for (const fieldNode of keyFieldNodes.values()) {
1207
- requiredKeys[fieldName].add(fieldNode.name.value);
1208
- }
1209
- }
1210
- for (const fieldNode of keyFieldNodes) {
1211
- fieldNodeSet.add(fieldNode);
1212
- }
1213
- }
1214
- const fieldNodes = Array.from(fieldNodeSet);
1215
- let sourceSubschemas = [sourceSubschema];
1216
- let delegationStage = calculateDelegationStage(mergedTypeInfo, sourceSubschemas, targetSubschemas, fieldNodes);
1217
- let stageIndex = 0;
1218
- let delegationMap = delegationStage.delegationMap;
1219
- while (delegationMap.size) {
1220
- delegationMaps.push(delegationMap);
1221
- const { proxiableSubschemas, nonProxiableSubschemas, proxiableFieldNodes, unproxiableFieldNodes } = delegationStage;
1222
- sourceSubschemas = sourceSubschemas.concat(proxiableSubschemas);
1223
- for (const fieldNode of proxiableFieldNodes) {
1224
- stageMap[fieldNode.name.value] = stageIndex;
1225
- }
1226
- stageIndex++;
1227
- delegationStage = calculateDelegationStage(mergedTypeInfo, sourceSubschemas, nonProxiableSubschemas, unproxiableFieldNodes);
1228
- delegationMap = delegationStage.delegationMap;
1229
- }
1230
- return {
1231
- requiredKeys,
1232
- delegationMaps,
1233
- stageMap,
1234
- };
1235
- });
1236
- function buildDelegationStage(mergedTypeInfo, fieldNodes, proxiableSubschemas) {
1237
- const { uniqueFields, nonUniqueFields } = mergedTypeInfo;
1238
- const proxiableFieldNodes = [];
1239
- const unproxiableFieldNodes = [];
1240
- // 2. for each selection:
1241
- const delegationMap = new Map();
1242
- for (const fieldNode of fieldNodes) {
1243
- if (fieldNode.name.value === '__typename') {
1244
- continue;
1245
- }
1246
- // 2a. use uniqueFields map to assign fields to subschema if one of possible subschemas
1247
- const uniqueSubschema = uniqueFields[fieldNode.name.value];
1248
- if (uniqueSubschema != null) {
1249
- if (!proxiableSubschemas.includes(uniqueSubschema)) {
1250
- unproxiableFieldNodes.push(fieldNode);
1251
- continue;
1252
- }
1253
- const existingSubschema = delegationMap.get(uniqueSubschema);
1254
- if (existingSubschema != null) {
1255
- existingSubschema.push(fieldNode);
1256
- }
1257
- else {
1258
- delegationMap.set(uniqueSubschema, [fieldNode]);
1259
- }
1260
- proxiableFieldNodes.push(fieldNode);
1261
- continue;
1262
- }
1263
- // 2b. use nonUniqueFields to assign to a possible subschema,
1264
- // preferring one of the subschemas already targets of delegation
1265
- let nonUniqueSubschemas = nonUniqueFields[fieldNode.name.value];
1266
- if (nonUniqueSubschemas == null) {
1267
- unproxiableFieldNodes.push(fieldNode);
1268
- continue;
1269
- }
1270
- nonUniqueSubschemas = nonUniqueSubschemas.filter(s => proxiableSubschemas.includes(s));
1271
- if (!nonUniqueSubschemas.length) {
1272
- unproxiableFieldNodes.push(fieldNode);
1273
- continue;
1274
- }
1275
- const existingSubschema = nonUniqueSubschemas.find(s => delegationMap.has(s));
1276
- if (existingSubschema != null) {
1277
- // It is okay we previously explicitly check whether the map has the element.
1278
- delegationMap.get(existingSubschema).push(fieldNode);
1279
- }
1280
- else {
1281
- delegationMap.set(nonUniqueSubschemas[0], [fieldNode]);
1282
- }
1283
- proxiableFieldNodes.push(fieldNode);
1284
- }
1285
- return {
1286
- delegationMap,
1287
- proxiableFieldNodes,
1288
- unproxiableFieldNodes,
1289
- };
1290
- }
1291
- async function executeDelegationStage(delegationMap, schema, type, mergedTypeInfo, context, object, parentInfo, parentPath) {
1292
- const initialPath = getInitialPath(object);
1293
- const newSubschemaMap = getSubschemaMap(object);
1294
- const unpathedErrors = getUnpathedErrors(object);
1295
- await Promise.all([...delegationMap.entries()].map(async ([s, fieldNodes]) => {
1296
- var _a;
1297
- const resolver = mergedTypeInfo.resolvers.get(s);
1298
- if (resolver) {
1299
- const selectionSet = { kind: graphql.Kind.SELECTION_SET, selections: fieldNodes };
1300
- let source;
1301
- try {
1302
- source = await resolver(object, context, parentInfo, s, selectionSet);
1303
- }
1304
- catch (error) {
1305
- source = error;
1306
- }
1307
- if (source instanceof Error || source === null) {
1308
- const fieldNodes = utils.collectFields(schema, {}, {}, type, selectionSet, new Map(), new Set());
1309
- const nullResult = Object.create(null);
1310
- if (source instanceof graphql.GraphQLError && source.path) {
1311
- const basePath = parentPath.slice(initialPath.length);
1312
- for (const [responseKey] of fieldNodes) {
1313
- const tailPath = source.path.length === parentPath.length ? [responseKey] : source.path.slice(initialPath.length);
1314
- const newPath = basePath.concat(tailPath);
1315
- nullResult[responseKey] = utils.relocatedError(source, newPath);
1316
- }
1317
- }
1318
- else if (source instanceof Error) {
1319
- const basePath = parentPath.slice(initialPath.length);
1320
- for (const [responseKey] of fieldNodes) {
1321
- const newPath = basePath.concat([responseKey]);
1322
- nullResult[responseKey] = graphql.locatedError(source, fieldNodes[responseKey], newPath);
1323
- }
1324
- }
1325
- else {
1326
- for (const [responseKey] of fieldNodes) {
1327
- nullResult[responseKey] = null;
1328
- }
1329
- }
1330
- source = nullResult;
1331
- }
1332
- // TODO: is this check necessary or just to make TS happy?
1333
- if (!isExternalObject(source)) {
1334
- Object.assign(object, source);
1335
- return object;
1336
- }
1337
- const objectSubschema = getObjectSubchema(source);
1338
- const subschemaMap = getSubschemaMap(source);
1339
- for (const responseKey in source) {
1340
- object[responseKey] = source[responseKey];
1341
- newSubschemaMap[responseKey] = (_a = subschemaMap === null || subschemaMap === void 0 ? void 0 : subschemaMap[responseKey]) !== null && _a !== void 0 ? _a : objectSubschema;
1342
- }
1343
- unpathedErrors.push(...getUnpathedErrors(source));
1344
- }
1345
- }));
1346
- return object;
1347
- }
1348
- const subschemaTypesContainSelectionSet = utils.memoize3(function subschemaTypesContainSelectionSet(mergedTypeInfo, sourceSubschemas, selectionSet) {
1349
- return typesContainSelectionSet(sourceSubschemas.map(sourceSubschema => sourceSubschema.transformedSchema.getType(mergedTypeInfo.typeName)), selectionSet);
1350
- });
1351
- function typesContainSelectionSet(types, selectionSet) {
1352
- var _a;
1353
- const fieldMaps = types.map(type => type.getFields());
1354
- for (const selection of selectionSet.selections) {
1355
- if (selection.kind === graphql.Kind.FIELD) {
1356
- const fields = fieldMaps.map(fieldMap => fieldMap[selection.name.value]).filter(field => field != null);
1357
- if (!fields.length) {
1358
- return false;
1359
- }
1360
- if (selection.selectionSet != null) {
1361
- return typesContainSelectionSet(fields.map(field => graphql.getNamedType(field.type)), selection.selectionSet);
1362
- }
1363
- }
1364
- else if (selection.kind === graphql.Kind.INLINE_FRAGMENT && ((_a = selection.typeCondition) === null || _a === void 0 ? void 0 : _a.name.value) === types[0].name) {
1365
- return typesContainSelectionSet(types, selection.selectionSet);
1366
- }
1367
- }
1368
- return true;
1369
- }
1370
-
1371
- /**
1372
- * Resolver that knows how to:
1373
- * a) handle aliases for proxied schemas
1374
- * b) handle errors from proxied schemas
1375
- * c) handle external to internal enum/scalar conversion
1376
- * d) handle type merging
1377
- * e) handle deferred values
1378
- */
1379
- function defaultMergedResolver(parent, args, context, info) {
1380
- if (!isExternalObject(parent)) {
1381
- return graphql.defaultFieldResolver(parent, args, context, info);
1382
- }
1383
- const responseKey = utils.getResponseKeyFromInfo(info);
1384
- const initialPossibleFields = getInitialPossibleFields(parent);
1385
- if (initialPossibleFields === undefined) {
1386
- // TODO: can this be removed in the next major release?
1387
- // legacy use of delegation without setting transformedSchema
1388
- const data = parent[responseKey];
1389
- if (data !== undefined) {
1390
- return resolveField(parent, responseKey, context, info);
1391
- }
1392
- }
1393
- else if (info.fieldName in initialPossibleFields) {
1394
- return resolveField(parent, responseKey, context, info);
1395
- }
1396
- return getMergedParent(parent, context, info).then(mergedParent => resolveField(mergedParent, responseKey, context, info));
1397
- }
1398
- function resolveField(parent, responseKey, context, info) {
1399
- const initialPath = getInitialPath(parent);
1400
- const subschema = getSubschema(parent, responseKey);
1401
- const unpathedErrors = getUnpathedErrors(parent);
1402
- return createExternalValue(parent[responseKey], unpathedErrors, initialPath, subschema, context, info);
1403
- }
1404
-
1405
- function delegateToSchema(options) {
1406
- const { info, schema, rootValue = schema.rootValue, operationName, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, selectionSet, fieldNodes, context, } = options;
1407
- const request = createRequestFromInfo({
1408
- info,
1409
- operation,
1410
- fieldName,
1411
- selectionSet,
1412
- fieldNodes,
1413
- rootValue,
1414
- operationName,
1415
- context,
1416
- });
1417
- return delegateRequest({
1418
- ...options,
1419
- request,
1420
- operation,
1421
- fieldName,
1422
- });
1423
- }
1424
- function getDelegationReturnType(targetSchema, operation, fieldName) {
1425
- const rootType = utils.getDefinedRootType(targetSchema, operation);
1426
- return rootType.getFields()[fieldName].type;
1427
- }
1428
- function delegateRequest(options) {
1429
- var _a;
1430
- let operationDefinition;
1431
- let targetFieldName;
1432
- const { document, operationName } = options.request;
1433
- if (options.fieldName == null) {
1434
- operationDefinition = graphql.getOperationAST(document, operationName);
1435
- if (operationDefinition == null) {
1436
- throw new Error('Cannot infer main operation from the provided document.');
1437
- }
1438
- targetFieldName = (operationDefinition === null || operationDefinition === void 0 ? void 0 : operationDefinition.selectionSet.selections[0]).name.value;
1439
- }
1440
- else {
1441
- targetFieldName = options.fieldName;
1442
- }
1443
- const { schema, info, operation = getDelegatingOperation(info.parentType, info.schema), returnType = (_a = info === null || info === void 0 ? void 0 : info.returnType) !== null && _a !== void 0 ? _a : getDelegationReturnType(schema instanceof graphql.GraphQLSchema ? schema : schema.schema, operation, targetFieldName), context, onLocatedError = (error) => error, validateRequest: shouldValidateRequest, } = options;
1444
- const delegationContext = getDelegationContext({
1445
- ...options,
1446
- operation,
1447
- fieldName: targetFieldName,
1448
- returnType,
1449
- });
1450
- const transformer = new Transformer(delegationContext);
1451
- const processedRequest = transformer.transformRequest(options.request);
1452
- if (shouldValidateRequest) {
1453
- validateRequest(delegationContext, processedRequest.document);
1454
- }
1455
- const executor = getExecutor(delegationContext);
1456
- return new valueOrPromise.ValueOrPromise(() => executor(processedRequest))
1457
- .then(originalResult => {
1458
- if (utils.isAsyncIterable(originalResult)) {
1459
- // "subscribe" to the subscription result and map the result through the transforms
1460
- return utils.mapAsyncIterator(originalResult, result => externalValueFromResult({
1461
- result: transformer.transformResult(result),
1462
- schema,
1463
- info,
1464
- context,
1465
- fieldName: targetFieldName,
1466
- returnType,
1467
- onLocatedError,
1468
- }));
1469
- }
1470
- return externalValueFromResult({
1471
- result: transformer.transformResult(originalResult),
1472
- schema,
1473
- info,
1474
- context,
1475
- fieldName: targetFieldName,
1476
- returnType,
1477
- onLocatedError,
1478
- });
1479
- })
1480
- .resolve();
1481
- }
1482
- function getDelegationContext({ request, schema, fieldName, returnType, args, info, transforms = [], transformedSchema, }) {
1483
- var _a, _b, _c, _d;
1484
- const { operationType: operation, context, operationName, document } = request;
1485
- let operationDefinition;
1486
- let targetFieldName;
1487
- if (fieldName == null) {
1488
- operationDefinition = graphql.getOperationAST(document, operationName);
1489
- if (operationDefinition == null) {
1490
- throw new Error('Cannot infer main operation from the provided document.');
1491
- }
1492
- targetFieldName = (operationDefinition === null || operationDefinition === void 0 ? void 0 : operationDefinition.selectionSet.selections[0]).name.value;
1493
- }
1494
- else {
1495
- targetFieldName = fieldName;
1496
- }
1497
- const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a['stitchingInfo'];
1498
- const subschemaOrSubschemaConfig = (_b = stitchingInfo === null || stitchingInfo === void 0 ? void 0 : stitchingInfo.subschemaMap.get(schema)) !== null && _b !== void 0 ? _b : schema;
1499
- if (!graphql.isSchema(subschemaOrSubschemaConfig)) {
1500
- const targetSchema = subschemaOrSubschemaConfig.schema;
1501
- return {
1502
- subschema: schema,
1503
- subschemaConfig: subschemaOrSubschemaConfig,
1504
- targetSchema,
1505
- operation,
1506
- fieldName: targetFieldName,
1507
- args,
1508
- context,
1509
- info,
1510
- returnType: (_c = returnType !== null && returnType !== void 0 ? returnType : info === null || info === void 0 ? void 0 : info.returnType) !== null && _c !== void 0 ? _c : getDelegationReturnType(targetSchema, operation, targetFieldName),
1511
- transforms: subschemaOrSubschemaConfig.transforms != null
1512
- ? subschemaOrSubschemaConfig.transforms.concat(transforms)
1513
- : transforms,
1514
- transformedSchema: transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : (subschemaOrSubschemaConfig instanceof Subschema ? subschemaOrSubschemaConfig.transformedSchema : targetSchema),
1515
- };
1516
- }
1517
- return {
1518
- subschema: schema,
1519
- subschemaConfig: undefined,
1520
- targetSchema: subschemaOrSubschemaConfig,
1521
- operation,
1522
- fieldName: targetFieldName,
1523
- args,
1524
- context,
1525
- info,
1526
- returnType: (_d = returnType !== null && returnType !== void 0 ? returnType : info === null || info === void 0 ? void 0 : info.returnType) !== null && _d !== void 0 ? _d : getDelegationReturnType(subschemaOrSubschemaConfig, operation, targetFieldName),
1527
- transforms,
1528
- transformedSchema: transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : subschemaOrSubschemaConfig,
1529
- };
1530
- }
1531
- function validateRequest(delegationContext, document) {
1532
- const errors = graphql.validate(delegationContext.targetSchema, document);
1533
- if (errors.length > 0) {
1534
- if (errors.length > 1) {
1535
- const combinedError = new utils.AggregateError(errors);
1536
- throw combinedError;
1537
- }
1538
- const error = errors[0];
1539
- throw error.originalError || error;
1540
- }
1541
- }
1542
- function getExecutor(delegationContext) {
1543
- var _a, _b;
1544
- const { subschemaConfig, targetSchema, context } = delegationContext;
1545
- let executor = (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.executor) || createDefaultExecutor(targetSchema);
1546
- if (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.batch) {
1547
- const batchingOptions = subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.batchingOptions;
1548
- executor = batchExecute.getBatchingExecutor((_b = (_a = context !== null && context !== void 0 ? context : globalThis) !== null && _a !== void 0 ? _a : window) !== null && _b !== void 0 ? _b : global, executor, batchingOptions === null || batchingOptions === void 0 ? void 0 : batchingOptions.dataLoaderOptions, batchingOptions === null || batchingOptions === void 0 ? void 0 : batchingOptions.extensionsReducer);
1549
- }
1550
- return executor;
1551
- }
1552
- const createDefaultExecutor = utils.memoize1(function createDefaultExecutor(schema) {
1553
- return function defaultExecutor({ document, context, variables, rootValue, operationName, operationType, }) {
1554
- const executionArgs = {
1555
- schema,
1556
- document,
1557
- contextValue: context,
1558
- variableValues: variables,
1559
- rootValue,
1560
- operationName,
1561
- };
1562
- if (operationType === 'subscription') {
1563
- return graphql.subscribe(executionArgs);
1564
- }
1565
- return graphql.execute(executionArgs);
1566
- };
1567
- });
1568
-
1569
- function isSubschemaConfig(value) {
1570
- return Boolean(value === null || value === void 0 ? void 0 : value.schema);
1571
- }
1572
- function cloneSubschemaConfig(subschemaConfig) {
1573
- var _a, _b;
1574
- const newSubschemaConfig = {
1575
- ...subschemaConfig,
1576
- transforms: subschemaConfig.transforms != null ? [...subschemaConfig.transforms] : undefined,
1577
- };
1578
- if (newSubschemaConfig.merge != null) {
1579
- newSubschemaConfig.merge = { ...subschemaConfig.merge };
1580
- for (const typeName in newSubschemaConfig.merge) {
1581
- const mergedTypeConfig = (newSubschemaConfig.merge[typeName] = { ...((_b = (_a = subschemaConfig.merge) === null || _a === void 0 ? void 0 : _a[typeName]) !== null && _b !== void 0 ? _b : {}) });
1582
- if (mergedTypeConfig.entryPoints != null) {
1583
- mergedTypeConfig.entryPoints = mergedTypeConfig.entryPoints.map(entryPoint => ({ ...entryPoint }));
1584
- }
1585
- if (mergedTypeConfig.fields != null) {
1586
- const fields = (mergedTypeConfig.fields = { ...mergedTypeConfig.fields });
1587
- for (const fieldName in fields) {
1588
- fields[fieldName] = { ...fields[fieldName] };
1589
- }
1590
- }
1591
- }
1592
- }
1593
- return newSubschemaConfig;
1594
- }
1595
-
1596
- exports.Subschema = Subschema;
1597
- exports.Transformer = Transformer;
1598
- exports.annotateExternalObject = annotateExternalObject;
1599
- exports.applySchemaTransforms = applySchemaTransforms;
1600
- exports.buildDelegationPlan = buildDelegationPlan;
1601
- exports.cloneSubschemaConfig = cloneSubschemaConfig;
1602
- exports.createDefaultExecutor = createDefaultExecutor;
1603
- exports.createExternalValue = createExternalValue;
1604
- exports.createRequest = createRequest;
1605
- exports.createRequestFromInfo = createRequestFromInfo;
1606
- exports.defaultMergedResolver = defaultMergedResolver;
1607
- exports.delegateRequest = delegateRequest;
1608
- exports.delegateToSchema = delegateToSchema;
1609
- exports.externalValueFromResult = externalValueFromResult;
1610
- exports.getDelegatingOperation = getDelegatingOperation;
1611
- exports.getDelegationContext = getDelegationContext;
1612
- exports.getExecutor = getExecutor;
1613
- exports.getInfo = getInfo;
1614
- exports.getInitialPath = getInitialPath;
1615
- exports.getInitialPossibleFields = getInitialPossibleFields;
1616
- exports.getMergedParent = getMergedParent;
1617
- exports.getObjectSubchema = getObjectSubchema;
1618
- exports.getSubschema = getSubschema;
1619
- exports.getSubschemaMap = getSubschemaMap;
1620
- exports.getUnpathedErrors = getUnpathedErrors;
1621
- exports.isExternalObject = isExternalObject;
1622
- exports.isSubschema = isSubschema;
1623
- exports.isSubschemaConfig = isSubschemaConfig;
1624
- exports.validateRequest = validateRequest;