@graphql-tools/stitching-directives 2.1.1-alpha-db7f3b43.0 → 3.0.0-alpha-24ba9af0.0

Sign up to get free protection for your applications and to get access to all the features.
package/es5/index.mjs DELETED
@@ -1,1191 +0,0 @@
1
- import { __values, __spreadArray, __read, __assign } from 'tslib';
2
- import { visit, Kind, TypeNameMetaFieldDef, parseValue, valueFromASTUntyped, getNullableType, isListType, isNamedType, isInterfaceType, isUnionType, isObjectType, isAbstractType, getNamedType, print, GraphQLDirective, GraphQLNonNull, GraphQLString, GraphQLList, parse } from 'graphql';
3
- import { mapSchema, MapperKind, getDirective, parseSelectionSet, getImplementingTypes, isSome, mergeDeep } from '@graphql-tools/utils/es5';
4
- import { cloneSubschemaConfig } from '@graphql-tools/delegate/es5';
5
-
6
- var defaultStitchingDirectiveOptions = {
7
- keyDirectiveName: 'key',
8
- computedDirectiveName: 'computed',
9
- canonicalDirectiveName: 'canonical',
10
- mergeDirectiveName: 'merge',
11
- pathToDirectivesInExtensions: ['directives'],
12
- };
13
-
14
- function extractVariables(inputValue) {
15
- var _a;
16
- var path = [];
17
- var variablePaths = Object.create(null);
18
- var keyPathVisitor = {
19
- enter: function (_node, key) {
20
- if (typeof key === 'number') {
21
- path.push(key);
22
- }
23
- },
24
- leave: function (_node, key) {
25
- if (typeof key === 'number') {
26
- path.pop();
27
- }
28
- },
29
- };
30
- var fieldPathVisitor = {
31
- enter: function (node) {
32
- path.push(node.name.value);
33
- },
34
- leave: function () {
35
- path.pop();
36
- },
37
- };
38
- var variableVisitor = {
39
- enter: function (node, key) {
40
- if (typeof key === 'number') {
41
- variablePaths[node.name.value] = path.concat([key]);
42
- }
43
- else {
44
- variablePaths[node.name.value] = path.slice();
45
- }
46
- return {
47
- kind: Kind.NULL,
48
- };
49
- },
50
- };
51
- var newInputValue = visit(inputValue, (_a = {},
52
- _a[Kind.OBJECT] = keyPathVisitor,
53
- _a[Kind.LIST] = keyPathVisitor,
54
- _a[Kind.OBJECT_FIELD] = fieldPathVisitor,
55
- _a[Kind.VARIABLE] = variableVisitor,
56
- _a));
57
- return {
58
- inputValue: newInputValue,
59
- variablePaths: variablePaths,
60
- };
61
- }
62
-
63
- var KEY_DELIMITER = '__dot__';
64
- var EXPANSION_PREFIX = '__exp';
65
- function preparseMergeArgsExpr(mergeArgsExpr) {
66
- var variableRegex = /\$[_A-Za-z][_A-Za-z0-9.]*/g;
67
- var dotRegex = /\./g;
68
- mergeArgsExpr = mergeArgsExpr.replace(variableRegex, function (variable) { return variable.replace(dotRegex, KEY_DELIMITER); });
69
- var segments = mergeArgsExpr.split('[[');
70
- var expansionExpressions = Object.create(null);
71
- if (segments.length === 1) {
72
- return { mergeArgsExpr: mergeArgsExpr, expansionExpressions: expansionExpressions };
73
- }
74
- var finalSegments = [segments[0]];
75
- for (var i = 1; i < segments.length; i++) {
76
- var additionalSegments = segments[i].split(']]');
77
- if (additionalSegments.length !== 2) {
78
- throw new Error("Each opening \"[[\" must be matched by a closing \"]]\" without nesting.");
79
- }
80
- finalSegments = finalSegments.concat(additionalSegments);
81
- }
82
- var finalMergeArgsExpr = finalSegments[0];
83
- for (var i = 1; i < finalSegments.length - 1; i += 2) {
84
- var variableName = "" + EXPANSION_PREFIX + ((i - 1) / 2 + 1);
85
- expansionExpressions[variableName] = finalSegments[i];
86
- finalMergeArgsExpr += "$" + variableName + finalSegments[i + 1];
87
- }
88
- return { mergeArgsExpr: finalMergeArgsExpr, expansionExpressions: expansionExpressions };
89
- }
90
-
91
- function addProperty(object, path, value) {
92
- var initialSegment = path[0];
93
- if (path.length === 1) {
94
- object[initialSegment] = value;
95
- return;
96
- }
97
- var field = object[initialSegment];
98
- if (field != null) {
99
- addProperty(field, path.slice(1), value);
100
- return;
101
- }
102
- if (typeof path[1] === 'string') {
103
- field = Object.create(null);
104
- }
105
- else {
106
- field = [];
107
- }
108
- addProperty(field, path.slice(1), value);
109
- object[initialSegment] = field;
110
- }
111
- function getProperty(object, path) {
112
- if (!path.length || object == null) {
113
- return object;
114
- }
115
- var newPath = path.slice();
116
- var key = newPath.shift();
117
- if (key == null) {
118
- return;
119
- }
120
- var prop = object[key];
121
- return getProperty(prop, newPath);
122
- }
123
- function getProperties(object, propertyTree) {
124
- if (object == null) {
125
- return object;
126
- }
127
- var newObject = Object.create(null);
128
- var _loop_1 = function (key) {
129
- var subKey = propertyTree[key];
130
- if (subKey == null) {
131
- newObject[key] = object[key];
132
- return "continue";
133
- }
134
- var prop = object[key];
135
- newObject[key] = deepMap(prop, function deepMapFn(item) {
136
- return getProperties(item, subKey);
137
- });
138
- };
139
- for (var key in propertyTree) {
140
- _loop_1(key);
141
- }
142
- return newObject;
143
- }
144
- function propertyTreeFromPaths(paths) {
145
- var e_1, _a;
146
- var propertyTree = Object.create(null);
147
- try {
148
- for (var paths_1 = __values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {
149
- var path = paths_1_1.value;
150
- addProperty(propertyTree, path, null);
151
- }
152
- }
153
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
154
- finally {
155
- try {
156
- if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);
157
- }
158
- finally { if (e_1) throw e_1.error; }
159
- }
160
- return propertyTree;
161
- }
162
- function deepMap(arrayOrItem, fn) {
163
- if (Array.isArray(arrayOrItem)) {
164
- return arrayOrItem.map(function (nestedArrayOrItem) { return deepMap(nestedArrayOrItem, fn); });
165
- }
166
- return fn(arrayOrItem);
167
- }
168
-
169
- function pathsFromSelectionSet(selectionSet, path) {
170
- var e_1, _a, e_2, _b;
171
- var _c;
172
- if (path === void 0) { path = []; }
173
- var paths = [];
174
- try {
175
- for (var _d = __values(selectionSet.selections), _e = _d.next(); !_e.done; _e = _d.next()) {
176
- var selection = _e.value;
177
- var additions = (_c = pathsFromSelection(selection, path)) !== null && _c !== void 0 ? _c : [];
178
- try {
179
- for (var additions_1 = (e_2 = void 0, __values(additions)), additions_1_1 = additions_1.next(); !additions_1_1.done; additions_1_1 = additions_1.next()) {
180
- var addition = additions_1_1.value;
181
- paths.push(addition);
182
- }
183
- }
184
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
185
- finally {
186
- try {
187
- if (additions_1_1 && !additions_1_1.done && (_b = additions_1.return)) _b.call(additions_1);
188
- }
189
- finally { if (e_2) throw e_2.error; }
190
- }
191
- }
192
- }
193
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
194
- finally {
195
- try {
196
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
197
- }
198
- finally { if (e_1) throw e_1.error; }
199
- }
200
- return paths;
201
- }
202
- function pathsFromSelection(selection, path) {
203
- var _a, _b;
204
- if (selection.kind === Kind.FIELD) {
205
- var responseKey = (_b = (_a = selection.alias) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : selection.name.value;
206
- if (selection.selectionSet) {
207
- return pathsFromSelectionSet(selection.selectionSet, path.concat([responseKey]));
208
- }
209
- else {
210
- return [path.concat([responseKey])];
211
- }
212
- }
213
- else if (selection.kind === Kind.INLINE_FRAGMENT) {
214
- return pathsFromSelectionSet(selection.selectionSet, path);
215
- }
216
- }
217
-
218
- function getSourcePaths(mappingInstructions, selectionSet) {
219
- var e_1, _a, e_2, _b;
220
- var sourcePaths = [];
221
- try {
222
- for (var mappingInstructions_1 = __values(mappingInstructions), mappingInstructions_1_1 = mappingInstructions_1.next(); !mappingInstructions_1_1.done; mappingInstructions_1_1 = mappingInstructions_1.next()) {
223
- var mappingInstruction = mappingInstructions_1_1.value;
224
- var sourcePath = mappingInstruction.sourcePath;
225
- if (sourcePath.length) {
226
- sourcePaths.push(sourcePath);
227
- continue;
228
- }
229
- if (selectionSet == null) {
230
- continue;
231
- }
232
- var paths = pathsFromSelectionSet(selectionSet);
233
- try {
234
- for (var paths_1 = (e_2 = void 0, __values(paths)), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {
235
- var path = paths_1_1.value;
236
- sourcePaths.push(path);
237
- }
238
- }
239
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
240
- finally {
241
- try {
242
- if (paths_1_1 && !paths_1_1.done && (_b = paths_1.return)) _b.call(paths_1);
243
- }
244
- finally { if (e_2) throw e_2.error; }
245
- }
246
- sourcePaths.push([TypeNameMetaFieldDef.name]);
247
- }
248
- }
249
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
250
- finally {
251
- try {
252
- if (mappingInstructions_1_1 && !mappingInstructions_1_1.done && (_a = mappingInstructions_1.return)) _a.call(mappingInstructions_1);
253
- }
254
- finally { if (e_1) throw e_1.error; }
255
- }
256
- return sourcePaths;
257
- }
258
-
259
- function parseMergeArgsExpr(mergeArgsExpr, selectionSet) {
260
- var _a = preparseMergeArgsExpr(mergeArgsExpr), newMergeArgsExpr = _a.mergeArgsExpr, expansionExpressions = _a.expansionExpressions;
261
- var inputValue = parseValue("{ " + newMergeArgsExpr + " }", { noLocation: true });
262
- var _b = extractVariables(inputValue), newInputValue = _b.inputValue, variablePaths = _b.variablePaths;
263
- if (!Object.keys(expansionExpressions).length) {
264
- if (!Object.keys(variablePaths).length) {
265
- throw new Error('Merge arguments must declare a key.');
266
- }
267
- var mappingInstructions = getMappingInstructions(variablePaths);
268
- var usedProperties_1 = propertyTreeFromPaths(getSourcePaths(mappingInstructions, selectionSet));
269
- return { args: valueFromASTUntyped(newInputValue), usedProperties: usedProperties_1, mappingInstructions: mappingInstructions };
270
- }
271
- var expansionRegEx = new RegExp("^" + EXPANSION_PREFIX + "[0-9]+$");
272
- for (var variableName in variablePaths) {
273
- if (!variableName.match(expansionRegEx)) {
274
- throw new Error('Expansions cannot be mixed with single key declarations.');
275
- }
276
- }
277
- var expansions = [];
278
- var sourcePaths = [];
279
- for (var variableName in expansionExpressions) {
280
- var str = expansionExpressions[variableName];
281
- var valuePath = variablePaths[variableName];
282
- var _c = extractVariables(parseValue("" + str, { noLocation: true })), expansionInputValue = _c.inputValue, expansionVariablePaths = _c.variablePaths;
283
- if (!Object.keys(expansionVariablePaths).length) {
284
- throw new Error('Merge arguments must declare a key.');
285
- }
286
- var mappingInstructions = getMappingInstructions(expansionVariablePaths);
287
- var value = valueFromASTUntyped(expansionInputValue);
288
- sourcePaths.push.apply(sourcePaths, __spreadArray([], __read(getSourcePaths(mappingInstructions, selectionSet)), false));
289
- assertNotWithinList(valuePath);
290
- expansions.push({
291
- valuePath: valuePath,
292
- value: value,
293
- mappingInstructions: mappingInstructions,
294
- });
295
- }
296
- var usedProperties = propertyTreeFromPaths(sourcePaths);
297
- return { args: valueFromASTUntyped(newInputValue), usedProperties: usedProperties, expansions: expansions };
298
- }
299
- function getMappingInstructions(variablePaths) {
300
- var mappingInstructions = [];
301
- for (var keyPath in variablePaths) {
302
- var valuePath = variablePaths[keyPath];
303
- var splitKeyPath = keyPath.split(KEY_DELIMITER).slice(1);
304
- assertNotWithinList(valuePath);
305
- mappingInstructions.push({
306
- destinationPath: valuePath,
307
- sourcePath: splitKeyPath,
308
- });
309
- }
310
- return mappingInstructions;
311
- }
312
- function assertNotWithinList(path) {
313
- var e_1, _a;
314
- try {
315
- for (var path_1 = __values(path), path_1_1 = path_1.next(); !path_1_1.done; path_1_1 = path_1.next()) {
316
- var pathSegment = path_1_1.value;
317
- if (typeof pathSegment === 'number') {
318
- throw new Error('Insertions cannot be made into a list.');
319
- }
320
- }
321
- }
322
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
323
- finally {
324
- try {
325
- if (path_1_1 && !path_1_1.done && (_a = path_1.return)) _a.call(path_1);
326
- }
327
- finally { if (e_1) throw e_1.error; }
328
- }
329
- }
330
-
331
- var dottedNameRegEx = /^[_A-Za-z][_0-9A-Za-z]*(.[_A-Za-z][_0-9A-Za-z]*)*$/;
332
- function stitchingDirectivesValidator(options) {
333
- if (options === void 0) { options = {}; }
334
- var _a = __assign(__assign({}, defaultStitchingDirectiveOptions), options), keyDirectiveName = _a.keyDirectiveName, computedDirectiveName = _a.computedDirectiveName, mergeDirectiveName = _a.mergeDirectiveName, pathToDirectivesInExtensions = _a.pathToDirectivesInExtensions;
335
- return function (schema) {
336
- var _a;
337
- var _b;
338
- var queryTypeName = (_b = schema.getQueryType()) === null || _b === void 0 ? void 0 : _b.name;
339
- mapSchema(schema, (_a = {},
340
- _a[MapperKind.OBJECT_TYPE] = function (type) {
341
- var _a;
342
- var keyDirective = (_a = getDirective(schema, type, keyDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
343
- if (keyDirective != null) {
344
- parseSelectionSet(keyDirective['selectionSet']);
345
- }
346
- return undefined;
347
- },
348
- _a[MapperKind.OBJECT_FIELD] = function (fieldConfig, _fieldName, typeName) {
349
- var e_1, _a, e_2, _b;
350
- var _c, _d, _e;
351
- var computedDirective = (_c = getDirective(schema, fieldConfig, computedDirectiveName, pathToDirectivesInExtensions)) === null || _c === void 0 ? void 0 : _c[0];
352
- if (computedDirective != null) {
353
- parseSelectionSet(computedDirective['selectionSet']);
354
- }
355
- var mergeDirective = (_d = getDirective(schema, fieldConfig, mergeDirectiveName, pathToDirectivesInExtensions)) === null || _d === void 0 ? void 0 : _d[0];
356
- if (mergeDirective != null) {
357
- if (typeName !== queryTypeName) {
358
- throw new Error('@merge directive may be used only for root fields of the root Query type.');
359
- }
360
- var returnType = getNullableType(fieldConfig.type);
361
- if (isListType(returnType)) {
362
- returnType = getNullableType(returnType.ofType);
363
- }
364
- if (!isNamedType(returnType)) {
365
- throw new Error('@merge directive must be used on a field that returns an object or a list of objects.');
366
- }
367
- var mergeArgsExpr = mergeDirective['argsExpr'];
368
- if (mergeArgsExpr != null) {
369
- parseMergeArgsExpr(mergeArgsExpr);
370
- }
371
- var args = Object.keys((_e = fieldConfig.args) !== null && _e !== void 0 ? _e : {});
372
- var keyArg = mergeDirective['keyArg'];
373
- if (keyArg == null) {
374
- if (!mergeArgsExpr && args.length !== 1) {
375
- throw new Error('Cannot use @merge directive without `keyArg` argument if resolver takes more than one argument.');
376
- }
377
- }
378
- else if (!keyArg.match(dottedNameRegEx)) {
379
- throw new Error('`keyArg` argument for @merge directive must be a set of valid GraphQL SDL names separated by periods.');
380
- // TODO: ideally we should check that the arg exists for the resolver
381
- }
382
- var keyField = mergeDirective['keyField'];
383
- if (keyField != null && !keyField.match(dottedNameRegEx)) {
384
- throw new Error('`keyField` argument for @merge directive must be a set of valid GraphQL SDL names separated by periods.');
385
- // TODO: ideally we should check that it is part of the key
386
- }
387
- var key = mergeDirective['key'];
388
- if (key != null) {
389
- if (keyField != null) {
390
- throw new Error('Cannot use @merge directive with both `keyField` and `key` arguments.');
391
- }
392
- try {
393
- for (var key_1 = __values(key), key_1_1 = key_1.next(); !key_1_1.done; key_1_1 = key_1.next()) {
394
- var keyDef = key_1_1.value;
395
- var _f = __read(keyDef.split(':'), 2), aliasOrKeyPath = _f[0], keyPath = _f[1];
396
- var aliasPath = void 0;
397
- if (keyPath == null) {
398
- keyPath = aliasPath = aliasOrKeyPath;
399
- }
400
- else {
401
- aliasPath = aliasOrKeyPath;
402
- }
403
- if (keyPath != null && !keyPath.match(dottedNameRegEx)) {
404
- throw new Error('Each partial key within the `key` argument for @merge directive must be a set of valid GraphQL SDL names separated by periods.');
405
- // TODO: ideally we should check that it is part of the key
406
- }
407
- if (aliasPath != null && !aliasOrKeyPath.match(dottedNameRegEx)) {
408
- throw new Error('Each alias within the `key` argument for @merge directive must be a set of valid GraphQL SDL names separated by periods.');
409
- // TODO: ideally we should check that the arg exists within the resolver
410
- }
411
- }
412
- }
413
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
414
- finally {
415
- try {
416
- if (key_1_1 && !key_1_1.done && (_a = key_1.return)) _a.call(key_1);
417
- }
418
- finally { if (e_1) throw e_1.error; }
419
- }
420
- }
421
- var additionalArgs = mergeDirective['additionalArgs'];
422
- if (additionalArgs != null) {
423
- parseValue("{ " + additionalArgs + " }", { noLocation: true });
424
- }
425
- if (mergeArgsExpr != null && (keyArg != null || additionalArgs != null)) {
426
- throw new Error('Cannot use @merge directive with both `argsExpr` argument and any additional argument.');
427
- }
428
- if (!isInterfaceType(returnType) && !isUnionType(returnType) && !isObjectType(returnType)) {
429
- throw new Error('@merge directive may be used only with resolver that return an object, interface, or union.');
430
- }
431
- var typeNames = mergeDirective['types'];
432
- if (typeNames != null) {
433
- if (!isAbstractType(returnType)) {
434
- throw new Error('Types argument can only be used with a field that returns an abstract type.');
435
- }
436
- var implementingTypes = isInterfaceType(returnType)
437
- ? getImplementingTypes(returnType.name, schema).map(function (typeName) { return schema.getType(typeName); })
438
- : returnType.getTypes();
439
- var implementingTypeNames = implementingTypes.map(function (type) { return type === null || type === void 0 ? void 0 : type.name; }).filter(isSome);
440
- try {
441
- for (var typeNames_1 = __values(typeNames), typeNames_1_1 = typeNames_1.next(); !typeNames_1_1.done; typeNames_1_1 = typeNames_1.next()) {
442
- var typeName_1 = typeNames_1_1.value;
443
- if (!implementingTypeNames.includes(typeName_1)) {
444
- throw new Error("Types argument can only include only type names that implement the field return type's abstract type.");
445
- }
446
- }
447
- }
448
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
449
- finally {
450
- try {
451
- if (typeNames_1_1 && !typeNames_1_1.done && (_b = typeNames_1.return)) _b.call(typeNames_1);
452
- }
453
- finally { if (e_2) throw e_2.error; }
454
- }
455
- }
456
- }
457
- return undefined;
458
- },
459
- _a));
460
- return schema;
461
- };
462
- }
463
-
464
- function stitchingDirectivesTransformer(options) {
465
- if (options === void 0) { options = {}; }
466
- var _a = __assign(__assign({}, defaultStitchingDirectiveOptions), options), keyDirectiveName = _a.keyDirectiveName, computedDirectiveName = _a.computedDirectiveName, mergeDirectiveName = _a.mergeDirectiveName, canonicalDirectiveName = _a.canonicalDirectiveName, pathToDirectivesInExtensions = _a.pathToDirectivesInExtensions;
467
- return function (subschemaConfig) {
468
- var _a, _b;
469
- var _c, _d, _e, _f, _g, _h, _j, _k;
470
- var newSubschemaConfig = cloneSubschemaConfig(subschemaConfig);
471
- var selectionSetsByType = Object.create(null);
472
- var computedFieldSelectionSets = Object.create(null);
473
- var mergedTypesResolversInfo = Object.create(null);
474
- var canonicalTypesInfo = Object.create(null);
475
- var schema = subschemaConfig.schema;
476
- // gateway should also run validation
477
- stitchingDirectivesValidator(options)(schema);
478
- function setCanonicalDefinition(typeName, fieldName) {
479
- var _a;
480
- canonicalTypesInfo[typeName] = canonicalTypesInfo[typeName] || Object.create(null);
481
- if (fieldName) {
482
- var fields = (_a = canonicalTypesInfo[typeName].fields) !== null && _a !== void 0 ? _a : Object.create(null);
483
- canonicalTypesInfo[typeName].fields = fields;
484
- fields[fieldName] = true;
485
- }
486
- else {
487
- canonicalTypesInfo[typeName].canonical = true;
488
- }
489
- }
490
- mapSchema(schema, (_a = {},
491
- _a[MapperKind.OBJECT_TYPE] = function (type) {
492
- var _a, _b;
493
- var keyDirective = (_a = getDirective(schema, type, keyDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
494
- if (keyDirective != null) {
495
- var selectionSet = parseSelectionSet(keyDirective['selectionSet'], { noLocation: true });
496
- selectionSetsByType[type.name] = selectionSet;
497
- }
498
- var canonicalDirective = (_b = getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _b === void 0 ? void 0 : _b[0];
499
- if (canonicalDirective != null) {
500
- setCanonicalDefinition(type.name);
501
- }
502
- return undefined;
503
- },
504
- _a[MapperKind.OBJECT_FIELD] = function (fieldConfig, fieldName, typeName) {
505
- var _a, _b, _c;
506
- var computedDirective = (_a = getDirective(schema, fieldConfig, computedDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
507
- if (computedDirective != null) {
508
- var selectionSet = parseSelectionSet(computedDirective['selectionSet'], { noLocation: true });
509
- if (!computedFieldSelectionSets[typeName]) {
510
- computedFieldSelectionSets[typeName] = Object.create(null);
511
- }
512
- computedFieldSelectionSets[typeName][fieldName] = selectionSet;
513
- }
514
- var mergeDirective = (_b = getDirective(schema, fieldConfig, mergeDirectiveName, pathToDirectivesInExtensions)) === null || _b === void 0 ? void 0 : _b[0];
515
- if ((mergeDirective === null || mergeDirective === void 0 ? void 0 : mergeDirective['keyField']) != null) {
516
- var mergeDirectiveKeyField = mergeDirective['keyField'];
517
- var selectionSet_1 = parseSelectionSet("{ " + mergeDirectiveKeyField + "}", { noLocation: true });
518
- var typeNames_1 = mergeDirective['types'];
519
- var returnType = getNamedType(fieldConfig.type);
520
- forEachConcreteType(schema, returnType, typeNames_1, function (typeName) {
521
- if (typeNames_1 == null || typeNames_1.includes(typeName)) {
522
- var existingSelectionSet = selectionSetsByType[typeName];
523
- selectionSetsByType[typeName] = existingSelectionSet
524
- ? mergeSelectionSets(existingSelectionSet, selectionSet_1)
525
- : selectionSet_1;
526
- }
527
- });
528
- }
529
- var canonicalDirective = (_c = getDirective(schema, fieldConfig, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _c === void 0 ? void 0 : _c[0];
530
- if (canonicalDirective != null) {
531
- setCanonicalDefinition(typeName, fieldName);
532
- }
533
- return undefined;
534
- },
535
- _a[MapperKind.INTERFACE_TYPE] = function (type) {
536
- var _a;
537
- var canonicalDirective = (_a = getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
538
- if (canonicalDirective) {
539
- setCanonicalDefinition(type.name);
540
- }
541
- return undefined;
542
- },
543
- _a[MapperKind.INTERFACE_FIELD] = function (fieldConfig, fieldName, typeName) {
544
- var _a;
545
- var canonicalDirective = (_a = getDirective(schema, fieldConfig, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
546
- if (canonicalDirective) {
547
- setCanonicalDefinition(typeName, fieldName);
548
- }
549
- return undefined;
550
- },
551
- _a[MapperKind.INPUT_OBJECT_TYPE] = function (type) {
552
- var _a;
553
- var canonicalDirective = (_a = getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
554
- if (canonicalDirective) {
555
- setCanonicalDefinition(type.name);
556
- }
557
- return undefined;
558
- },
559
- _a[MapperKind.INPUT_OBJECT_FIELD] = function (inputFieldConfig, fieldName, typeName) {
560
- var _a;
561
- var canonicalDirective = (_a = getDirective(schema, inputFieldConfig, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
562
- if (canonicalDirective != null) {
563
- setCanonicalDefinition(typeName, fieldName);
564
- }
565
- return undefined;
566
- },
567
- _a[MapperKind.UNION_TYPE] = function (type) {
568
- var _a;
569
- var canonicalDirective = (_a = getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
570
- if (canonicalDirective != null) {
571
- setCanonicalDefinition(type.name);
572
- }
573
- return undefined;
574
- },
575
- _a[MapperKind.ENUM_TYPE] = function (type) {
576
- var _a;
577
- var canonicalDirective = (_a = getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
578
- if (canonicalDirective != null) {
579
- setCanonicalDefinition(type.name);
580
- }
581
- return undefined;
582
- },
583
- _a[MapperKind.SCALAR_TYPE] = function (type) {
584
- var _a;
585
- var canonicalDirective = (_a = getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
586
- if (canonicalDirective != null) {
587
- setCanonicalDefinition(type.name);
588
- }
589
- return undefined;
590
- },
591
- _a));
592
- if (subschemaConfig.merge) {
593
- for (var typeName in subschemaConfig.merge) {
594
- var mergedTypeConfig = subschemaConfig.merge[typeName];
595
- if (mergedTypeConfig.selectionSet) {
596
- var selectionSet = parseSelectionSet(mergedTypeConfig.selectionSet, { noLocation: true });
597
- if (selectionSet) {
598
- if (selectionSetsByType[typeName]) {
599
- selectionSetsByType[typeName] = mergeSelectionSets(selectionSetsByType[typeName], selectionSet);
600
- }
601
- else {
602
- selectionSetsByType[typeName] = selectionSet;
603
- }
604
- }
605
- }
606
- if (mergedTypeConfig.fields) {
607
- for (var fieldName in mergedTypeConfig.fields) {
608
- var fieldConfig = mergedTypeConfig.fields[fieldName];
609
- if (!fieldConfig.selectionSet)
610
- continue;
611
- var selectionSet = parseSelectionSet(fieldConfig.selectionSet, { noLocation: true });
612
- if (selectionSet) {
613
- if ((_c = computedFieldSelectionSets[typeName]) === null || _c === void 0 ? void 0 : _c[fieldName]) {
614
- computedFieldSelectionSets[typeName][fieldName] = mergeSelectionSets(computedFieldSelectionSets[typeName][fieldName], selectionSet);
615
- }
616
- else {
617
- if (computedFieldSelectionSets[typeName] == null) {
618
- computedFieldSelectionSets[typeName] = Object.create(null);
619
- }
620
- computedFieldSelectionSets[typeName][fieldName] = selectionSet;
621
- }
622
- }
623
- }
624
- }
625
- }
626
- }
627
- var allSelectionSetsByType = Object.create(null);
628
- for (var typeName in selectionSetsByType) {
629
- allSelectionSetsByType[typeName] = allSelectionSetsByType[typeName] || [];
630
- var selectionSet = selectionSetsByType[typeName];
631
- allSelectionSetsByType[typeName].push(selectionSet);
632
- }
633
- for (var typeName in computedFieldSelectionSets) {
634
- var selectionSets = computedFieldSelectionSets[typeName];
635
- for (var i in selectionSets) {
636
- allSelectionSetsByType[typeName] = allSelectionSetsByType[typeName] || [];
637
- var selectionSet = selectionSets[i];
638
- allSelectionSetsByType[typeName].push(selectionSet);
639
- }
640
- }
641
- mapSchema(schema, (_b = {},
642
- _b[MapperKind.OBJECT_FIELD] = function objectFieldMapper(fieldConfig, fieldName) {
643
- var e_1, _a;
644
- var _b, _c;
645
- var mergeDirective = (_b = getDirective(schema, fieldConfig, mergeDirectiveName, pathToDirectivesInExtensions)) === null || _b === void 0 ? void 0 : _b[0];
646
- if (mergeDirective != null) {
647
- var returnType = getNullableType(fieldConfig.type);
648
- var returnsList_1 = isListType(returnType);
649
- var namedType = getNamedType(returnType);
650
- var mergeArgsExpr_1 = mergeDirective['argsExpr'];
651
- if (mergeArgsExpr_1 == null) {
652
- var key = mergeDirective['key'];
653
- var keyField = mergeDirective['keyField'];
654
- var keyExpr = key != null ? buildKeyExpr(key) : keyField != null ? "$key." + keyField : '$key';
655
- var keyArg = mergeDirective['keyArg'];
656
- var argNames = keyArg == null ? [Object.keys((_c = fieldConfig.args) !== null && _c !== void 0 ? _c : {})[0]] : keyArg.split('.');
657
- var lastArgName = argNames.pop();
658
- mergeArgsExpr_1 = returnsList_1 ? lastArgName + ": [[" + keyExpr + "]]" : lastArgName + ": " + keyExpr;
659
- try {
660
- for (var _d = __values(argNames.reverse()), _e = _d.next(); !_e.done; _e = _d.next()) {
661
- var argName = _e.value;
662
- mergeArgsExpr_1 = argName + ": { " + mergeArgsExpr_1 + " }";
663
- }
664
- }
665
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
666
- finally {
667
- try {
668
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
669
- }
670
- finally { if (e_1) throw e_1.error; }
671
- }
672
- }
673
- var typeNames = mergeDirective['types'];
674
- forEachConcreteTypeName(namedType, schema, typeNames, function generateResolveInfo(typeName) {
675
- var parsedMergeArgsExpr = parseMergeArgsExpr(mergeArgsExpr_1, allSelectionSetsByType[typeName] == null
676
- ? undefined
677
- : mergeSelectionSets.apply(void 0, __spreadArray([], __read(allSelectionSetsByType[typeName]), false)));
678
- var additionalArgs = mergeDirective['additionalArgs'];
679
- if (additionalArgs != null) {
680
- parsedMergeArgsExpr.args = mergeDeep([
681
- parsedMergeArgsExpr.args,
682
- valueFromASTUntyped(parseValue("{ " + additionalArgs + " }", { noLocation: true })),
683
- ]);
684
- }
685
- mergedTypesResolversInfo[typeName] = __assign({ fieldName: fieldName, returnsList: returnsList_1 }, parsedMergeArgsExpr);
686
- });
687
- }
688
- return undefined;
689
- },
690
- _b));
691
- for (var typeName in selectionSetsByType) {
692
- var selectionSet = selectionSetsByType[typeName];
693
- var mergeConfig = (_d = newSubschemaConfig.merge) !== null && _d !== void 0 ? _d : Object.create(null);
694
- newSubschemaConfig.merge = mergeConfig;
695
- if (mergeConfig[typeName] == null) {
696
- newSubschemaConfig.merge[typeName] = Object.create(null);
697
- }
698
- var mergeTypeConfig = mergeConfig[typeName];
699
- mergeTypeConfig.selectionSet = print(selectionSet);
700
- }
701
- for (var typeName in computedFieldSelectionSets) {
702
- var selectionSets = computedFieldSelectionSets[typeName];
703
- var mergeConfig = (_e = newSubschemaConfig.merge) !== null && _e !== void 0 ? _e : Object.create(null);
704
- newSubschemaConfig.merge = mergeConfig;
705
- if (mergeConfig[typeName] == null) {
706
- mergeConfig[typeName] = Object.create(null);
707
- }
708
- var mergeTypeConfig = newSubschemaConfig.merge[typeName];
709
- var mergeTypeConfigFields = (_f = mergeTypeConfig.fields) !== null && _f !== void 0 ? _f : Object.create(null);
710
- mergeTypeConfig.fields = mergeTypeConfigFields;
711
- for (var fieldName in selectionSets) {
712
- var selectionSet = selectionSets[fieldName];
713
- var fieldConfig = (_g = mergeTypeConfigFields[fieldName]) !== null && _g !== void 0 ? _g : Object.create(null);
714
- mergeTypeConfigFields[fieldName] = fieldConfig;
715
- fieldConfig.selectionSet = print(selectionSet);
716
- fieldConfig.computed = true;
717
- }
718
- }
719
- for (var typeName in mergedTypesResolversInfo) {
720
- var mergedTypeResolverInfo = mergedTypesResolversInfo[typeName];
721
- var mergeConfig = (_h = newSubschemaConfig.merge) !== null && _h !== void 0 ? _h : Object.create(null);
722
- newSubschemaConfig.merge = mergeConfig;
723
- if (newSubschemaConfig.merge[typeName] == null) {
724
- newSubschemaConfig.merge[typeName] = Object.create(null);
725
- }
726
- var mergeTypeConfig = newSubschemaConfig.merge[typeName];
727
- mergeTypeConfig.fieldName = mergedTypeResolverInfo.fieldName;
728
- if (mergedTypeResolverInfo.returnsList) {
729
- mergeTypeConfig.key = generateKeyFn(mergedTypeResolverInfo);
730
- mergeTypeConfig.argsFromKeys = generateArgsFromKeysFn(mergedTypeResolverInfo);
731
- }
732
- else {
733
- mergeTypeConfig.args = generateArgsFn(mergedTypeResolverInfo);
734
- }
735
- }
736
- for (var typeName in canonicalTypesInfo) {
737
- var canonicalTypeInfo = canonicalTypesInfo[typeName];
738
- var mergeConfig = (_j = newSubschemaConfig.merge) !== null && _j !== void 0 ? _j : Object.create(null);
739
- newSubschemaConfig.merge = mergeConfig;
740
- if (newSubschemaConfig.merge[typeName] == null) {
741
- newSubschemaConfig.merge[typeName] = Object.create(null);
742
- }
743
- var mergeTypeConfig = newSubschemaConfig.merge[typeName];
744
- if (canonicalTypeInfo.canonical) {
745
- mergeTypeConfig.canonical = true;
746
- }
747
- if (canonicalTypeInfo.fields) {
748
- var mergeTypeConfigFields = (_k = mergeTypeConfig.fields) !== null && _k !== void 0 ? _k : Object.create(null);
749
- mergeTypeConfig.fields = mergeTypeConfigFields;
750
- for (var fieldName in canonicalTypeInfo.fields) {
751
- if (mergeTypeConfigFields[fieldName] == null) {
752
- mergeTypeConfigFields[fieldName] = Object.create(null);
753
- }
754
- mergeTypeConfigFields[fieldName].canonical = true;
755
- }
756
- }
757
- }
758
- return newSubschemaConfig;
759
- };
760
- }
761
- function forEachConcreteType(schema, type, typeNames, fn) {
762
- var e_2, _a, e_3, _b;
763
- if (isInterfaceType(type)) {
764
- try {
765
- for (var _c = __values(getImplementingTypes(type.name, schema)), _d = _c.next(); !_d.done; _d = _c.next()) {
766
- var typeName = _d.value;
767
- if (typeNames == null || typeNames.includes(typeName)) {
768
- fn(typeName);
769
- }
770
- }
771
- }
772
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
773
- finally {
774
- try {
775
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
776
- }
777
- finally { if (e_2) throw e_2.error; }
778
- }
779
- }
780
- else if (isUnionType(type)) {
781
- try {
782
- for (var _e = __values(type.getTypes()), _f = _e.next(); !_f.done; _f = _e.next()) {
783
- var typeName = _f.value.name;
784
- if (typeNames == null || typeNames.includes(typeName)) {
785
- fn(typeName);
786
- }
787
- }
788
- }
789
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
790
- finally {
791
- try {
792
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
793
- }
794
- finally { if (e_3) throw e_3.error; }
795
- }
796
- }
797
- else if (isObjectType(type)) {
798
- fn(type.name);
799
- }
800
- }
801
- function generateKeyFn(mergedTypeResolverInfo) {
802
- return function keyFn(originalResult) {
803
- return getProperties(originalResult, mergedTypeResolverInfo.usedProperties);
804
- };
805
- }
806
- function generateArgsFromKeysFn(mergedTypeResolverInfo) {
807
- var expansions = mergedTypeResolverInfo.expansions, args = mergedTypeResolverInfo.args;
808
- return function generateArgsFromKeys(keys) {
809
- var e_4, _a, e_5, _b, e_6, _c;
810
- var newArgs = mergeDeep([{}, args]);
811
- if (expansions) {
812
- try {
813
- for (var expansions_1 = __values(expansions), expansions_1_1 = expansions_1.next(); !expansions_1_1.done; expansions_1_1 = expansions_1.next()) {
814
- var expansion = expansions_1_1.value;
815
- var mappingInstructions = expansion.mappingInstructions;
816
- var expanded = [];
817
- try {
818
- for (var keys_1 = (e_5 = void 0, __values(keys)), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
819
- var key = keys_1_1.value;
820
- var newValue = mergeDeep([{}, expansion.valuePath]);
821
- try {
822
- for (var mappingInstructions_1 = (e_6 = void 0, __values(mappingInstructions)), mappingInstructions_1_1 = mappingInstructions_1.next(); !mappingInstructions_1_1.done; mappingInstructions_1_1 = mappingInstructions_1.next()) {
823
- var _d = mappingInstructions_1_1.value, destinationPath = _d.destinationPath, sourcePath = _d.sourcePath;
824
- if (destinationPath.length) {
825
- addProperty(newValue, destinationPath, getProperty(key, sourcePath));
826
- }
827
- else {
828
- newValue = getProperty(key, sourcePath);
829
- }
830
- }
831
- }
832
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
833
- finally {
834
- try {
835
- if (mappingInstructions_1_1 && !mappingInstructions_1_1.done && (_c = mappingInstructions_1.return)) _c.call(mappingInstructions_1);
836
- }
837
- finally { if (e_6) throw e_6.error; }
838
- }
839
- expanded.push(newValue);
840
- }
841
- }
842
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
843
- finally {
844
- try {
845
- if (keys_1_1 && !keys_1_1.done && (_b = keys_1.return)) _b.call(keys_1);
846
- }
847
- finally { if (e_5) throw e_5.error; }
848
- }
849
- addProperty(newArgs, expansion.valuePath, expanded);
850
- }
851
- }
852
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
853
- finally {
854
- try {
855
- if (expansions_1_1 && !expansions_1_1.done && (_a = expansions_1.return)) _a.call(expansions_1);
856
- }
857
- finally { if (e_4) throw e_4.error; }
858
- }
859
- }
860
- return newArgs;
861
- };
862
- }
863
- function generateArgsFn(mergedTypeResolverInfo) {
864
- var mappingInstructions = mergedTypeResolverInfo.mappingInstructions, args = mergedTypeResolverInfo.args, usedProperties = mergedTypeResolverInfo.usedProperties;
865
- return function generateArgs(originalResult) {
866
- var e_7, _a;
867
- var newArgs = mergeDeep([{}, args]);
868
- var filteredResult = getProperties(originalResult, usedProperties);
869
- if (mappingInstructions) {
870
- try {
871
- for (var mappingInstructions_2 = __values(mappingInstructions), mappingInstructions_2_1 = mappingInstructions_2.next(); !mappingInstructions_2_1.done; mappingInstructions_2_1 = mappingInstructions_2.next()) {
872
- var mappingInstruction = mappingInstructions_2_1.value;
873
- var destinationPath = mappingInstruction.destinationPath, sourcePath = mappingInstruction.sourcePath;
874
- addProperty(newArgs, destinationPath, getProperty(filteredResult, sourcePath));
875
- }
876
- }
877
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
878
- finally {
879
- try {
880
- if (mappingInstructions_2_1 && !mappingInstructions_2_1.done && (_a = mappingInstructions_2.return)) _a.call(mappingInstructions_2);
881
- }
882
- finally { if (e_7) throw e_7.error; }
883
- }
884
- }
885
- return newArgs;
886
- };
887
- }
888
- function buildKeyExpr(key) {
889
- var e_8, _a, _b, e_9, _c, _d;
890
- var mergedObject = {};
891
- try {
892
- for (var key_1 = __values(key), key_1_1 = key_1.next(); !key_1_1.done; key_1_1 = key_1.next()) {
893
- var keyDef = key_1_1.value;
894
- var _e = __read(keyDef.split(':'), 2), aliasOrKeyPath = _e[0], keyPath = _e[1];
895
- var aliasPath = void 0;
896
- if (keyPath == null) {
897
- keyPath = aliasPath = aliasOrKeyPath;
898
- }
899
- else {
900
- aliasPath = aliasOrKeyPath;
901
- }
902
- var aliasParts = aliasPath.split('.');
903
- var lastAliasPart = aliasParts.pop();
904
- if (lastAliasPart == null) {
905
- throw new Error("Key \"" + key + "\" is invalid, no path provided.");
906
- }
907
- var object = (_b = {}, _b[lastAliasPart] = "$key." + keyPath, _b);
908
- try {
909
- for (var _f = (e_9 = void 0, __values(aliasParts.reverse())), _g = _f.next(); !_g.done; _g = _f.next()) {
910
- var aliasPart = _g.value;
911
- object = (_d = {}, _d[aliasPart] = object, _d);
912
- }
913
- }
914
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
915
- finally {
916
- try {
917
- if (_g && !_g.done && (_c = _f.return)) _c.call(_f);
918
- }
919
- finally { if (e_9) throw e_9.error; }
920
- }
921
- mergedObject = mergeDeep([mergedObject, object]);
922
- }
923
- }
924
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
925
- finally {
926
- try {
927
- if (key_1_1 && !key_1_1.done && (_a = key_1.return)) _a.call(key_1);
928
- }
929
- finally { if (e_8) throw e_8.error; }
930
- }
931
- return JSON.stringify(mergedObject).replace(/"/g, '');
932
- }
933
- function mergeSelectionSets() {
934
- var e_10, _a, e_11, _b;
935
- var selectionSets = [];
936
- for (var _i = 0; _i < arguments.length; _i++) {
937
- selectionSets[_i] = arguments[_i];
938
- }
939
- var normalizedSelections = Object.create(null);
940
- try {
941
- for (var selectionSets_1 = __values(selectionSets), selectionSets_1_1 = selectionSets_1.next(); !selectionSets_1_1.done; selectionSets_1_1 = selectionSets_1.next()) {
942
- var selectionSet = selectionSets_1_1.value;
943
- try {
944
- for (var _c = (e_11 = void 0, __values(selectionSet.selections)), _d = _c.next(); !_d.done; _d = _c.next()) {
945
- var selection = _d.value;
946
- var normalizedSelection = print(selection);
947
- normalizedSelections[normalizedSelection] = selection;
948
- }
949
- }
950
- catch (e_11_1) { e_11 = { error: e_11_1 }; }
951
- finally {
952
- try {
953
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
954
- }
955
- finally { if (e_11) throw e_11.error; }
956
- }
957
- }
958
- }
959
- catch (e_10_1) { e_10 = { error: e_10_1 }; }
960
- finally {
961
- try {
962
- if (selectionSets_1_1 && !selectionSets_1_1.done && (_a = selectionSets_1.return)) _a.call(selectionSets_1);
963
- }
964
- finally { if (e_10) throw e_10.error; }
965
- }
966
- var newSelectionSet = {
967
- kind: Kind.SELECTION_SET,
968
- selections: Object.values(normalizedSelections),
969
- };
970
- return newSelectionSet;
971
- }
972
- function forEachConcreteTypeName(returnType, schema, typeNames, fn) {
973
- var e_12, _a, e_13, _b;
974
- if (isInterfaceType(returnType)) {
975
- try {
976
- for (var _c = __values(getImplementingTypes(returnType.name, schema)), _d = _c.next(); !_d.done; _d = _c.next()) {
977
- var typeName = _d.value;
978
- if (typeNames == null || typeNames.includes(typeName)) {
979
- fn(typeName);
980
- }
981
- }
982
- }
983
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
984
- finally {
985
- try {
986
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
987
- }
988
- finally { if (e_12) throw e_12.error; }
989
- }
990
- }
991
- else if (isUnionType(returnType)) {
992
- try {
993
- for (var _e = __values(returnType.getTypes()), _f = _e.next(); !_f.done; _f = _e.next()) {
994
- var type = _f.value;
995
- if (typeNames == null || typeNames.includes(type.name)) {
996
- fn(type.name);
997
- }
998
- }
999
- }
1000
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
1001
- finally {
1002
- try {
1003
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
1004
- }
1005
- finally { if (e_13) throw e_13.error; }
1006
- }
1007
- }
1008
- else if (isObjectType(returnType) && (typeNames == null || typeNames.includes(returnType.name))) {
1009
- fn(returnType.name);
1010
- }
1011
- }
1012
-
1013
- function stitchingDirectives(options) {
1014
- if (options === void 0) { options = {}; }
1015
- var finalOptions = __assign(__assign({}, defaultStitchingDirectiveOptions), options);
1016
- var keyDirectiveName = finalOptions.keyDirectiveName, computedDirectiveName = finalOptions.computedDirectiveName, mergeDirectiveName = finalOptions.mergeDirectiveName, canonicalDirectiveName = finalOptions.canonicalDirectiveName;
1017
- var keyDirectiveTypeDefs = /* GraphQL */ "directive @" + keyDirectiveName + "(selectionSet: String!) on OBJECT";
1018
- var computedDirectiveTypeDefs = /* GraphQL */ "directive @" + computedDirectiveName + "(selectionSet: String!) on FIELD_DEFINITION";
1019
- var mergeDirectiveTypeDefs = /* GraphQL */ "directive @" + mergeDirectiveName + "(argsExpr: String, keyArg: String, keyField: String, key: [String!], additionalArgs: String) on FIELD_DEFINITION";
1020
- var canonicalDirectiveTypeDefs = /* GraphQL */ "directive @" + canonicalDirectiveName + " on OBJECT | INTERFACE | INPUT_OBJECT | UNION | ENUM | SCALAR | FIELD_DEFINITION | INPUT_FIELD_DEFINITION";
1021
- var keyDirective = new GraphQLDirective({
1022
- name: keyDirectiveName,
1023
- locations: ['OBJECT'],
1024
- args: {
1025
- selectionSet: { type: new GraphQLNonNull(GraphQLString) },
1026
- },
1027
- });
1028
- var computedDirective = new GraphQLDirective({
1029
- name: computedDirectiveName,
1030
- locations: ['FIELD_DEFINITION'],
1031
- args: {
1032
- selectionSet: { type: new GraphQLNonNull(GraphQLString) },
1033
- },
1034
- });
1035
- var mergeDirective = new GraphQLDirective({
1036
- name: mergeDirectiveName,
1037
- locations: ['FIELD_DEFINITION'],
1038
- args: {
1039
- argsExpr: { type: GraphQLString },
1040
- keyArg: { type: GraphQLString },
1041
- keyField: { type: GraphQLString },
1042
- key: { type: new GraphQLList(new GraphQLNonNull(GraphQLString)) },
1043
- additionalArgs: { type: GraphQLString },
1044
- },
1045
- });
1046
- var canonicalDirective = new GraphQLDirective({
1047
- name: canonicalDirectiveName,
1048
- locations: [
1049
- 'OBJECT',
1050
- 'INTERFACE',
1051
- 'INPUT_OBJECT',
1052
- 'UNION',
1053
- 'ENUM',
1054
- 'SCALAR',
1055
- 'FIELD_DEFINITION',
1056
- 'INPUT_FIELD_DEFINITION',
1057
- ],
1058
- });
1059
- var allStitchingDirectivesTypeDefs = [
1060
- keyDirectiveTypeDefs,
1061
- computedDirectiveTypeDefs,
1062
- mergeDirectiveTypeDefs,
1063
- canonicalDirectiveTypeDefs,
1064
- ].join('\n');
1065
- return {
1066
- keyDirectiveTypeDefs: keyDirectiveTypeDefs,
1067
- computedDirectiveTypeDefs: computedDirectiveTypeDefs,
1068
- mergeDirectiveTypeDefs: mergeDirectiveTypeDefs,
1069
- canonicalDirectiveTypeDefs: canonicalDirectiveTypeDefs,
1070
- stitchingDirectivesTypeDefs: allStitchingDirectivesTypeDefs,
1071
- allStitchingDirectivesTypeDefs: allStitchingDirectivesTypeDefs,
1072
- keyDirective: keyDirective,
1073
- computedDirective: computedDirective,
1074
- mergeDirective: mergeDirective,
1075
- canonicalDirective: canonicalDirective,
1076
- allStitchingDirectives: [keyDirective, computedDirective, mergeDirective, canonicalDirective],
1077
- stitchingDirectivesValidator: stitchingDirectivesValidator(finalOptions),
1078
- stitchingDirectivesTransformer: stitchingDirectivesTransformer(finalOptions),
1079
- };
1080
- }
1081
-
1082
- // Taken from https://github.com/gmac/federation-to-stitching-sdl/blob/main/index.js
1083
- var extensionKind = /Extension$/;
1084
- var entityKinds = [
1085
- Kind.OBJECT_TYPE_DEFINITION,
1086
- Kind.OBJECT_TYPE_EXTENSION,
1087
- Kind.INTERFACE_TYPE_DEFINITION,
1088
- Kind.INTERFACE_TYPE_EXTENSION,
1089
- ];
1090
- function isEntityKind(def) {
1091
- return entityKinds.includes(def.kind);
1092
- }
1093
- function getQueryTypeDef(definitions) {
1094
- var _a;
1095
- var schemaDef = definitions.find(function (def) { return def.kind === Kind.SCHEMA_DEFINITION; });
1096
- var typeName = schemaDef
1097
- ? (_a = schemaDef.operationTypes.find(function (_a) {
1098
- var operation = _a.operation;
1099
- return operation === 'query';
1100
- })) === null || _a === void 0 ? void 0 : _a.type.name.value
1101
- : 'Query';
1102
- return definitions.find(function (def) { return def.kind === Kind.OBJECT_TYPE_DEFINITION && def.name.value === typeName; });
1103
- }
1104
- // Federation services are actually fairly complex,
1105
- // as the `buildFederatedSchema` helper does a fair amount
1106
- // of hidden work to setup the Federation schema specification:
1107
- // https://www.apollographql.com/docs/federation/federation-spec/#federation-schema-specification
1108
- function federationToStitchingSDL(federationSDL, stitchingConfig) {
1109
- if (stitchingConfig === void 0) { stitchingConfig = stitchingDirectives(); }
1110
- var doc = parse(federationSDL);
1111
- var entityTypes = [];
1112
- var baseTypeNames = doc.definitions.reduce(function (memo, typeDef) {
1113
- if (!extensionKind.test(typeDef.kind) && 'name' in typeDef && typeDef.name) {
1114
- memo[typeDef.name.value] = true;
1115
- }
1116
- return memo;
1117
- }, {});
1118
- doc.definitions.forEach(function (typeDef) {
1119
- var _a, _b, _c;
1120
- // Un-extend all types (remove "extends" keywords)...
1121
- // extended types are invalid GraphQL without a local base type to extend from.
1122
- // Stitching merges flat types in lieu of hierarchical extensions.
1123
- if (extensionKind.test(typeDef.kind) && 'name' in typeDef && typeDef.name && !baseTypeNames[typeDef.name.value]) {
1124
- typeDef.kind = typeDef.kind.replace(extensionKind, 'Definition');
1125
- }
1126
- if (!isEntityKind(typeDef))
1127
- return;
1128
- // Find object definitions with "@key" directives;
1129
- // these are federated entities that get turned into merged types.
1130
- var keyDirs = [];
1131
- var otherDirs = [];
1132
- (_a = typeDef.directives) === null || _a === void 0 ? void 0 : _a.forEach(function (dir) {
1133
- if (dir.name.value === 'key') {
1134
- keyDirs.push(dir);
1135
- }
1136
- else {
1137
- otherDirs.push(dir);
1138
- }
1139
- });
1140
- if (!keyDirs.length)
1141
- return;
1142
- // Setup stitching MergedTypeConfig for all federated entities:
1143
- var selectionSet = "{ " + keyDirs.map(function (dir) { return dir.arguments[0].value.value; }).join(' ') + " }";
1144
- var keyFields = parse(selectionSet).definitions[0].selectionSet.selections.map(function (sel) { return sel.name.value; });
1145
- var keyDir = keyDirs[0];
1146
- keyDir.name.value = stitchingConfig.keyDirective.name;
1147
- keyDir.arguments[0].name.value = 'selectionSet';
1148
- keyDir.arguments[0].value.value = selectionSet;
1149
- typeDef.directives = __spreadArray([keyDir], __read(otherDirs), false);
1150
- // Remove non-key "@external" fields from the type...
1151
- // the stitching query planner expects services to only publish their own fields.
1152
- // This makes "@provides" moot because the query planner can automate the logic.
1153
- typeDef.fields = (_b = typeDef.fields) === null || _b === void 0 ? void 0 : _b.filter(function (fieldDef) {
1154
- var _a;
1155
- return (keyFields.includes(fieldDef.name.value) || !((_a = fieldDef.directives) === null || _a === void 0 ? void 0 : _a.find(function (dir) { return dir.name.value === 'external'; })));
1156
- });
1157
- // Discard remaining "@external" directives and any "@provides" directives
1158
- (_c = typeDef.fields) === null || _c === void 0 ? void 0 : _c.forEach(function (fieldDef) {
1159
- fieldDef.directives = fieldDef.directives.filter(function (dir) { return !/^(external|provides)$/.test(dir.name.value); });
1160
- fieldDef.directives.forEach(function (dir) {
1161
- if (dir.name.value === 'requires') {
1162
- dir.name.value = stitchingConfig.computedDirective.name;
1163
- dir.arguments[0].name.value = 'selectionSet';
1164
- dir.arguments[0].value.value = "{ " + dir.arguments[0].value.value + " }";
1165
- }
1166
- });
1167
- });
1168
- if (typeDef.kind === Kind.OBJECT_TYPE_DEFINITION || typeDef.kind === Kind.OBJECT_TYPE_EXTENSION) {
1169
- entityTypes.push(typeDef.name.value);
1170
- }
1171
- });
1172
- // Federation service SDLs are incomplete because they omit the federation spec itself...
1173
- // (https://www.apollographql.com/docs/federation/federation-spec/#federation-schema-specification)
1174
- // To make federation SDLs into valid and parsable GraphQL schemas,
1175
- // we must fill in the missing details from the specification.
1176
- if (entityTypes.length) {
1177
- var queryDef = getQueryTypeDef(doc.definitions);
1178
- var entitiesSchema = parse(/* GraphQL */ "\n scalar _Any\n union _Entity = " + entityTypes.filter(function (v, i, a) { return a.indexOf(v) === i; }).join(' | ') + "\n type Query { _entities(representations: [_Any!]!): [_Entity]! @" + stitchingConfig.mergeDirective.name + " }\n ").definitions;
1179
- doc.definitions.push(entitiesSchema[0]);
1180
- doc.definitions.push(entitiesSchema[1]);
1181
- if (queryDef) {
1182
- queryDef.fields.push(entitiesSchema[2].fields[0]);
1183
- }
1184
- else {
1185
- doc.definitions.push(entitiesSchema[2]);
1186
- }
1187
- }
1188
- return [stitchingConfig.stitchingDirectivesTypeDefs, print(doc)].join('\n');
1189
- }
1190
-
1191
- export { federationToStitchingSDL, stitchingDirectives };