UNPKG

49.9 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var globals = require('./globals');
6var graphql = require('graphql');
7var tslib = require('tslib');
8var zenObservableTs = require('zen-observable-ts');
9require('symbol-observable');
10
11function shouldInclude(_a, variables) {
12 var directives = _a.directives;
13 if (!directives || !directives.length) {
14 return true;
15 }
16 return getInclusionDirectives(directives).every(function (_a) {
17 var directive = _a.directive, ifArgument = _a.ifArgument;
18 var evaledValue = false;
19 if (ifArgument.value.kind === 'Variable') {
20 evaledValue = variables && variables[ifArgument.value.name.value];
21 __DEV__ ? globals.invariant(evaledValue !== void 0, "Invalid variable referenced in @".concat(directive.name.value, " directive.")) : globals.invariant(evaledValue !== void 0, 39);
22 }
23 else {
24 evaledValue = ifArgument.value.value;
25 }
26 return directive.name.value === 'skip' ? !evaledValue : evaledValue;
27 });
28}
29function getDirectiveNames(root) {
30 var names = [];
31 graphql.visit(root, {
32 Directive: function (node) {
33 names.push(node.name.value);
34 },
35 });
36 return names;
37}
38var hasAnyDirectives = function (names, root) { return hasDirectives(names, root, false); };
39var hasAllDirectives = function (names, root) { return hasDirectives(names, root, true); };
40function hasDirectives(names, root, all) {
41 var nameSet = new Set(names);
42 var uniqueCount = nameSet.size;
43 graphql.visit(root, {
44 Directive: function (node) {
45 if (nameSet.delete(node.name.value) &&
46 (!all || !nameSet.size)) {
47 return graphql.BREAK;
48 }
49 },
50 });
51 return all ? !nameSet.size : nameSet.size < uniqueCount;
52}
53function hasClientExports(document) {
54 return document && hasDirectives(['client', 'export'], document, true);
55}
56function isInclusionDirective(_a) {
57 var value = _a.name.value;
58 return value === 'skip' || value === 'include';
59}
60function getInclusionDirectives(directives) {
61 var result = [];
62 if (directives && directives.length) {
63 directives.forEach(function (directive) {
64 if (!isInclusionDirective(directive))
65 return;
66 var directiveArguments = directive.arguments;
67 var directiveName = directive.name.value;
68 __DEV__ ? globals.invariant(directiveArguments && directiveArguments.length === 1, "Incorrect number of arguments for the @".concat(directiveName, " directive.")) : globals.invariant(directiveArguments && directiveArguments.length === 1, 40);
69 var ifArgument = directiveArguments[0];
70 __DEV__ ? globals.invariant(ifArgument.name && ifArgument.name.value === 'if', "Invalid argument for the @".concat(directiveName, " directive.")) : globals.invariant(ifArgument.name && ifArgument.name.value === 'if', 41);
71 var ifValue = ifArgument.value;
72 __DEV__ ? globals.invariant(ifValue &&
73 (ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), "Argument for the @".concat(directiveName, " directive must be a variable or a boolean value.")) : globals.invariant(ifValue &&
74 (ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), 42);
75 result.push({ directive: directive, ifArgument: ifArgument });
76 });
77 }
78 return result;
79}
80
81function getFragmentQueryDocument(document, fragmentName) {
82 var actualFragmentName = fragmentName;
83 var fragments = [];
84 document.definitions.forEach(function (definition) {
85 if (definition.kind === 'OperationDefinition') {
86 throw __DEV__ ? new globals.InvariantError("Found a ".concat(definition.operation, " operation").concat(definition.name ? " named '".concat(definition.name.value, "'") : '', ". ") +
87 'No operations are allowed when using a fragment as a query. Only fragments are allowed.') : new globals.InvariantError(43);
88 }
89 if (definition.kind === 'FragmentDefinition') {
90 fragments.push(definition);
91 }
92 });
93 if (typeof actualFragmentName === 'undefined') {
94 __DEV__ ? globals.invariant(fragments.length === 1, "Found ".concat(fragments.length, " fragments. `fragmentName` must be provided when there is not exactly 1 fragment.")) : globals.invariant(fragments.length === 1, 44);
95 actualFragmentName = fragments[0].name.value;
96 }
97 var query = tslib.__assign(tslib.__assign({}, document), { definitions: tslib.__spreadArray([
98 {
99 kind: 'OperationDefinition',
100 operation: 'query',
101 selectionSet: {
102 kind: 'SelectionSet',
103 selections: [
104 {
105 kind: 'FragmentSpread',
106 name: {
107 kind: 'Name',
108 value: actualFragmentName,
109 },
110 },
111 ],
112 },
113 }
114 ], document.definitions, true) });
115 return query;
116}
117function createFragmentMap(fragments) {
118 if (fragments === void 0) { fragments = []; }
119 var symTable = {};
120 fragments.forEach(function (fragment) {
121 symTable[fragment.name.value] = fragment;
122 });
123 return symTable;
124}
125function getFragmentFromSelection(selection, fragmentMap) {
126 switch (selection.kind) {
127 case 'InlineFragment':
128 return selection;
129 case 'FragmentSpread': {
130 var fragmentName = selection.name.value;
131 if (typeof fragmentMap === "function") {
132 return fragmentMap(fragmentName);
133 }
134 var fragment = fragmentMap && fragmentMap[fragmentName];
135 __DEV__ ? globals.invariant(fragment, "No fragment named ".concat(fragmentName)) : globals.invariant(fragment, 45);
136 return fragment || null;
137 }
138 default:
139 return null;
140 }
141}
142
143function isNonNullObject(obj) {
144 return obj !== null && typeof obj === 'object';
145}
146
147function makeReference(id) {
148 return { __ref: String(id) };
149}
150function isReference(obj) {
151 return Boolean(obj && typeof obj === 'object' && typeof obj.__ref === 'string');
152}
153function isDocumentNode(value) {
154 return (isNonNullObject(value) &&
155 value.kind === "Document" &&
156 Array.isArray(value.definitions));
157}
158function isStringValue(value) {
159 return value.kind === 'StringValue';
160}
161function isBooleanValue(value) {
162 return value.kind === 'BooleanValue';
163}
164function isIntValue(value) {
165 return value.kind === 'IntValue';
166}
167function isFloatValue(value) {
168 return value.kind === 'FloatValue';
169}
170function isVariable(value) {
171 return value.kind === 'Variable';
172}
173function isObjectValue(value) {
174 return value.kind === 'ObjectValue';
175}
176function isListValue(value) {
177 return value.kind === 'ListValue';
178}
179function isEnumValue(value) {
180 return value.kind === 'EnumValue';
181}
182function isNullValue(value) {
183 return value.kind === 'NullValue';
184}
185function valueToObjectRepresentation(argObj, name, value, variables) {
186 if (isIntValue(value) || isFloatValue(value)) {
187 argObj[name.value] = Number(value.value);
188 }
189 else if (isBooleanValue(value) || isStringValue(value)) {
190 argObj[name.value] = value.value;
191 }
192 else if (isObjectValue(value)) {
193 var nestedArgObj_1 = {};
194 value.fields.map(function (obj) {
195 return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables);
196 });
197 argObj[name.value] = nestedArgObj_1;
198 }
199 else if (isVariable(value)) {
200 var variableValue = (variables || {})[value.name.value];
201 argObj[name.value] = variableValue;
202 }
203 else if (isListValue(value)) {
204 argObj[name.value] = value.values.map(function (listValue) {
205 var nestedArgArrayObj = {};
206 valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
207 return nestedArgArrayObj[name.value];
208 });
209 }
210 else if (isEnumValue(value)) {
211 argObj[name.value] = value.value;
212 }
213 else if (isNullValue(value)) {
214 argObj[name.value] = null;
215 }
216 else {
217 throw __DEV__ ? new globals.InvariantError("The inline argument \"".concat(name.value, "\" of kind \"").concat(value.kind, "\"") +
218 'is not supported. Use variables instead of inline arguments to ' +
219 'overcome this limitation.') : new globals.InvariantError(54);
220 }
221}
222function storeKeyNameFromField(field, variables) {
223 var directivesObj = null;
224 if (field.directives) {
225 directivesObj = {};
226 field.directives.forEach(function (directive) {
227 directivesObj[directive.name.value] = {};
228 if (directive.arguments) {
229 directive.arguments.forEach(function (_a) {
230 var name = _a.name, value = _a.value;
231 return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables);
232 });
233 }
234 });
235 }
236 var argObj = null;
237 if (field.arguments && field.arguments.length) {
238 argObj = {};
239 field.arguments.forEach(function (_a) {
240 var name = _a.name, value = _a.value;
241 return valueToObjectRepresentation(argObj, name, value, variables);
242 });
243 }
244 return getStoreKeyName(field.name.value, argObj, directivesObj);
245}
246var KNOWN_DIRECTIVES = [
247 'connection',
248 'include',
249 'skip',
250 'client',
251 'rest',
252 'export',
253];
254var getStoreKeyName = Object.assign(function (fieldName, args, directives) {
255 if (args &&
256 directives &&
257 directives['connection'] &&
258 directives['connection']['key']) {
259 if (directives['connection']['filter'] &&
260 directives['connection']['filter'].length > 0) {
261 var filterKeys = directives['connection']['filter']
262 ? directives['connection']['filter']
263 : [];
264 filterKeys.sort();
265 var filteredArgs_1 = {};
266 filterKeys.forEach(function (key) {
267 filteredArgs_1[key] = args[key];
268 });
269 return "".concat(directives['connection']['key'], "(").concat(stringify(filteredArgs_1), ")");
270 }
271 else {
272 return directives['connection']['key'];
273 }
274 }
275 var completeFieldName = fieldName;
276 if (args) {
277 var stringifiedArgs = stringify(args);
278 completeFieldName += "(".concat(stringifiedArgs, ")");
279 }
280 if (directives) {
281 Object.keys(directives).forEach(function (key) {
282 if (KNOWN_DIRECTIVES.indexOf(key) !== -1)
283 return;
284 if (directives[key] && Object.keys(directives[key]).length) {
285 completeFieldName += "@".concat(key, "(").concat(stringify(directives[key]), ")");
286 }
287 else {
288 completeFieldName += "@".concat(key);
289 }
290 });
291 }
292 return completeFieldName;
293}, {
294 setStringify: function (s) {
295 var previous = stringify;
296 stringify = s;
297 return previous;
298 },
299});
300var stringify = function defaultStringify(value) {
301 return JSON.stringify(value, stringifyReplacer);
302};
303function stringifyReplacer(_key, value) {
304 if (isNonNullObject(value) && !Array.isArray(value)) {
305 value = Object.keys(value).sort().reduce(function (copy, key) {
306 copy[key] = value[key];
307 return copy;
308 }, {});
309 }
310 return value;
311}
312function argumentsObjectFromField(field, variables) {
313 if (field.arguments && field.arguments.length) {
314 var argObj_1 = {};
315 field.arguments.forEach(function (_a) {
316 var name = _a.name, value = _a.value;
317 return valueToObjectRepresentation(argObj_1, name, value, variables);
318 });
319 return argObj_1;
320 }
321 return null;
322}
323function resultKeyNameFromField(field) {
324 return field.alias ? field.alias.value : field.name.value;
325}
326function getTypenameFromResult(result, selectionSet, fragmentMap) {
327 if (typeof result.__typename === 'string') {
328 return result.__typename;
329 }
330 for (var _i = 0, _a = selectionSet.selections; _i < _a.length; _i++) {
331 var selection = _a[_i];
332 if (isField(selection)) {
333 if (selection.name.value === '__typename') {
334 return result[resultKeyNameFromField(selection)];
335 }
336 }
337 else {
338 var typename = getTypenameFromResult(result, getFragmentFromSelection(selection, fragmentMap).selectionSet, fragmentMap);
339 if (typeof typename === 'string') {
340 return typename;
341 }
342 }
343 }
344}
345function isField(selection) {
346 return selection.kind === 'Field';
347}
348function isInlineFragment(selection) {
349 return selection.kind === 'InlineFragment';
350}
351
352function checkDocument(doc) {
353 __DEV__ ? globals.invariant(doc && doc.kind === 'Document', "Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql") : globals.invariant(doc && doc.kind === 'Document', 46);
354 var operations = doc.definitions
355 .filter(function (d) { return d.kind !== 'FragmentDefinition'; })
356 .map(function (definition) {
357 if (definition.kind !== 'OperationDefinition') {
358 throw __DEV__ ? new globals.InvariantError("Schema type definitions not allowed in queries. Found: \"".concat(definition.kind, "\"")) : new globals.InvariantError(47);
359 }
360 return definition;
361 });
362 __DEV__ ? globals.invariant(operations.length <= 1, "Ambiguous GraphQL document: contains ".concat(operations.length, " operations")) : globals.invariant(operations.length <= 1, 48);
363 return doc;
364}
365function getOperationDefinition(doc) {
366 checkDocument(doc);
367 return doc.definitions.filter(function (definition) { return definition.kind === 'OperationDefinition'; })[0];
368}
369function getOperationName(doc) {
370 return (doc.definitions
371 .filter(function (definition) {
372 return definition.kind === 'OperationDefinition' && definition.name;
373 })
374 .map(function (x) { return x.name.value; })[0] || null);
375}
376function getFragmentDefinitions(doc) {
377 return doc.definitions.filter(function (definition) { return definition.kind === 'FragmentDefinition'; });
378}
379function getQueryDefinition(doc) {
380 var queryDef = getOperationDefinition(doc);
381 __DEV__ ? globals.invariant(queryDef && queryDef.operation === 'query', 'Must contain a query definition.') : globals.invariant(queryDef && queryDef.operation === 'query', 49);
382 return queryDef;
383}
384function getFragmentDefinition(doc) {
385 __DEV__ ? globals.invariant(doc.kind === 'Document', "Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql") : globals.invariant(doc.kind === 'Document', 50);
386 __DEV__ ? globals.invariant(doc.definitions.length <= 1, 'Fragment must have exactly one definition.') : globals.invariant(doc.definitions.length <= 1, 51);
387 var fragmentDef = doc.definitions[0];
388 __DEV__ ? globals.invariant(fragmentDef.kind === 'FragmentDefinition', 'Must be a fragment definition.') : globals.invariant(fragmentDef.kind === 'FragmentDefinition', 52);
389 return fragmentDef;
390}
391function getMainDefinition(queryDoc) {
392 checkDocument(queryDoc);
393 var fragmentDefinition;
394 for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {
395 var definition = _a[_i];
396 if (definition.kind === 'OperationDefinition') {
397 var operation = definition.operation;
398 if (operation === 'query' ||
399 operation === 'mutation' ||
400 operation === 'subscription') {
401 return definition;
402 }
403 }
404 if (definition.kind === 'FragmentDefinition' && !fragmentDefinition) {
405 fragmentDefinition = definition;
406 }
407 }
408 if (fragmentDefinition) {
409 return fragmentDefinition;
410 }
411 throw __DEV__ ? new globals.InvariantError('Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.') : new globals.InvariantError(53);
412}
413function getDefaultValues(definition) {
414 var defaultValues = Object.create(null);
415 var defs = definition && definition.variableDefinitions;
416 if (defs && defs.length) {
417 defs.forEach(function (def) {
418 if (def.defaultValue) {
419 valueToObjectRepresentation(defaultValues, def.variable.name, def.defaultValue);
420 }
421 });
422 }
423 return defaultValues;
424}
425
426function filterInPlace(array, test, context) {
427 var target = 0;
428 array.forEach(function (elem, i) {
429 if (test.call(this, elem, i, array)) {
430 array[target++] = elem;
431 }
432 }, context);
433 array.length = target;
434 return array;
435}
436
437var TYPENAME_FIELD = {
438 kind: 'Field',
439 name: {
440 kind: 'Name',
441 value: '__typename',
442 },
443};
444function isEmpty(op, fragmentMap) {
445 return !op || op.selectionSet.selections.every(function (selection) { return selection.kind === 'FragmentSpread' &&
446 isEmpty(fragmentMap[selection.name.value], fragmentMap); });
447}
448function nullIfDocIsEmpty(doc) {
449 return isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))
450 ? null
451 : doc;
452}
453function getDirectiveMatcher(directives) {
454 return function directiveMatcher(directive) {
455 return directives.some(function (dir) {
456 return (dir.name && dir.name === directive.name.value) ||
457 (dir.test && dir.test(directive));
458 });
459 };
460}
461function removeDirectivesFromDocument(directives, doc) {
462 var variablesInUse = Object.create(null);
463 var variablesToRemove = [];
464 var fragmentSpreadsInUse = Object.create(null);
465 var fragmentSpreadsToRemove = [];
466 var modifiedDoc = nullIfDocIsEmpty(graphql.visit(doc, {
467 Variable: {
468 enter: function (node, _key, parent) {
469 if (parent.kind !== 'VariableDefinition') {
470 variablesInUse[node.name.value] = true;
471 }
472 },
473 },
474 Field: {
475 enter: function (node) {
476 if (directives && node.directives) {
477 var shouldRemoveField = directives.some(function (directive) { return directive.remove; });
478 if (shouldRemoveField &&
479 node.directives &&
480 node.directives.some(getDirectiveMatcher(directives))) {
481 if (node.arguments) {
482 node.arguments.forEach(function (arg) {
483 if (arg.value.kind === 'Variable') {
484 variablesToRemove.push({
485 name: arg.value.name.value,
486 });
487 }
488 });
489 }
490 if (node.selectionSet) {
491 getAllFragmentSpreadsFromSelectionSet(node.selectionSet).forEach(function (frag) {
492 fragmentSpreadsToRemove.push({
493 name: frag.name.value,
494 });
495 });
496 }
497 return null;
498 }
499 }
500 },
501 },
502 FragmentSpread: {
503 enter: function (node) {
504 fragmentSpreadsInUse[node.name.value] = true;
505 },
506 },
507 Directive: {
508 enter: function (node) {
509 if (getDirectiveMatcher(directives)(node)) {
510 return null;
511 }
512 },
513 },
514 }));
515 if (modifiedDoc &&
516 filterInPlace(variablesToRemove, function (v) { return !!v.name && !variablesInUse[v.name]; }).length) {
517 modifiedDoc = removeArgumentsFromDocument(variablesToRemove, modifiedDoc);
518 }
519 if (modifiedDoc &&
520 filterInPlace(fragmentSpreadsToRemove, function (fs) { return !!fs.name && !fragmentSpreadsInUse[fs.name]; })
521 .length) {
522 modifiedDoc = removeFragmentSpreadFromDocument(fragmentSpreadsToRemove, modifiedDoc);
523 }
524 return modifiedDoc;
525}
526var addTypenameToDocument = Object.assign(function (doc) {
527 return graphql.visit(doc, {
528 SelectionSet: {
529 enter: function (node, _key, parent) {
530 if (parent &&
531 parent.kind === 'OperationDefinition') {
532 return;
533 }
534 var selections = node.selections;
535 if (!selections) {
536 return;
537 }
538 var skip = selections.some(function (selection) {
539 return (isField(selection) &&
540 (selection.name.value === '__typename' ||
541 selection.name.value.lastIndexOf('__', 0) === 0));
542 });
543 if (skip) {
544 return;
545 }
546 var field = parent;
547 if (isField(field) &&
548 field.directives &&
549 field.directives.some(function (d) { return d.name.value === 'export'; })) {
550 return;
551 }
552 return tslib.__assign(tslib.__assign({}, node), { selections: tslib.__spreadArray(tslib.__spreadArray([], selections, true), [TYPENAME_FIELD], false) });
553 },
554 },
555 });
556}, {
557 added: function (field) {
558 return field === TYPENAME_FIELD;
559 },
560});
561var connectionRemoveConfig = {
562 test: function (directive) {
563 var willRemove = directive.name.value === 'connection';
564 if (willRemove) {
565 if (!directive.arguments ||
566 !directive.arguments.some(function (arg) { return arg.name.value === 'key'; })) {
567 __DEV__ && globals.invariant.warn('Removing an @connection directive even though it does not have a key. ' +
568 'You may want to use the key parameter to specify a store key.');
569 }
570 }
571 return willRemove;
572 },
573};
574function removeConnectionDirectiveFromDocument(doc) {
575 return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));
576}
577function getArgumentMatcher(config) {
578 return function argumentMatcher(argument) {
579 return config.some(function (aConfig) {
580 return argument.value &&
581 argument.value.kind === 'Variable' &&
582 argument.value.name &&
583 (aConfig.name === argument.value.name.value ||
584 (aConfig.test && aConfig.test(argument)));
585 });
586 };
587}
588function removeArgumentsFromDocument(config, doc) {
589 var argMatcher = getArgumentMatcher(config);
590 return nullIfDocIsEmpty(graphql.visit(doc, {
591 OperationDefinition: {
592 enter: function (node) {
593 return tslib.__assign(tslib.__assign({}, node), { variableDefinitions: node.variableDefinitions ? node.variableDefinitions.filter(function (varDef) {
594 return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });
595 }) : [] });
596 },
597 },
598 Field: {
599 enter: function (node) {
600 var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });
601 if (shouldRemoveField) {
602 var argMatchCount_1 = 0;
603 if (node.arguments) {
604 node.arguments.forEach(function (arg) {
605 if (argMatcher(arg)) {
606 argMatchCount_1 += 1;
607 }
608 });
609 }
610 if (argMatchCount_1 === 1) {
611 return null;
612 }
613 }
614 },
615 },
616 Argument: {
617 enter: function (node) {
618 if (argMatcher(node)) {
619 return null;
620 }
621 },
622 },
623 }));
624}
625function removeFragmentSpreadFromDocument(config, doc) {
626 function enter(node) {
627 if (config.some(function (def) { return def.name === node.name.value; })) {
628 return null;
629 }
630 }
631 return nullIfDocIsEmpty(graphql.visit(doc, {
632 FragmentSpread: { enter: enter },
633 FragmentDefinition: { enter: enter },
634 }));
635}
636function getAllFragmentSpreadsFromSelectionSet(selectionSet) {
637 var allFragments = [];
638 selectionSet.selections.forEach(function (selection) {
639 if ((isField(selection) || isInlineFragment(selection)) &&
640 selection.selectionSet) {
641 getAllFragmentSpreadsFromSelectionSet(selection.selectionSet).forEach(function (frag) { return allFragments.push(frag); });
642 }
643 else if (selection.kind === 'FragmentSpread') {
644 allFragments.push(selection);
645 }
646 });
647 return allFragments;
648}
649function buildQueryFromSelectionSet(document) {
650 var definition = getMainDefinition(document);
651 var definitionOperation = definition.operation;
652 if (definitionOperation === 'query') {
653 return document;
654 }
655 var modifiedDoc = graphql.visit(document, {
656 OperationDefinition: {
657 enter: function (node) {
658 return tslib.__assign(tslib.__assign({}, node), { operation: 'query' });
659 },
660 },
661 });
662 return modifiedDoc;
663}
664function removeClientSetsFromDocument(document) {
665 checkDocument(document);
666 var modifiedDoc = removeDirectivesFromDocument([
667 {
668 test: function (directive) { return directive.name.value === 'client'; },
669 remove: true,
670 },
671 ], document);
672 if (modifiedDoc) {
673 modifiedDoc = graphql.visit(modifiedDoc, {
674 FragmentDefinition: {
675 enter: function (node) {
676 if (node.selectionSet) {
677 var isTypenameOnly = node.selectionSet.selections.every(function (selection) {
678 return isField(selection) && selection.name.value === '__typename';
679 });
680 if (isTypenameOnly) {
681 return null;
682 }
683 }
684 },
685 },
686 });
687 }
688 return modifiedDoc;
689}
690
691var hasOwnProperty = Object.prototype.hasOwnProperty;
692function mergeDeep() {
693 var sources = [];
694 for (var _i = 0; _i < arguments.length; _i++) {
695 sources[_i] = arguments[_i];
696 }
697 return mergeDeepArray(sources);
698}
699function mergeDeepArray(sources) {
700 var target = sources[0] || {};
701 var count = sources.length;
702 if (count > 1) {
703 var merger = new DeepMerger();
704 for (var i = 1; i < count; ++i) {
705 target = merger.merge(target, sources[i]);
706 }
707 }
708 return target;
709}
710var defaultReconciler = function (target, source, property) {
711 return this.merge(target[property], source[property]);
712};
713var DeepMerger = (function () {
714 function DeepMerger(reconciler) {
715 if (reconciler === void 0) { reconciler = defaultReconciler; }
716 this.reconciler = reconciler;
717 this.isObject = isNonNullObject;
718 this.pastCopies = new Set();
719 }
720 DeepMerger.prototype.merge = function (target, source) {
721 var _this = this;
722 var context = [];
723 for (var _i = 2; _i < arguments.length; _i++) {
724 context[_i - 2] = arguments[_i];
725 }
726 if (isNonNullObject(source) && isNonNullObject(target)) {
727 Object.keys(source).forEach(function (sourceKey) {
728 if (hasOwnProperty.call(target, sourceKey)) {
729 var targetValue = target[sourceKey];
730 if (source[sourceKey] !== targetValue) {
731 var result = _this.reconciler.apply(_this, tslib.__spreadArray([target, source, sourceKey], context, false));
732 if (result !== targetValue) {
733 target = _this.shallowCopyForMerge(target);
734 target[sourceKey] = result;
735 }
736 }
737 }
738 else {
739 target = _this.shallowCopyForMerge(target);
740 target[sourceKey] = source[sourceKey];
741 }
742 });
743 return target;
744 }
745 return source;
746 };
747 DeepMerger.prototype.shallowCopyForMerge = function (value) {
748 if (isNonNullObject(value)) {
749 if (!this.pastCopies.has(value)) {
750 if (Array.isArray(value)) {
751 value = value.slice(0);
752 }
753 else {
754 value = tslib.__assign({ __proto__: Object.getPrototypeOf(value) }, value);
755 }
756 this.pastCopies.add(value);
757 }
758 }
759 return value;
760 };
761 return DeepMerger;
762}());
763
764function concatPagination(keyArgs) {
765 if (keyArgs === void 0) { keyArgs = false; }
766 return {
767 keyArgs: keyArgs,
768 merge: function (existing, incoming) {
769 return existing ? tslib.__spreadArray(tslib.__spreadArray([], existing, true), incoming, true) : incoming;
770 },
771 };
772}
773function offsetLimitPagination(keyArgs) {
774 if (keyArgs === void 0) { keyArgs = false; }
775 return {
776 keyArgs: keyArgs,
777 merge: function (existing, incoming, _a) {
778 var args = _a.args;
779 var merged = existing ? existing.slice(0) : [];
780 if (incoming) {
781 if (args) {
782 var _b = args.offset, offset = _b === void 0 ? 0 : _b;
783 for (var i = 0; i < incoming.length; ++i) {
784 merged[offset + i] = incoming[i];
785 }
786 }
787 else {
788 merged.push.apply(merged, incoming);
789 }
790 }
791 return merged;
792 },
793 };
794}
795function relayStylePagination(keyArgs) {
796 if (keyArgs === void 0) { keyArgs = false; }
797 return {
798 keyArgs: keyArgs,
799 read: function (existing, _a) {
800 var canRead = _a.canRead, readField = _a.readField;
801 if (!existing)
802 return existing;
803 var edges = [];
804 var firstEdgeCursor = "";
805 var lastEdgeCursor = "";
806 existing.edges.forEach(function (edge) {
807 if (canRead(readField("node", edge))) {
808 edges.push(edge);
809 if (edge.cursor) {
810 firstEdgeCursor = firstEdgeCursor || edge.cursor || "";
811 lastEdgeCursor = edge.cursor || lastEdgeCursor;
812 }
813 }
814 });
815 var _b = existing.pageInfo || {}, startCursor = _b.startCursor, endCursor = _b.endCursor;
816 return tslib.__assign(tslib.__assign({}, getExtras(existing)), { edges: edges, pageInfo: tslib.__assign(tslib.__assign({}, existing.pageInfo), { startCursor: startCursor || firstEdgeCursor, endCursor: endCursor || lastEdgeCursor }) });
817 },
818 merge: function (existing, incoming, _a) {
819 var args = _a.args, isReference = _a.isReference, readField = _a.readField;
820 if (!existing) {
821 existing = makeEmptyData();
822 }
823 if (!incoming) {
824 return existing;
825 }
826 var incomingEdges = incoming.edges ? incoming.edges.map(function (edge) {
827 if (isReference(edge = tslib.__assign({}, edge))) {
828 edge.cursor = readField("cursor", edge);
829 }
830 return edge;
831 }) : [];
832 if (incoming.pageInfo) {
833 var pageInfo_1 = incoming.pageInfo;
834 var startCursor = pageInfo_1.startCursor, endCursor = pageInfo_1.endCursor;
835 var firstEdge = incomingEdges[0];
836 var lastEdge = incomingEdges[incomingEdges.length - 1];
837 if (firstEdge && startCursor) {
838 firstEdge.cursor = startCursor;
839 }
840 if (lastEdge && endCursor) {
841 lastEdge.cursor = endCursor;
842 }
843 var firstCursor = firstEdge && firstEdge.cursor;
844 if (firstCursor && !startCursor) {
845 incoming = mergeDeep(incoming, {
846 pageInfo: {
847 startCursor: firstCursor,
848 },
849 });
850 }
851 var lastCursor = lastEdge && lastEdge.cursor;
852 if (lastCursor && !endCursor) {
853 incoming = mergeDeep(incoming, {
854 pageInfo: {
855 endCursor: lastCursor,
856 },
857 });
858 }
859 }
860 var prefix = existing.edges;
861 var suffix = [];
862 if (args && args.after) {
863 var index = prefix.findIndex(function (edge) { return edge.cursor === args.after; });
864 if (index >= 0) {
865 prefix = prefix.slice(0, index + 1);
866 }
867 }
868 else if (args && args.before) {
869 var index = prefix.findIndex(function (edge) { return edge.cursor === args.before; });
870 suffix = index < 0 ? prefix : prefix.slice(index);
871 prefix = [];
872 }
873 else if (incoming.edges) {
874 prefix = [];
875 }
876 var edges = tslib.__spreadArray(tslib.__spreadArray(tslib.__spreadArray([], prefix, true), incomingEdges, true), suffix, true);
877 var pageInfo = tslib.__assign(tslib.__assign({}, incoming.pageInfo), existing.pageInfo);
878 if (incoming.pageInfo) {
879 var _b = incoming.pageInfo, hasPreviousPage = _b.hasPreviousPage, hasNextPage = _b.hasNextPage, startCursor = _b.startCursor, endCursor = _b.endCursor, extras = tslib.__rest(_b, ["hasPreviousPage", "hasNextPage", "startCursor", "endCursor"]);
880 Object.assign(pageInfo, extras);
881 if (!prefix.length) {
882 if (void 0 !== hasPreviousPage)
883 pageInfo.hasPreviousPage = hasPreviousPage;
884 if (void 0 !== startCursor)
885 pageInfo.startCursor = startCursor;
886 }
887 if (!suffix.length) {
888 if (void 0 !== hasNextPage)
889 pageInfo.hasNextPage = hasNextPage;
890 if (void 0 !== endCursor)
891 pageInfo.endCursor = endCursor;
892 }
893 }
894 return tslib.__assign(tslib.__assign(tslib.__assign({}, getExtras(existing)), getExtras(incoming)), { edges: edges, pageInfo: pageInfo });
895 },
896 };
897}
898var getExtras = function (obj) { return tslib.__rest(obj, notExtras); };
899var notExtras = ["edges", "pageInfo"];
900function makeEmptyData() {
901 return {
902 edges: [],
903 pageInfo: {
904 hasPreviousPage: false,
905 hasNextPage: true,
906 startCursor: "",
907 endCursor: "",
908 },
909 };
910}
911
912var toString = Object.prototype.toString;
913function cloneDeep(value) {
914 return cloneDeepHelper(value);
915}
916function cloneDeepHelper(val, seen) {
917 switch (toString.call(val)) {
918 case "[object Array]": {
919 seen = seen || new Map;
920 if (seen.has(val))
921 return seen.get(val);
922 var copy_1 = val.slice(0);
923 seen.set(val, copy_1);
924 copy_1.forEach(function (child, i) {
925 copy_1[i] = cloneDeepHelper(child, seen);
926 });
927 return copy_1;
928 }
929 case "[object Object]": {
930 seen = seen || new Map;
931 if (seen.has(val))
932 return seen.get(val);
933 var copy_2 = Object.create(Object.getPrototypeOf(val));
934 seen.set(val, copy_2);
935 Object.keys(val).forEach(function (key) {
936 copy_2[key] = cloneDeepHelper(val[key], seen);
937 });
938 return copy_2;
939 }
940 default:
941 return val;
942 }
943}
944
945function deepFreeze(value) {
946 var workSet = new Set([value]);
947 workSet.forEach(function (obj) {
948 if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {
949 Object.getOwnPropertyNames(obj).forEach(function (name) {
950 if (isNonNullObject(obj[name]))
951 workSet.add(obj[name]);
952 });
953 }
954 });
955 return value;
956}
957function shallowFreeze(obj) {
958 if (__DEV__ && !Object.isFrozen(obj)) {
959 try {
960 Object.freeze(obj);
961 }
962 catch (e) {
963 if (e instanceof TypeError)
964 return null;
965 throw e;
966 }
967 }
968 return obj;
969}
970function maybeDeepFreeze(obj) {
971 if (__DEV__) {
972 deepFreeze(obj);
973 }
974 return obj;
975}
976
977function iterateObserversSafely(observers, method, argument) {
978 var observersWithMethod = [];
979 observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });
980 observersWithMethod.forEach(function (obs) { return obs[method](argument); });
981}
982
983function asyncMap(observable, mapFn, catchFn) {
984 return new zenObservableTs.Observable(function (observer) {
985 var next = observer.next, error = observer.error, complete = observer.complete;
986 var activeCallbackCount = 0;
987 var completed = false;
988 var promiseQueue = {
989 then: function (callback) {
990 return new Promise(function (resolve) { return resolve(callback()); });
991 },
992 };
993 function makeCallback(examiner, delegate) {
994 if (examiner) {
995 return function (arg) {
996 ++activeCallbackCount;
997 var both = function () { return examiner(arg); };
998 promiseQueue = promiseQueue.then(both, both).then(function (result) {
999 --activeCallbackCount;
1000 next && next.call(observer, result);
1001 if (completed) {
1002 handler.complete();
1003 }
1004 }, function (error) {
1005 --activeCallbackCount;
1006 throw error;
1007 }).catch(function (caught) {
1008 error && error.call(observer, caught);
1009 });
1010 };
1011 }
1012 else {
1013 return function (arg) { return delegate && delegate.call(observer, arg); };
1014 }
1015 }
1016 var handler = {
1017 next: makeCallback(mapFn, next),
1018 error: makeCallback(catchFn, error),
1019 complete: function () {
1020 completed = true;
1021 if (!activeCallbackCount) {
1022 complete && complete.call(observer);
1023 }
1024 },
1025 };
1026 var sub = observable.subscribe(handler);
1027 return function () { return sub.unsubscribe(); };
1028 });
1029}
1030
1031var canUseWeakMap = typeof WeakMap === 'function' &&
1032 globals.maybe(function () { return navigator.product; }) !== 'ReactNative';
1033var canUseWeakSet = typeof WeakSet === 'function';
1034var canUseSymbol = typeof Symbol === 'function' &&
1035 typeof Symbol.for === 'function';
1036var canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;
1037var canUseDOM = typeof globals.maybe(function () { return window.document.createElement; }) === "function";
1038var usingJSDOM = globals.maybe(function () { return navigator.userAgent.indexOf("jsdom") >= 0; }) || false;
1039var canUseLayoutEffect = canUseDOM && !usingJSDOM;
1040
1041function fixObservableSubclass(subclass) {
1042 function set(key) {
1043 Object.defineProperty(subclass, key, { value: zenObservableTs.Observable });
1044 }
1045 if (canUseSymbol && Symbol.species) {
1046 set(Symbol.species);
1047 }
1048 set("@@species");
1049 return subclass;
1050}
1051
1052function isPromiseLike(value) {
1053 return value && typeof value.then === "function";
1054}
1055var Concast = (function (_super) {
1056 tslib.__extends(Concast, _super);
1057 function Concast(sources) {
1058 var _this = _super.call(this, function (observer) {
1059 _this.addObserver(observer);
1060 return function () { return _this.removeObserver(observer); };
1061 }) || this;
1062 _this.observers = new Set();
1063 _this.promise = new Promise(function (resolve, reject) {
1064 _this.resolve = resolve;
1065 _this.reject = reject;
1066 });
1067 _this.handlers = {
1068 next: function (result) {
1069 if (_this.sub !== null) {
1070 _this.latest = ["next", result];
1071 _this.notify("next", result);
1072 iterateObserversSafely(_this.observers, "next", result);
1073 }
1074 },
1075 error: function (error) {
1076 var sub = _this.sub;
1077 if (sub !== null) {
1078 if (sub)
1079 setTimeout(function () { return sub.unsubscribe(); });
1080 _this.sub = null;
1081 _this.latest = ["error", error];
1082 _this.reject(error);
1083 _this.notify("error", error);
1084 iterateObserversSafely(_this.observers, "error", error);
1085 }
1086 },
1087 complete: function () {
1088 var sub = _this.sub;
1089 if (sub !== null) {
1090 var value = _this.sources.shift();
1091 if (!value) {
1092 if (sub)
1093 setTimeout(function () { return sub.unsubscribe(); });
1094 _this.sub = null;
1095 if (_this.latest &&
1096 _this.latest[0] === "next") {
1097 _this.resolve(_this.latest[1]);
1098 }
1099 else {
1100 _this.resolve();
1101 }
1102 _this.notify("complete");
1103 iterateObserversSafely(_this.observers, "complete");
1104 }
1105 else if (isPromiseLike(value)) {
1106 value.then(function (obs) { return _this.sub = obs.subscribe(_this.handlers); });
1107 }
1108 else {
1109 _this.sub = value.subscribe(_this.handlers);
1110 }
1111 }
1112 },
1113 };
1114 _this.nextResultListeners = new Set();
1115 _this.cancel = function (reason) {
1116 _this.reject(reason);
1117 _this.sources = [];
1118 _this.handlers.complete();
1119 };
1120 _this.promise.catch(function (_) { });
1121 if (typeof sources === "function") {
1122 sources = [new zenObservableTs.Observable(sources)];
1123 }
1124 if (isPromiseLike(sources)) {
1125 sources.then(function (iterable) { return _this.start(iterable); }, _this.handlers.error);
1126 }
1127 else {
1128 _this.start(sources);
1129 }
1130 return _this;
1131 }
1132 Concast.prototype.start = function (sources) {
1133 if (this.sub !== void 0)
1134 return;
1135 this.sources = Array.from(sources);
1136 this.handlers.complete();
1137 };
1138 Concast.prototype.deliverLastMessage = function (observer) {
1139 if (this.latest) {
1140 var nextOrError = this.latest[0];
1141 var method = observer[nextOrError];
1142 if (method) {
1143 method.call(observer, this.latest[1]);
1144 }
1145 if (this.sub === null &&
1146 nextOrError === "next" &&
1147 observer.complete) {
1148 observer.complete();
1149 }
1150 }
1151 };
1152 Concast.prototype.addObserver = function (observer) {
1153 if (!this.observers.has(observer)) {
1154 this.deliverLastMessage(observer);
1155 this.observers.add(observer);
1156 }
1157 };
1158 Concast.prototype.removeObserver = function (observer) {
1159 if (this.observers.delete(observer) &&
1160 this.observers.size < 1) {
1161 this.handlers.complete();
1162 }
1163 };
1164 Concast.prototype.notify = function (method, arg) {
1165 var nextResultListeners = this.nextResultListeners;
1166 if (nextResultListeners.size) {
1167 this.nextResultListeners = new Set;
1168 nextResultListeners.forEach(function (listener) { return listener(method, arg); });
1169 }
1170 };
1171 Concast.prototype.beforeNext = function (callback) {
1172 var called = false;
1173 this.nextResultListeners.add(function (method, arg) {
1174 if (!called) {
1175 called = true;
1176 callback(method, arg);
1177 }
1178 });
1179 };
1180 return Concast;
1181}(zenObservableTs.Observable));
1182fixObservableSubclass(Concast);
1183
1184function isNonEmptyArray(value) {
1185 return Array.isArray(value) && value.length > 0;
1186}
1187
1188function graphQLResultHasError(result) {
1189 return (result.errors && result.errors.length > 0) || false;
1190}
1191
1192function compact() {
1193 var objects = [];
1194 for (var _i = 0; _i < arguments.length; _i++) {
1195 objects[_i] = arguments[_i];
1196 }
1197 var result = Object.create(null);
1198 objects.forEach(function (obj) {
1199 if (!obj)
1200 return;
1201 Object.keys(obj).forEach(function (key) {
1202 var value = obj[key];
1203 if (value !== void 0) {
1204 result[key] = value;
1205 }
1206 });
1207 });
1208 return result;
1209}
1210
1211var prefixCounts = new Map();
1212function makeUniqueId(prefix) {
1213 var count = prefixCounts.get(prefix) || 1;
1214 prefixCounts.set(prefix, count + 1);
1215 return "".concat(prefix, ":").concat(count, ":").concat(Math.random().toString(36).slice(2));
1216}
1217
1218function stringifyForDisplay(value) {
1219 var undefId = makeUniqueId("stringifyForDisplay");
1220 return JSON.stringify(value, function (key, value) {
1221 return value === void 0 ? undefId : value;
1222 }).split(JSON.stringify(undefId)).join("<undefined>");
1223}
1224
1225function mergeOptions(defaults, options) {
1226 return compact(defaults, options, options.variables && {
1227 variables: tslib.__assign(tslib.__assign({}, (defaults && defaults.variables)), options.variables),
1228 });
1229}
1230
1231exports.DEV = globals.DEV;
1232exports.maybe = globals.maybe;
1233exports.Observable = zenObservableTs.Observable;
1234exports.Concast = Concast;
1235exports.DeepMerger = DeepMerger;
1236exports.addTypenameToDocument = addTypenameToDocument;
1237exports.argumentsObjectFromField = argumentsObjectFromField;
1238exports.asyncMap = asyncMap;
1239exports.buildQueryFromSelectionSet = buildQueryFromSelectionSet;
1240exports.canUseAsyncIteratorSymbol = canUseAsyncIteratorSymbol;
1241exports.canUseDOM = canUseDOM;
1242exports.canUseLayoutEffect = canUseLayoutEffect;
1243exports.canUseSymbol = canUseSymbol;
1244exports.canUseWeakMap = canUseWeakMap;
1245exports.canUseWeakSet = canUseWeakSet;
1246exports.checkDocument = checkDocument;
1247exports.cloneDeep = cloneDeep;
1248exports.compact = compact;
1249exports.concatPagination = concatPagination;
1250exports.createFragmentMap = createFragmentMap;
1251exports.fixObservableSubclass = fixObservableSubclass;
1252exports.getDefaultValues = getDefaultValues;
1253exports.getDirectiveNames = getDirectiveNames;
1254exports.getFragmentDefinition = getFragmentDefinition;
1255exports.getFragmentDefinitions = getFragmentDefinitions;
1256exports.getFragmentFromSelection = getFragmentFromSelection;
1257exports.getFragmentQueryDocument = getFragmentQueryDocument;
1258exports.getInclusionDirectives = getInclusionDirectives;
1259exports.getMainDefinition = getMainDefinition;
1260exports.getOperationDefinition = getOperationDefinition;
1261exports.getOperationName = getOperationName;
1262exports.getQueryDefinition = getQueryDefinition;
1263exports.getStoreKeyName = getStoreKeyName;
1264exports.getTypenameFromResult = getTypenameFromResult;
1265exports.graphQLResultHasError = graphQLResultHasError;
1266exports.hasAllDirectives = hasAllDirectives;
1267exports.hasAnyDirectives = hasAnyDirectives;
1268exports.hasClientExports = hasClientExports;
1269exports.hasDirectives = hasDirectives;
1270exports.isDocumentNode = isDocumentNode;
1271exports.isField = isField;
1272exports.isInlineFragment = isInlineFragment;
1273exports.isNonEmptyArray = isNonEmptyArray;
1274exports.isNonNullObject = isNonNullObject;
1275exports.isReference = isReference;
1276exports.iterateObserversSafely = iterateObserversSafely;
1277exports.makeReference = makeReference;
1278exports.makeUniqueId = makeUniqueId;
1279exports.maybeDeepFreeze = maybeDeepFreeze;
1280exports.mergeDeep = mergeDeep;
1281exports.mergeDeepArray = mergeDeepArray;
1282exports.mergeOptions = mergeOptions;
1283exports.offsetLimitPagination = offsetLimitPagination;
1284exports.relayStylePagination = relayStylePagination;
1285exports.removeArgumentsFromDocument = removeArgumentsFromDocument;
1286exports.removeClientSetsFromDocument = removeClientSetsFromDocument;
1287exports.removeConnectionDirectiveFromDocument = removeConnectionDirectiveFromDocument;
1288exports.removeDirectivesFromDocument = removeDirectivesFromDocument;
1289exports.removeFragmentSpreadFromDocument = removeFragmentSpreadFromDocument;
1290exports.resultKeyNameFromField = resultKeyNameFromField;
1291exports.shouldInclude = shouldInclude;
1292exports.storeKeyNameFromField = storeKeyNameFromField;
1293exports.stringifyForDisplay = stringifyForDisplay;
1294exports.valueToObjectRepresentation = valueToObjectRepresentation;
1295//# sourceMappingURL=utilities.cjs.map