UNPKG

112 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var globals = require('../utilities/globals');
6var tslib = require('tslib');
7var optimism = require('optimism');
8var utilities = require('../utilities');
9var caches = require('@wry/caches');
10var equal = require('@wry/equality');
11var trie = require('@wry/trie');
12var graphql = require('graphql');
13
14function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
15
16var equal__default = /*#__PURE__*/_interopDefaultLegacy(equal);
17
18var getInMemoryCacheMemoryInternals = globalThis.__DEV__ !== false ?
19 _getInMemoryCacheMemoryInternals
20 : undefined;
21var getApolloCacheMemoryInternals = globalThis.__DEV__ !== false ?
22 _getApolloCacheMemoryInternals
23 : undefined;
24function _getApolloCacheMemoryInternals() {
25 return {
26 cache: {
27 fragmentQueryDocuments: getWrapperInformation(this["getFragmentDoc"]),
28 },
29 };
30}
31function _getInMemoryCacheMemoryInternals() {
32 var fragments = this.config.fragments;
33 return tslib.__assign(tslib.__assign({}, _getApolloCacheMemoryInternals.apply(this)), { addTypenameDocumentTransform: transformInfo(this["addTypenameTransform"]), inMemoryCache: {
34 executeSelectionSet: getWrapperInformation(this["storeReader"]["executeSelectionSet"]),
35 executeSubSelectedArray: getWrapperInformation(this["storeReader"]["executeSubSelectedArray"]),
36 maybeBroadcastWatch: getWrapperInformation(this["maybeBroadcastWatch"]),
37 }, fragmentRegistry: {
38 findFragmentSpreads: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.findFragmentSpreads),
39 lookup: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.lookup),
40 transform: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.transform),
41 } });
42}
43function isWrapper(f) {
44 return !!f && "dirtyKey" in f;
45}
46function getWrapperInformation(f) {
47 return isWrapper(f) ? f.size : undefined;
48}
49function isDefined(value) {
50 return value != null;
51}
52function transformInfo(transform) {
53 return recurseTransformInfo(transform).map(function (cache) { return ({ cache: cache }); });
54}
55function recurseTransformInfo(transform) {
56 return transform ?
57 tslib.__spreadArray(tslib.__spreadArray([
58 getWrapperInformation(transform === null || transform === void 0 ? void 0 : transform["performWork"])
59 ], recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["left"]), true), recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["right"]), true).filter(isDefined)
60 : [];
61}
62
63function equalByQuery(query, _a, _b, variables) {
64 var aData = _a.data, aRest = tslib.__rest(_a, ["data"]);
65 var bData = _b.data, bRest = tslib.__rest(_b, ["data"]);
66 return (equal__default(aRest, bRest) &&
67 equalBySelectionSet(utilities.getMainDefinition(query).selectionSet, aData, bData, {
68 fragmentMap: utilities.createFragmentMap(utilities.getFragmentDefinitions(query)),
69 variables: variables,
70 }));
71}
72function equalBySelectionSet(selectionSet, aResult, bResult, context) {
73 if (aResult === bResult) {
74 return true;
75 }
76 var seenSelections = new Set();
77 return selectionSet.selections.every(function (selection) {
78 if (seenSelections.has(selection))
79 return true;
80 seenSelections.add(selection);
81 if (!utilities.shouldInclude(selection, context.variables))
82 return true;
83 if (selectionHasNonreactiveDirective(selection))
84 return true;
85 if (utilities.isField(selection)) {
86 var resultKey = utilities.resultKeyNameFromField(selection);
87 var aResultChild = aResult && aResult[resultKey];
88 var bResultChild = bResult && bResult[resultKey];
89 var childSelectionSet = selection.selectionSet;
90 if (!childSelectionSet) {
91 return equal__default(aResultChild, bResultChild);
92 }
93 var aChildIsArray = Array.isArray(aResultChild);
94 var bChildIsArray = Array.isArray(bResultChild);
95 if (aChildIsArray !== bChildIsArray)
96 return false;
97 if (aChildIsArray && bChildIsArray) {
98 var length_1 = aResultChild.length;
99 if (bResultChild.length !== length_1) {
100 return false;
101 }
102 for (var i = 0; i < length_1; ++i) {
103 if (!equalBySelectionSet(childSelectionSet, aResultChild[i], bResultChild[i], context)) {
104 return false;
105 }
106 }
107 return true;
108 }
109 return equalBySelectionSet(childSelectionSet, aResultChild, bResultChild, context);
110 }
111 else {
112 var fragment = utilities.getFragmentFromSelection(selection, context.fragmentMap);
113 if (fragment) {
114 if (selectionHasNonreactiveDirective(fragment))
115 return true;
116 return equalBySelectionSet(fragment.selectionSet,
117 aResult, bResult, context);
118 }
119 }
120 });
121}
122function selectionHasNonreactiveDirective(selection) {
123 return (!!selection.directives && selection.directives.some(directiveIsNonreactive));
124}
125function directiveIsNonreactive(dir) {
126 return dir.name.value === "nonreactive";
127}
128
129var ApolloCache = (function () {
130 function ApolloCache() {
131 this.assumeImmutableResults = false;
132 this.getFragmentDoc = optimism.wrap(utilities.getFragmentQueryDocument, {
133 max: utilities.cacheSizes["cache.fragmentQueryDocuments"] ||
134 1000 ,
135 cache: caches.WeakCache,
136 });
137 }
138 ApolloCache.prototype.batch = function (options) {
139 var _this = this;
140 var optimisticId = typeof options.optimistic === "string" ? options.optimistic
141 : options.optimistic === false ? null
142 : void 0;
143 var updateResult;
144 this.performTransaction(function () { return (updateResult = options.update(_this)); }, optimisticId);
145 return updateResult;
146 };
147 ApolloCache.prototype.recordOptimisticTransaction = function (transaction, optimisticId) {
148 this.performTransaction(transaction, optimisticId);
149 };
150 ApolloCache.prototype.transformDocument = function (document) {
151 return document;
152 };
153 ApolloCache.prototype.transformForLink = function (document) {
154 return document;
155 };
156 ApolloCache.prototype.identify = function (object) {
157 return;
158 };
159 ApolloCache.prototype.gc = function () {
160 return [];
161 };
162 ApolloCache.prototype.modify = function (options) {
163 return false;
164 };
165 ApolloCache.prototype.readQuery = function (options, optimistic) {
166 if (optimistic === void 0) { optimistic = !!options.optimistic; }
167 return this.read(tslib.__assign(tslib.__assign({}, options), { rootId: options.id || "ROOT_QUERY", optimistic: optimistic }));
168 };
169 ApolloCache.prototype.watchFragment = function (options) {
170 var _this = this;
171 var fragment = options.fragment, fragmentName = options.fragmentName, from = options.from, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, otherOptions = tslib.__rest(options, ["fragment", "fragmentName", "from", "optimistic"]);
172 var query = this.getFragmentDoc(fragment, fragmentName);
173 var diffOptions = tslib.__assign(tslib.__assign({}, otherOptions), { returnPartialData: true, id:
174 typeof from === "undefined" || typeof from === "string" ?
175 from
176 : this.identify(from), query: query, optimistic: optimistic });
177 var latestDiff;
178 return new utilities.Observable(function (observer) {
179 return _this.watch(tslib.__assign(tslib.__assign({}, diffOptions), { immediate: true, callback: function (diff) {
180 if (
181 latestDiff &&
182 equalByQuery(query, { data: latestDiff === null || latestDiff === void 0 ? void 0 : latestDiff.result }, { data: diff.result })) {
183 return;
184 }
185 var result = {
186 data: diff.result,
187 complete: !!diff.complete,
188 };
189 if (diff.missing) {
190 result.missing = utilities.mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));
191 }
192 latestDiff = diff;
193 observer.next(result);
194 } }));
195 });
196 };
197 ApolloCache.prototype.readFragment = function (options, optimistic) {
198 if (optimistic === void 0) { optimistic = !!options.optimistic; }
199 return this.read(tslib.__assign(tslib.__assign({}, options), { query: this.getFragmentDoc(options.fragment, options.fragmentName), rootId: options.id, optimistic: optimistic }));
200 };
201 ApolloCache.prototype.writeQuery = function (_a) {
202 var id = _a.id, data = _a.data, options = tslib.__rest(_a, ["id", "data"]);
203 return this.write(Object.assign(options, {
204 dataId: id || "ROOT_QUERY",
205 result: data,
206 }));
207 };
208 ApolloCache.prototype.writeFragment = function (_a) {
209 var id = _a.id, data = _a.data, fragment = _a.fragment, fragmentName = _a.fragmentName, options = tslib.__rest(_a, ["id", "data", "fragment", "fragmentName"]);
210 return this.write(Object.assign(options, {
211 query: this.getFragmentDoc(fragment, fragmentName),
212 dataId: id,
213 result: data,
214 }));
215 };
216 ApolloCache.prototype.updateQuery = function (options, update) {
217 return this.batch({
218 update: function (cache) {
219 var value = cache.readQuery(options);
220 var data = update(value);
221 if (data === void 0 || data === null)
222 return value;
223 cache.writeQuery(tslib.__assign(tslib.__assign({}, options), { data: data }));
224 return data;
225 },
226 });
227 };
228 ApolloCache.prototype.updateFragment = function (options, update) {
229 return this.batch({
230 update: function (cache) {
231 var value = cache.readFragment(options);
232 var data = update(value);
233 if (data === void 0 || data === null)
234 return value;
235 cache.writeFragment(tslib.__assign(tslib.__assign({}, options), { data: data }));
236 return data;
237 },
238 });
239 };
240 return ApolloCache;
241}());
242if (globalThis.__DEV__ !== false) {
243 ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;
244}
245
246exports.Cache = void 0;
247(function (Cache) {
248})(exports.Cache || (exports.Cache = {}));
249
250var MissingFieldError = (function (_super) {
251 tslib.__extends(MissingFieldError, _super);
252 function MissingFieldError(message, path, query, variables) {
253 var _a;
254 var _this = _super.call(this, message) || this;
255 _this.message = message;
256 _this.path = path;
257 _this.query = query;
258 _this.variables = variables;
259 if (Array.isArray(_this.path)) {
260 _this.missing = _this.message;
261 for (var i = _this.path.length - 1; i >= 0; --i) {
262 _this.missing = (_a = {}, _a[_this.path[i]] = _this.missing, _a);
263 }
264 }
265 else {
266 _this.missing = _this.path;
267 }
268 _this.__proto__ = MissingFieldError.prototype;
269 return _this;
270 }
271 return MissingFieldError;
272}(Error));
273
274var hasOwn = Object.prototype.hasOwnProperty;
275function isNullish(value) {
276 return value === null || value === void 0;
277}
278function defaultDataIdFromObject(_a, context) {
279 var __typename = _a.__typename, id = _a.id, _id = _a._id;
280 if (typeof __typename === "string") {
281 if (context) {
282 context.keyObject =
283 !isNullish(id) ? { id: id }
284 : !isNullish(_id) ? { _id: _id }
285 : void 0;
286 }
287 if (isNullish(id) && !isNullish(_id)) {
288 id = _id;
289 }
290 if (!isNullish(id)) {
291 return "".concat(__typename, ":").concat(typeof id === "number" || typeof id === "string" ?
292 id
293 : JSON.stringify(id));
294 }
295 }
296}
297var defaultConfig = {
298 dataIdFromObject: defaultDataIdFromObject,
299 addTypename: true,
300 resultCaching: true,
301 canonizeResults: false,
302};
303function normalizeConfig(config) {
304 return utilities.compact(defaultConfig, config);
305}
306function shouldCanonizeResults(config) {
307 var value = config.canonizeResults;
308 return value === void 0 ? defaultConfig.canonizeResults : value;
309}
310function getTypenameFromStoreObject(store, objectOrReference) {
311 return utilities.isReference(objectOrReference) ?
312 store.get(objectOrReference.__ref, "__typename")
313 : objectOrReference && objectOrReference.__typename;
314}
315var TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;
316function fieldNameFromStoreName(storeFieldName) {
317 var match = storeFieldName.match(TypeOrFieldNameRegExp);
318 return match ? match[0] : storeFieldName;
319}
320function selectionSetMatchesResult(selectionSet, result, variables) {
321 if (utilities.isNonNullObject(result)) {
322 return utilities.isArray(result) ?
323 result.every(function (item) {
324 return selectionSetMatchesResult(selectionSet, item, variables);
325 })
326 : selectionSet.selections.every(function (field) {
327 if (utilities.isField(field) && utilities.shouldInclude(field, variables)) {
328 var key = utilities.resultKeyNameFromField(field);
329 return (hasOwn.call(result, key) &&
330 (!field.selectionSet ||
331 selectionSetMatchesResult(field.selectionSet, result[key], variables)));
332 }
333 return true;
334 });
335 }
336 return false;
337}
338function storeValueIsStoreObject(value) {
339 return utilities.isNonNullObject(value) && !utilities.isReference(value) && !utilities.isArray(value);
340}
341function makeProcessedFieldsMerger() {
342 return new utilities.DeepMerger();
343}
344function extractFragmentContext(document, fragments) {
345 var fragmentMap = utilities.createFragmentMap(utilities.getFragmentDefinitions(document));
346 return {
347 fragmentMap: fragmentMap,
348 lookupFragment: function (name) {
349 var def = fragmentMap[name];
350 if (!def && fragments) {
351 def = fragments.lookup(name);
352 }
353 return def || null;
354 },
355 };
356}
357
358var DELETE = Object.create(null);
359var delModifier = function () { return DELETE; };
360var INVALIDATE = Object.create(null);
361exports.EntityStore = (function () {
362 function EntityStore(policies, group) {
363 var _this = this;
364 this.policies = policies;
365 this.group = group;
366 this.data = Object.create(null);
367 this.rootIds = Object.create(null);
368 this.refs = Object.create(null);
369 this.getFieldValue = function (objectOrReference, storeFieldName) {
370 return utilities.maybeDeepFreeze(utilities.isReference(objectOrReference) ?
371 _this.get(objectOrReference.__ref, storeFieldName)
372 : objectOrReference && objectOrReference[storeFieldName]);
373 };
374 this.canRead = function (objOrRef) {
375 return utilities.isReference(objOrRef) ?
376 _this.has(objOrRef.__ref)
377 : typeof objOrRef === "object";
378 };
379 this.toReference = function (objOrIdOrRef, mergeIntoStore) {
380 if (typeof objOrIdOrRef === "string") {
381 return utilities.makeReference(objOrIdOrRef);
382 }
383 if (utilities.isReference(objOrIdOrRef)) {
384 return objOrIdOrRef;
385 }
386 var id = _this.policies.identify(objOrIdOrRef)[0];
387 if (id) {
388 var ref = utilities.makeReference(id);
389 if (mergeIntoStore) {
390 _this.merge(id, objOrIdOrRef);
391 }
392 return ref;
393 }
394 };
395 }
396 EntityStore.prototype.toObject = function () {
397 return tslib.__assign({}, this.data);
398 };
399 EntityStore.prototype.has = function (dataId) {
400 return this.lookup(dataId, true) !== void 0;
401 };
402 EntityStore.prototype.get = function (dataId, fieldName) {
403 this.group.depend(dataId, fieldName);
404 if (hasOwn.call(this.data, dataId)) {
405 var storeObject = this.data[dataId];
406 if (storeObject && hasOwn.call(storeObject, fieldName)) {
407 return storeObject[fieldName];
408 }
409 }
410 if (fieldName === "__typename" &&
411 hasOwn.call(this.policies.rootTypenamesById, dataId)) {
412 return this.policies.rootTypenamesById[dataId];
413 }
414 if (this instanceof Layer) {
415 return this.parent.get(dataId, fieldName);
416 }
417 };
418 EntityStore.prototype.lookup = function (dataId, dependOnExistence) {
419 if (dependOnExistence)
420 this.group.depend(dataId, "__exists");
421 if (hasOwn.call(this.data, dataId)) {
422 return this.data[dataId];
423 }
424 if (this instanceof Layer) {
425 return this.parent.lookup(dataId, dependOnExistence);
426 }
427 if (this.policies.rootTypenamesById[dataId]) {
428 return Object.create(null);
429 }
430 };
431 EntityStore.prototype.merge = function (older, newer) {
432 var _this = this;
433 var dataId;
434 if (utilities.isReference(older))
435 older = older.__ref;
436 if (utilities.isReference(newer))
437 newer = newer.__ref;
438 var existing = typeof older === "string" ? this.lookup((dataId = older)) : older;
439 var incoming = typeof newer === "string" ? this.lookup((dataId = newer)) : newer;
440 if (!incoming)
441 return;
442 globals.invariant(typeof dataId === "string", 1);
443 var merged = new utilities.DeepMerger(storeObjectReconciler).merge(existing, incoming);
444 this.data[dataId] = merged;
445 if (merged !== existing) {
446 delete this.refs[dataId];
447 if (this.group.caching) {
448 var fieldsToDirty_1 = Object.create(null);
449 if (!existing)
450 fieldsToDirty_1.__exists = 1;
451 Object.keys(incoming).forEach(function (storeFieldName) {
452 if (!existing ||
453 existing[storeFieldName] !== merged[storeFieldName]) {
454 fieldsToDirty_1[storeFieldName] = 1;
455 var fieldName = fieldNameFromStoreName(storeFieldName);
456 if (fieldName !== storeFieldName &&
457 !_this.policies.hasKeyArgs(merged.__typename, fieldName)) {
458 fieldsToDirty_1[fieldName] = 1;
459 }
460 if (merged[storeFieldName] === void 0 && !(_this instanceof Layer)) {
461 delete merged[storeFieldName];
462 }
463 }
464 });
465 if (fieldsToDirty_1.__typename &&
466 !(existing && existing.__typename) &&
467 this.policies.rootTypenamesById[dataId] === merged.__typename) {
468 delete fieldsToDirty_1.__typename;
469 }
470 Object.keys(fieldsToDirty_1).forEach(function (fieldName) {
471 return _this.group.dirty(dataId, fieldName);
472 });
473 }
474 }
475 };
476 EntityStore.prototype.modify = function (dataId, fields) {
477 var _this = this;
478 var storeObject = this.lookup(dataId);
479 if (storeObject) {
480 var changedFields_1 = Object.create(null);
481 var needToMerge_1 = false;
482 var allDeleted_1 = true;
483 var sharedDetails_1 = {
484 DELETE: DELETE,
485 INVALIDATE: INVALIDATE,
486 isReference: utilities.isReference,
487 toReference: this.toReference,
488 canRead: this.canRead,
489 readField: function (fieldNameOrOptions, from) {
490 return _this.policies.readField(typeof fieldNameOrOptions === "string" ?
491 {
492 fieldName: fieldNameOrOptions,
493 from: from || utilities.makeReference(dataId),
494 }
495 : fieldNameOrOptions, { store: _this });
496 },
497 };
498 Object.keys(storeObject).forEach(function (storeFieldName) {
499 var fieldName = fieldNameFromStoreName(storeFieldName);
500 var fieldValue = storeObject[storeFieldName];
501 if (fieldValue === void 0)
502 return;
503 var modify = typeof fields === "function" ? fields : (fields[storeFieldName] || fields[fieldName]);
504 if (modify) {
505 var newValue = modify === delModifier ? DELETE : (modify(utilities.maybeDeepFreeze(fieldValue), tslib.__assign(tslib.__assign({}, sharedDetails_1), { fieldName: fieldName, storeFieldName: storeFieldName, storage: _this.getStorage(dataId, storeFieldName) })));
506 if (newValue === INVALIDATE) {
507 _this.group.dirty(dataId, storeFieldName);
508 }
509 else {
510 if (newValue === DELETE)
511 newValue = void 0;
512 if (newValue !== fieldValue) {
513 changedFields_1[storeFieldName] = newValue;
514 needToMerge_1 = true;
515 fieldValue = newValue;
516 if (globalThis.__DEV__ !== false) {
517 var checkReference = function (ref) {
518 if (_this.lookup(ref.__ref) === undefined) {
519 globalThis.__DEV__ !== false && globals.invariant.warn(2, ref);
520 return true;
521 }
522 };
523 if (utilities.isReference(newValue)) {
524 checkReference(newValue);
525 }
526 else if (Array.isArray(newValue)) {
527 var seenReference = false;
528 var someNonReference = void 0;
529 for (var _i = 0, newValue_1 = newValue; _i < newValue_1.length; _i++) {
530 var value = newValue_1[_i];
531 if (utilities.isReference(value)) {
532 seenReference = true;
533 if (checkReference(value))
534 break;
535 }
536 else {
537 if (typeof value === "object" && !!value) {
538 var id = _this.policies.identify(value)[0];
539 if (id) {
540 someNonReference = value;
541 }
542 }
543 }
544 if (seenReference && someNonReference !== undefined) {
545 globalThis.__DEV__ !== false && globals.invariant.warn(3, someNonReference);
546 break;
547 }
548 }
549 }
550 }
551 }
552 }
553 }
554 if (fieldValue !== void 0) {
555 allDeleted_1 = false;
556 }
557 });
558 if (needToMerge_1) {
559 this.merge(dataId, changedFields_1);
560 if (allDeleted_1) {
561 if (this instanceof Layer) {
562 this.data[dataId] = void 0;
563 }
564 else {
565 delete this.data[dataId];
566 }
567 this.group.dirty(dataId, "__exists");
568 }
569 return true;
570 }
571 }
572 return false;
573 };
574 EntityStore.prototype.delete = function (dataId, fieldName, args) {
575 var _a;
576 var storeObject = this.lookup(dataId);
577 if (storeObject) {
578 var typename = this.getFieldValue(storeObject, "__typename");
579 var storeFieldName = fieldName && args ?
580 this.policies.getStoreFieldName({ typename: typename, fieldName: fieldName, args: args })
581 : fieldName;
582 return this.modify(dataId, storeFieldName ? (_a = {},
583 _a[storeFieldName] = delModifier,
584 _a) : delModifier);
585 }
586 return false;
587 };
588 EntityStore.prototype.evict = function (options, limit) {
589 var evicted = false;
590 if (options.id) {
591 if (hasOwn.call(this.data, options.id)) {
592 evicted = this.delete(options.id, options.fieldName, options.args);
593 }
594 if (this instanceof Layer && this !== limit) {
595 evicted = this.parent.evict(options, limit) || evicted;
596 }
597 if (options.fieldName || evicted) {
598 this.group.dirty(options.id, options.fieldName || "__exists");
599 }
600 }
601 return evicted;
602 };
603 EntityStore.prototype.clear = function () {
604 this.replace(null);
605 };
606 EntityStore.prototype.extract = function () {
607 var _this = this;
608 var obj = this.toObject();
609 var extraRootIds = [];
610 this.getRootIdSet().forEach(function (id) {
611 if (!hasOwn.call(_this.policies.rootTypenamesById, id)) {
612 extraRootIds.push(id);
613 }
614 });
615 if (extraRootIds.length) {
616 obj.__META = { extraRootIds: extraRootIds.sort() };
617 }
618 return obj;
619 };
620 EntityStore.prototype.replace = function (newData) {
621 var _this = this;
622 Object.keys(this.data).forEach(function (dataId) {
623 if (!(newData && hasOwn.call(newData, dataId))) {
624 _this.delete(dataId);
625 }
626 });
627 if (newData) {
628 var __META = newData.__META, rest_1 = tslib.__rest(newData, ["__META"]);
629 Object.keys(rest_1).forEach(function (dataId) {
630 _this.merge(dataId, rest_1[dataId]);
631 });
632 if (__META) {
633 __META.extraRootIds.forEach(this.retain, this);
634 }
635 }
636 };
637 EntityStore.prototype.retain = function (rootId) {
638 return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);
639 };
640 EntityStore.prototype.release = function (rootId) {
641 if (this.rootIds[rootId] > 0) {
642 var count = --this.rootIds[rootId];
643 if (!count)
644 delete this.rootIds[rootId];
645 return count;
646 }
647 return 0;
648 };
649 EntityStore.prototype.getRootIdSet = function (ids) {
650 if (ids === void 0) { ids = new Set(); }
651 Object.keys(this.rootIds).forEach(ids.add, ids);
652 if (this instanceof Layer) {
653 this.parent.getRootIdSet(ids);
654 }
655 else {
656 Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);
657 }
658 return ids;
659 };
660 EntityStore.prototype.gc = function () {
661 var _this = this;
662 var ids = this.getRootIdSet();
663 var snapshot = this.toObject();
664 ids.forEach(function (id) {
665 if (hasOwn.call(snapshot, id)) {
666 Object.keys(_this.findChildRefIds(id)).forEach(ids.add, ids);
667 delete snapshot[id];
668 }
669 });
670 var idsToRemove = Object.keys(snapshot);
671 if (idsToRemove.length) {
672 var root_1 = this;
673 while (root_1 instanceof Layer)
674 root_1 = root_1.parent;
675 idsToRemove.forEach(function (id) { return root_1.delete(id); });
676 }
677 return idsToRemove;
678 };
679 EntityStore.prototype.findChildRefIds = function (dataId) {
680 if (!hasOwn.call(this.refs, dataId)) {
681 var found_1 = (this.refs[dataId] = Object.create(null));
682 var root = this.data[dataId];
683 if (!root)
684 return found_1;
685 var workSet_1 = new Set([root]);
686 workSet_1.forEach(function (obj) {
687 if (utilities.isReference(obj)) {
688 found_1[obj.__ref] = true;
689 }
690 if (utilities.isNonNullObject(obj)) {
691 Object.keys(obj).forEach(function (key) {
692 var child = obj[key];
693 if (utilities.isNonNullObject(child)) {
694 workSet_1.add(child);
695 }
696 });
697 }
698 });
699 }
700 return this.refs[dataId];
701 };
702 EntityStore.prototype.makeCacheKey = function () {
703 return this.group.keyMaker.lookupArray(arguments);
704 };
705 return EntityStore;
706}());
707var CacheGroup = (function () {
708 function CacheGroup(caching, parent) {
709 if (parent === void 0) { parent = null; }
710 this.caching = caching;
711 this.parent = parent;
712 this.d = null;
713 this.resetCaching();
714 }
715 CacheGroup.prototype.resetCaching = function () {
716 this.d = this.caching ? optimism.dep() : null;
717 this.keyMaker = new trie.Trie(utilities.canUseWeakMap);
718 };
719 CacheGroup.prototype.depend = function (dataId, storeFieldName) {
720 if (this.d) {
721 this.d(makeDepKey(dataId, storeFieldName));
722 var fieldName = fieldNameFromStoreName(storeFieldName);
723 if (fieldName !== storeFieldName) {
724 this.d(makeDepKey(dataId, fieldName));
725 }
726 if (this.parent) {
727 this.parent.depend(dataId, storeFieldName);
728 }
729 }
730 };
731 CacheGroup.prototype.dirty = function (dataId, storeFieldName) {
732 if (this.d) {
733 this.d.dirty(makeDepKey(dataId, storeFieldName),
734 storeFieldName === "__exists" ? "forget" : "setDirty");
735 }
736 };
737 return CacheGroup;
738}());
739function makeDepKey(dataId, storeFieldName) {
740 return storeFieldName + "#" + dataId;
741}
742function maybeDependOnExistenceOfEntity(store, entityId) {
743 if (supportsResultCaching(store)) {
744 store.group.depend(entityId, "__exists");
745 }
746}
747(function (EntityStore) {
748 var Root = (function (_super) {
749 tslib.__extends(Root, _super);
750 function Root(_a) {
751 var policies = _a.policies, _b = _a.resultCaching, resultCaching = _b === void 0 ? true : _b, seed = _a.seed;
752 var _this = _super.call(this, policies, new CacheGroup(resultCaching)) || this;
753 _this.stump = new Stump(_this);
754 _this.storageTrie = new trie.Trie(utilities.canUseWeakMap);
755 if (seed)
756 _this.replace(seed);
757 return _this;
758 }
759 Root.prototype.addLayer = function (layerId, replay) {
760 return this.stump.addLayer(layerId, replay);
761 };
762 Root.prototype.removeLayer = function () {
763 return this;
764 };
765 Root.prototype.getStorage = function () {
766 return this.storageTrie.lookupArray(arguments);
767 };
768 return Root;
769 }(EntityStore));
770 EntityStore.Root = Root;
771})(exports.EntityStore || (exports.EntityStore = {}));
772var Layer = (function (_super) {
773 tslib.__extends(Layer, _super);
774 function Layer(id, parent, replay, group) {
775 var _this = _super.call(this, parent.policies, group) || this;
776 _this.id = id;
777 _this.parent = parent;
778 _this.replay = replay;
779 _this.group = group;
780 replay(_this);
781 return _this;
782 }
783 Layer.prototype.addLayer = function (layerId, replay) {
784 return new Layer(layerId, this, replay, this.group);
785 };
786 Layer.prototype.removeLayer = function (layerId) {
787 var _this = this;
788 var parent = this.parent.removeLayer(layerId);
789 if (layerId === this.id) {
790 if (this.group.caching) {
791 Object.keys(this.data).forEach(function (dataId) {
792 var ownStoreObject = _this.data[dataId];
793 var parentStoreObject = parent["lookup"](dataId);
794 if (!parentStoreObject) {
795 _this.delete(dataId);
796 }
797 else if (!ownStoreObject) {
798 _this.group.dirty(dataId, "__exists");
799 Object.keys(parentStoreObject).forEach(function (storeFieldName) {
800 _this.group.dirty(dataId, storeFieldName);
801 });
802 }
803 else if (ownStoreObject !== parentStoreObject) {
804 Object.keys(ownStoreObject).forEach(function (storeFieldName) {
805 if (!equal.equal(ownStoreObject[storeFieldName], parentStoreObject[storeFieldName])) {
806 _this.group.dirty(dataId, storeFieldName);
807 }
808 });
809 }
810 });
811 }
812 return parent;
813 }
814 if (parent === this.parent)
815 return this;
816 return parent.addLayer(this.id, this.replay);
817 };
818 Layer.prototype.toObject = function () {
819 return tslib.__assign(tslib.__assign({}, this.parent.toObject()), this.data);
820 };
821 Layer.prototype.findChildRefIds = function (dataId) {
822 var fromParent = this.parent.findChildRefIds(dataId);
823 return hasOwn.call(this.data, dataId) ? tslib.__assign(tslib.__assign({}, fromParent), _super.prototype.findChildRefIds.call(this, dataId)) : fromParent;
824 };
825 Layer.prototype.getStorage = function () {
826 var p = this.parent;
827 while (p.parent)
828 p = p.parent;
829 return p.getStorage.apply(p,
830 arguments);
831 };
832 return Layer;
833}(exports.EntityStore));
834var Stump = (function (_super) {
835 tslib.__extends(Stump, _super);
836 function Stump(root) {
837 return _super.call(this, "EntityStore.Stump", root, function () { }, new CacheGroup(root.group.caching, root.group)) || this;
838 }
839 Stump.prototype.removeLayer = function () {
840 return this;
841 };
842 Stump.prototype.merge = function (older, newer) {
843 return this.parent.merge(older, newer);
844 };
845 return Stump;
846}(Layer));
847function storeObjectReconciler(existingObject, incomingObject, property) {
848 var existingValue = existingObject[property];
849 var incomingValue = incomingObject[property];
850 return equal.equal(existingValue, incomingValue) ? existingValue : incomingValue;
851}
852function supportsResultCaching(store) {
853 return !!(store instanceof exports.EntityStore && store.group.caching);
854}
855
856function shallowCopy(value) {
857 if (utilities.isNonNullObject(value)) {
858 return utilities.isArray(value) ?
859 value.slice(0)
860 : tslib.__assign({ __proto__: Object.getPrototypeOf(value) }, value);
861 }
862 return value;
863}
864var ObjectCanon = (function () {
865 function ObjectCanon() {
866 this.known = new (utilities.canUseWeakSet ? WeakSet : Set)();
867 this.pool = new trie.Trie(utilities.canUseWeakMap);
868 this.passes = new WeakMap();
869 this.keysByJSON = new Map();
870 this.empty = this.admit({});
871 }
872 ObjectCanon.prototype.isKnown = function (value) {
873 return utilities.isNonNullObject(value) && this.known.has(value);
874 };
875 ObjectCanon.prototype.pass = function (value) {
876 if (utilities.isNonNullObject(value)) {
877 var copy = shallowCopy(value);
878 this.passes.set(copy, value);
879 return copy;
880 }
881 return value;
882 };
883 ObjectCanon.prototype.admit = function (value) {
884 var _this = this;
885 if (utilities.isNonNullObject(value)) {
886 var original = this.passes.get(value);
887 if (original)
888 return original;
889 var proto = Object.getPrototypeOf(value);
890 switch (proto) {
891 case Array.prototype: {
892 if (this.known.has(value))
893 return value;
894 var array = value.map(this.admit, this);
895 var node = this.pool.lookupArray(array);
896 if (!node.array) {
897 this.known.add((node.array = array));
898 if (globalThis.__DEV__ !== false) {
899 Object.freeze(array);
900 }
901 }
902 return node.array;
903 }
904 case null:
905 case Object.prototype: {
906 if (this.known.has(value))
907 return value;
908 var proto_1 = Object.getPrototypeOf(value);
909 var array_1 = [proto_1];
910 var keys = this.sortedKeys(value);
911 array_1.push(keys.json);
912 var firstValueIndex_1 = array_1.length;
913 keys.sorted.forEach(function (key) {
914 array_1.push(_this.admit(value[key]));
915 });
916 var node = this.pool.lookupArray(array_1);
917 if (!node.object) {
918 var obj_1 = (node.object = Object.create(proto_1));
919 this.known.add(obj_1);
920 keys.sorted.forEach(function (key, i) {
921 obj_1[key] = array_1[firstValueIndex_1 + i];
922 });
923 if (globalThis.__DEV__ !== false) {
924 Object.freeze(obj_1);
925 }
926 }
927 return node.object;
928 }
929 }
930 }
931 return value;
932 };
933 ObjectCanon.prototype.sortedKeys = function (obj) {
934 var keys = Object.keys(obj);
935 var node = this.pool.lookupArray(keys);
936 if (!node.keys) {
937 keys.sort();
938 var json = JSON.stringify(keys);
939 if (!(node.keys = this.keysByJSON.get(json))) {
940 this.keysByJSON.set(json, (node.keys = { sorted: keys, json: json }));
941 }
942 }
943 return node.keys;
944 };
945 return ObjectCanon;
946}());
947
948function execSelectionSetKeyArgs(options) {
949 return [
950 options.selectionSet,
951 options.objectOrReference,
952 options.context,
953 options.context.canonizeResults,
954 ];
955}
956var StoreReader = (function () {
957 function StoreReader(config) {
958 var _this = this;
959 this.knownResults = new (utilities.canUseWeakMap ? WeakMap : Map)();
960 this.config = utilities.compact(config, {
961 addTypename: config.addTypename !== false,
962 canonizeResults: shouldCanonizeResults(config),
963 });
964 this.canon = config.canon || new ObjectCanon();
965 this.executeSelectionSet = optimism.wrap(function (options) {
966 var _a;
967 var canonizeResults = options.context.canonizeResults;
968 var peekArgs = execSelectionSetKeyArgs(options);
969 peekArgs[3] = !canonizeResults;
970 var other = (_a = _this.executeSelectionSet).peek.apply(_a, peekArgs);
971 if (other) {
972 if (canonizeResults) {
973 return tslib.__assign(tslib.__assign({}, other), {
974 result: _this.canon.admit(other.result) });
975 }
976 return other;
977 }
978 maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);
979 return _this.execSelectionSetImpl(options);
980 }, {
981 max: this.config.resultCacheMaxSize ||
982 utilities.cacheSizes["inMemoryCache.executeSelectionSet"] ||
983 50000 ,
984 keyArgs: execSelectionSetKeyArgs,
985 makeCacheKey: function (selectionSet, parent, context, canonizeResults) {
986 if (supportsResultCaching(context.store)) {
987 return context.store.makeCacheKey(selectionSet, utilities.isReference(parent) ? parent.__ref : parent, context.varString, canonizeResults);
988 }
989 },
990 });
991 this.executeSubSelectedArray = optimism.wrap(function (options) {
992 maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);
993 return _this.execSubSelectedArrayImpl(options);
994 }, {
995 max: this.config.resultCacheMaxSize ||
996 utilities.cacheSizes["inMemoryCache.executeSubSelectedArray"] ||
997 10000 ,
998 makeCacheKey: function (_a) {
999 var field = _a.field, array = _a.array, context = _a.context;
1000 if (supportsResultCaching(context.store)) {
1001 return context.store.makeCacheKey(field, array, context.varString);
1002 }
1003 },
1004 });
1005 }
1006 StoreReader.prototype.resetCanon = function () {
1007 this.canon = new ObjectCanon();
1008 };
1009 StoreReader.prototype.diffQueryAgainstStore = function (_a) {
1010 var store = _a.store, query = _a.query, _b = _a.rootId, rootId = _b === void 0 ? "ROOT_QUERY" : _b, variables = _a.variables, _c = _a.returnPartialData, returnPartialData = _c === void 0 ? true : _c, _d = _a.canonizeResults, canonizeResults = _d === void 0 ? this.config.canonizeResults : _d;
1011 var policies = this.config.cache.policies;
1012 variables = tslib.__assign(tslib.__assign({}, utilities.getDefaultValues(utilities.getQueryDefinition(query))), variables);
1013 var rootRef = utilities.makeReference(rootId);
1014 var execResult = this.executeSelectionSet({
1015 selectionSet: utilities.getMainDefinition(query).selectionSet,
1016 objectOrReference: rootRef,
1017 enclosingRef: rootRef,
1018 context: tslib.__assign({ store: store, query: query, policies: policies, variables: variables, varString: utilities.canonicalStringify(variables), canonizeResults: canonizeResults }, extractFragmentContext(query, this.config.fragments)),
1019 });
1020 var missing;
1021 if (execResult.missing) {
1022 missing = [
1023 new MissingFieldError(firstMissing(execResult.missing), execResult.missing, query, variables),
1024 ];
1025 if (!returnPartialData) {
1026 throw missing[0];
1027 }
1028 }
1029 return {
1030 result: execResult.result,
1031 complete: !missing,
1032 missing: missing,
1033 };
1034 };
1035 StoreReader.prototype.isFresh = function (result, parent, selectionSet, context) {
1036 if (supportsResultCaching(context.store) &&
1037 this.knownResults.get(result) === selectionSet) {
1038 var latest = this.executeSelectionSet.peek(selectionSet, parent, context,
1039 this.canon.isKnown(result));
1040 if (latest && result === latest.result) {
1041 return true;
1042 }
1043 }
1044 return false;
1045 };
1046 StoreReader.prototype.execSelectionSetImpl = function (_a) {
1047 var _this = this;
1048 var selectionSet = _a.selectionSet, objectOrReference = _a.objectOrReference, enclosingRef = _a.enclosingRef, context = _a.context;
1049 if (utilities.isReference(objectOrReference) &&
1050 !context.policies.rootTypenamesById[objectOrReference.__ref] &&
1051 !context.store.has(objectOrReference.__ref)) {
1052 return {
1053 result: this.canon.empty,
1054 missing: "Dangling reference to missing ".concat(objectOrReference.__ref, " object"),
1055 };
1056 }
1057 var variables = context.variables, policies = context.policies, store = context.store;
1058 var typename = store.getFieldValue(objectOrReference, "__typename");
1059 var objectsToMerge = [];
1060 var missing;
1061 var missingMerger = new utilities.DeepMerger();
1062 if (this.config.addTypename &&
1063 typeof typename === "string" &&
1064 !policies.rootIdsByTypename[typename]) {
1065 objectsToMerge.push({ __typename: typename });
1066 }
1067 function handleMissing(result, resultName) {
1068 var _a;
1069 if (result.missing) {
1070 missing = missingMerger.merge(missing, (_a = {},
1071 _a[resultName] = result.missing,
1072 _a));
1073 }
1074 return result.result;
1075 }
1076 var workSet = new Set(selectionSet.selections);
1077 workSet.forEach(function (selection) {
1078 var _a, _b;
1079 if (!utilities.shouldInclude(selection, variables))
1080 return;
1081 if (utilities.isField(selection)) {
1082 var fieldValue = policies.readField({
1083 fieldName: selection.name.value,
1084 field: selection,
1085 variables: context.variables,
1086 from: objectOrReference,
1087 }, context);
1088 var resultName = utilities.resultKeyNameFromField(selection);
1089 if (fieldValue === void 0) {
1090 if (!utilities.addTypenameToDocument.added(selection)) {
1091 missing = missingMerger.merge(missing, (_a = {},
1092 _a[resultName] = "Can't find field '".concat(selection.name.value, "' on ").concat(utilities.isReference(objectOrReference) ?
1093 objectOrReference.__ref + " object"
1094 : "object " + JSON.stringify(objectOrReference, null, 2)),
1095 _a));
1096 }
1097 }
1098 else if (utilities.isArray(fieldValue)) {
1099 if (fieldValue.length > 0) {
1100 fieldValue = handleMissing(_this.executeSubSelectedArray({
1101 field: selection,
1102 array: fieldValue,
1103 enclosingRef: enclosingRef,
1104 context: context,
1105 }), resultName);
1106 }
1107 }
1108 else if (!selection.selectionSet) {
1109 if (context.canonizeResults) {
1110 fieldValue = _this.canon.pass(fieldValue);
1111 }
1112 }
1113 else if (fieldValue != null) {
1114 fieldValue = handleMissing(_this.executeSelectionSet({
1115 selectionSet: selection.selectionSet,
1116 objectOrReference: fieldValue,
1117 enclosingRef: utilities.isReference(fieldValue) ? fieldValue : enclosingRef,
1118 context: context,
1119 }), resultName);
1120 }
1121 if (fieldValue !== void 0) {
1122 objectsToMerge.push((_b = {}, _b[resultName] = fieldValue, _b));
1123 }
1124 }
1125 else {
1126 var fragment = utilities.getFragmentFromSelection(selection, context.lookupFragment);
1127 if (!fragment && selection.kind === graphql.Kind.FRAGMENT_SPREAD) {
1128 throw globals.newInvariantError(9, selection.name.value);
1129 }
1130 if (fragment && policies.fragmentMatches(fragment, typename)) {
1131 fragment.selectionSet.selections.forEach(workSet.add, workSet);
1132 }
1133 }
1134 });
1135 var result = utilities.mergeDeepArray(objectsToMerge);
1136 var finalResult = { result: result, missing: missing };
1137 var frozen = context.canonizeResults ?
1138 this.canon.admit(finalResult)
1139 : utilities.maybeDeepFreeze(finalResult);
1140 if (frozen.result) {
1141 this.knownResults.set(frozen.result, selectionSet);
1142 }
1143 return frozen;
1144 };
1145 StoreReader.prototype.execSubSelectedArrayImpl = function (_a) {
1146 var _this = this;
1147 var field = _a.field, array = _a.array, enclosingRef = _a.enclosingRef, context = _a.context;
1148 var missing;
1149 var missingMerger = new utilities.DeepMerger();
1150 function handleMissing(childResult, i) {
1151 var _a;
1152 if (childResult.missing) {
1153 missing = missingMerger.merge(missing, (_a = {}, _a[i] = childResult.missing, _a));
1154 }
1155 return childResult.result;
1156 }
1157 if (field.selectionSet) {
1158 array = array.filter(context.store.canRead);
1159 }
1160 array = array.map(function (item, i) {
1161 if (item === null) {
1162 return null;
1163 }
1164 if (utilities.isArray(item)) {
1165 return handleMissing(_this.executeSubSelectedArray({
1166 field: field,
1167 array: item,
1168 enclosingRef: enclosingRef,
1169 context: context,
1170 }), i);
1171 }
1172 if (field.selectionSet) {
1173 return handleMissing(_this.executeSelectionSet({
1174 selectionSet: field.selectionSet,
1175 objectOrReference: item,
1176 enclosingRef: utilities.isReference(item) ? item : enclosingRef,
1177 context: context,
1178 }), i);
1179 }
1180 if (globalThis.__DEV__ !== false) {
1181 assertSelectionSetForIdValue(context.store, field, item);
1182 }
1183 return item;
1184 });
1185 return {
1186 result: context.canonizeResults ? this.canon.admit(array) : array,
1187 missing: missing,
1188 };
1189 };
1190 return StoreReader;
1191}());
1192function firstMissing(tree) {
1193 try {
1194 JSON.stringify(tree, function (_, value) {
1195 if (typeof value === "string")
1196 throw value;
1197 return value;
1198 });
1199 }
1200 catch (result) {
1201 return result;
1202 }
1203}
1204function assertSelectionSetForIdValue(store, field, fieldValue) {
1205 if (!field.selectionSet) {
1206 var workSet_1 = new Set([fieldValue]);
1207 workSet_1.forEach(function (value) {
1208 if (utilities.isNonNullObject(value)) {
1209 globals.invariant(
1210 !utilities.isReference(value),
1211 10,
1212 getTypenameFromStoreObject(store, value),
1213 field.name.value
1214 );
1215 Object.values(value).forEach(workSet_1.add, workSet_1);
1216 }
1217 });
1218 }
1219}
1220
1221var cacheSlot = new optimism.Slot();
1222var cacheInfoMap = new WeakMap();
1223function getCacheInfo(cache) {
1224 var info = cacheInfoMap.get(cache);
1225 if (!info) {
1226 cacheInfoMap.set(cache, (info = {
1227 vars: new Set(),
1228 dep: optimism.dep(),
1229 }));
1230 }
1231 return info;
1232}
1233function forgetCache(cache) {
1234 getCacheInfo(cache).vars.forEach(function (rv) { return rv.forgetCache(cache); });
1235}
1236function recallCache(cache) {
1237 getCacheInfo(cache).vars.forEach(function (rv) { return rv.attachCache(cache); });
1238}
1239function makeVar(value) {
1240 var caches = new Set();
1241 var listeners = new Set();
1242 var rv = function (newValue) {
1243 if (arguments.length > 0) {
1244 if (value !== newValue) {
1245 value = newValue;
1246 caches.forEach(function (cache) {
1247 getCacheInfo(cache).dep.dirty(rv);
1248 broadcast(cache);
1249 });
1250 var oldListeners = Array.from(listeners);
1251 listeners.clear();
1252 oldListeners.forEach(function (listener) { return listener(value); });
1253 }
1254 }
1255 else {
1256 var cache = cacheSlot.getValue();
1257 if (cache) {
1258 attach(cache);
1259 getCacheInfo(cache).dep(rv);
1260 }
1261 }
1262 return value;
1263 };
1264 rv.onNextChange = function (listener) {
1265 listeners.add(listener);
1266 return function () {
1267 listeners.delete(listener);
1268 };
1269 };
1270 var attach = (rv.attachCache = function (cache) {
1271 caches.add(cache);
1272 getCacheInfo(cache).vars.add(rv);
1273 return rv;
1274 });
1275 rv.forgetCache = function (cache) { return caches.delete(cache); };
1276 return rv;
1277}
1278function broadcast(cache) {
1279 if (cache.broadcastWatches) {
1280 cache.broadcastWatches();
1281 }
1282}
1283
1284var specifierInfoCache = Object.create(null);
1285function lookupSpecifierInfo(spec) {
1286 var cacheKey = JSON.stringify(spec);
1287 return (specifierInfoCache[cacheKey] ||
1288 (specifierInfoCache[cacheKey] = Object.create(null)));
1289}
1290function keyFieldsFnFromSpecifier(specifier) {
1291 var info = lookupSpecifierInfo(specifier);
1292 return (info.keyFieldsFn || (info.keyFieldsFn = function (object, context) {
1293 var extract = function (from, key) {
1294 return context.readField(key, from);
1295 };
1296 var keyObject = (context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {
1297 var extracted = extractKeyPath(context.storeObject, schemaKeyPath,
1298 extract);
1299 if (extracted === void 0 &&
1300 object !== context.storeObject &&
1301 hasOwn.call(object, schemaKeyPath[0])) {
1302 extracted = extractKeyPath(object, schemaKeyPath, extractKey);
1303 }
1304 globals.invariant(extracted !== void 0, 4, schemaKeyPath.join("."), object);
1305 return extracted;
1306 }));
1307 return "".concat(context.typename, ":").concat(JSON.stringify(keyObject));
1308 }));
1309}
1310function keyArgsFnFromSpecifier(specifier) {
1311 var info = lookupSpecifierInfo(specifier);
1312 return (info.keyArgsFn ||
1313 (info.keyArgsFn = function (args, _a) {
1314 var field = _a.field, variables = _a.variables, fieldName = _a.fieldName;
1315 var collected = collectSpecifierPaths(specifier, function (keyPath) {
1316 var firstKey = keyPath[0];
1317 var firstChar = firstKey.charAt(0);
1318 if (firstChar === "@") {
1319 if (field && utilities.isNonEmptyArray(field.directives)) {
1320 var directiveName_1 = firstKey.slice(1);
1321 var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });
1322 var directiveArgs = d && utilities.argumentsObjectFromField(d, variables);
1323 return (directiveArgs &&
1324 extractKeyPath(directiveArgs,
1325 keyPath.slice(1)));
1326 }
1327 return;
1328 }
1329 if (firstChar === "$") {
1330 var variableName = firstKey.slice(1);
1331 if (variables && hasOwn.call(variables, variableName)) {
1332 var varKeyPath = keyPath.slice(0);
1333 varKeyPath[0] = variableName;
1334 return extractKeyPath(variables, varKeyPath);
1335 }
1336 return;
1337 }
1338 if (args) {
1339 return extractKeyPath(args, keyPath);
1340 }
1341 });
1342 var suffix = JSON.stringify(collected);
1343 if (args || suffix !== "{}") {
1344 fieldName += ":" + suffix;
1345 }
1346 return fieldName;
1347 }));
1348}
1349function collectSpecifierPaths(specifier, extractor) {
1350 var merger = new utilities.DeepMerger();
1351 return getSpecifierPaths(specifier).reduce(function (collected, path) {
1352 var _a;
1353 var toMerge = extractor(path);
1354 if (toMerge !== void 0) {
1355 for (var i = path.length - 1; i >= 0; --i) {
1356 toMerge = (_a = {}, _a[path[i]] = toMerge, _a);
1357 }
1358 collected = merger.merge(collected, toMerge);
1359 }
1360 return collected;
1361 }, Object.create(null));
1362}
1363function getSpecifierPaths(spec) {
1364 var info = lookupSpecifierInfo(spec);
1365 if (!info.paths) {
1366 var paths_1 = (info.paths = []);
1367 var currentPath_1 = [];
1368 spec.forEach(function (s, i) {
1369 if (utilities.isArray(s)) {
1370 getSpecifierPaths(s).forEach(function (p) { return paths_1.push(currentPath_1.concat(p)); });
1371 currentPath_1.length = 0;
1372 }
1373 else {
1374 currentPath_1.push(s);
1375 if (!utilities.isArray(spec[i + 1])) {
1376 paths_1.push(currentPath_1.slice(0));
1377 currentPath_1.length = 0;
1378 }
1379 }
1380 });
1381 }
1382 return info.paths;
1383}
1384function extractKey(object, key) {
1385 return object[key];
1386}
1387function extractKeyPath(object, path, extract) {
1388 extract = extract || extractKey;
1389 return normalize(path.reduce(function reducer(obj, key) {
1390 return utilities.isArray(obj) ?
1391 obj.map(function (child) { return reducer(child, key); })
1392 : obj && extract(obj, key);
1393 }, object));
1394}
1395function normalize(value) {
1396 if (utilities.isNonNullObject(value)) {
1397 if (utilities.isArray(value)) {
1398 return value.map(normalize);
1399 }
1400 return collectSpecifierPaths(Object.keys(value).sort(), function (path) {
1401 return extractKeyPath(value, path);
1402 });
1403 }
1404 return value;
1405}
1406
1407function argsFromFieldSpecifier(spec) {
1408 return (spec.args !== void 0 ? spec.args
1409 : spec.field ? utilities.argumentsObjectFromField(spec.field, spec.variables)
1410 : null);
1411}
1412var nullKeyFieldsFn = function () { return void 0; };
1413var simpleKeyArgsFn = function (_args, context) { return context.fieldName; };
1414var mergeTrueFn = function (existing, incoming, _a) {
1415 var mergeObjects = _a.mergeObjects;
1416 return mergeObjects(existing, incoming);
1417};
1418var mergeFalseFn = function (_, incoming) { return incoming; };
1419var Policies = (function () {
1420 function Policies(config) {
1421 this.config = config;
1422 this.typePolicies = Object.create(null);
1423 this.toBeAdded = Object.create(null);
1424 this.supertypeMap = new Map();
1425 this.fuzzySubtypes = new Map();
1426 this.rootIdsByTypename = Object.create(null);
1427 this.rootTypenamesById = Object.create(null);
1428 this.usingPossibleTypes = false;
1429 this.config = tslib.__assign({ dataIdFromObject: defaultDataIdFromObject }, config);
1430 this.cache = this.config.cache;
1431 this.setRootTypename("Query");
1432 this.setRootTypename("Mutation");
1433 this.setRootTypename("Subscription");
1434 if (config.possibleTypes) {
1435 this.addPossibleTypes(config.possibleTypes);
1436 }
1437 if (config.typePolicies) {
1438 this.addTypePolicies(config.typePolicies);
1439 }
1440 }
1441 Policies.prototype.identify = function (object, partialContext) {
1442 var _a;
1443 var policies = this;
1444 var typename = (partialContext &&
1445 (partialContext.typename || ((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename))) ||
1446 object.__typename;
1447 if (typename === this.rootTypenamesById.ROOT_QUERY) {
1448 return ["ROOT_QUERY"];
1449 }
1450 var storeObject = (partialContext && partialContext.storeObject) || object;
1451 var context = tslib.__assign(tslib.__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: (partialContext && partialContext.readField) ||
1452 function () {
1453 var options = normalizeReadFieldOptions(arguments, storeObject);
1454 return policies.readField(options, {
1455 store: policies.cache["data"],
1456 variables: options.variables,
1457 });
1458 } });
1459 var id;
1460 var policy = typename && this.getTypePolicy(typename);
1461 var keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;
1462 while (keyFn) {
1463 var specifierOrId = keyFn(tslib.__assign(tslib.__assign({}, object), storeObject), context);
1464 if (utilities.isArray(specifierOrId)) {
1465 keyFn = keyFieldsFnFromSpecifier(specifierOrId);
1466 }
1467 else {
1468 id = specifierOrId;
1469 break;
1470 }
1471 }
1472 id = id ? String(id) : void 0;
1473 return context.keyObject ? [id, context.keyObject] : [id];
1474 };
1475 Policies.prototype.addTypePolicies = function (typePolicies) {
1476 var _this = this;
1477 Object.keys(typePolicies).forEach(function (typename) {
1478 var _a = typePolicies[typename], queryType = _a.queryType, mutationType = _a.mutationType, subscriptionType = _a.subscriptionType, incoming = tslib.__rest(_a, ["queryType", "mutationType", "subscriptionType"]);
1479 if (queryType)
1480 _this.setRootTypename("Query", typename);
1481 if (mutationType)
1482 _this.setRootTypename("Mutation", typename);
1483 if (subscriptionType)
1484 _this.setRootTypename("Subscription", typename);
1485 if (hasOwn.call(_this.toBeAdded, typename)) {
1486 _this.toBeAdded[typename].push(incoming);
1487 }
1488 else {
1489 _this.toBeAdded[typename] = [incoming];
1490 }
1491 });
1492 };
1493 Policies.prototype.updateTypePolicy = function (typename, incoming) {
1494 var _this = this;
1495 var existing = this.getTypePolicy(typename);
1496 var keyFields = incoming.keyFields, fields = incoming.fields;
1497 function setMerge(existing, merge) {
1498 existing.merge =
1499 typeof merge === "function" ? merge
1500 : merge === true ? mergeTrueFn
1501 : merge === false ? mergeFalseFn
1502 : existing.merge;
1503 }
1504 setMerge(existing, incoming.merge);
1505 existing.keyFn =
1506 keyFields === false ? nullKeyFieldsFn
1507 : utilities.isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields)
1508 : typeof keyFields === "function" ? keyFields
1509 : existing.keyFn;
1510 if (fields) {
1511 Object.keys(fields).forEach(function (fieldName) {
1512 var existing = _this.getFieldPolicy(typename, fieldName, true);
1513 var incoming = fields[fieldName];
1514 if (typeof incoming === "function") {
1515 existing.read = incoming;
1516 }
1517 else {
1518 var keyArgs = incoming.keyArgs, read = incoming.read, merge = incoming.merge;
1519 existing.keyFn =
1520 keyArgs === false ? simpleKeyArgsFn
1521 : utilities.isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs)
1522 : typeof keyArgs === "function" ? keyArgs
1523 : existing.keyFn;
1524 if (typeof read === "function") {
1525 existing.read = read;
1526 }
1527 setMerge(existing, merge);
1528 }
1529 if (existing.read && existing.merge) {
1530 existing.keyFn = existing.keyFn || simpleKeyArgsFn;
1531 }
1532 });
1533 }
1534 };
1535 Policies.prototype.setRootTypename = function (which, typename) {
1536 if (typename === void 0) { typename = which; }
1537 var rootId = "ROOT_" + which.toUpperCase();
1538 var old = this.rootTypenamesById[rootId];
1539 if (typename !== old) {
1540 globals.invariant(!old || old === which, 5, which);
1541 if (old)
1542 delete this.rootIdsByTypename[old];
1543 this.rootIdsByTypename[typename] = rootId;
1544 this.rootTypenamesById[rootId] = typename;
1545 }
1546 };
1547 Policies.prototype.addPossibleTypes = function (possibleTypes) {
1548 var _this = this;
1549 this.usingPossibleTypes = true;
1550 Object.keys(possibleTypes).forEach(function (supertype) {
1551 _this.getSupertypeSet(supertype, true);
1552 possibleTypes[supertype].forEach(function (subtype) {
1553 _this.getSupertypeSet(subtype, true).add(supertype);
1554 var match = subtype.match(TypeOrFieldNameRegExp);
1555 if (!match || match[0] !== subtype) {
1556 _this.fuzzySubtypes.set(subtype, new RegExp(subtype));
1557 }
1558 });
1559 });
1560 };
1561 Policies.prototype.getTypePolicy = function (typename) {
1562 var _this = this;
1563 if (!hasOwn.call(this.typePolicies, typename)) {
1564 var policy_1 = (this.typePolicies[typename] = Object.create(null));
1565 policy_1.fields = Object.create(null);
1566 var supertypes_1 = this.supertypeMap.get(typename);
1567 if (!supertypes_1 && this.fuzzySubtypes.size) {
1568 supertypes_1 = this.getSupertypeSet(typename, true);
1569 this.fuzzySubtypes.forEach(function (regExp, fuzzy) {
1570 if (regExp.test(typename)) {
1571 var fuzzySupertypes = _this.supertypeMap.get(fuzzy);
1572 if (fuzzySupertypes) {
1573 fuzzySupertypes.forEach(function (supertype) {
1574 return supertypes_1.add(supertype);
1575 });
1576 }
1577 }
1578 });
1579 }
1580 if (supertypes_1 && supertypes_1.size) {
1581 supertypes_1.forEach(function (supertype) {
1582 var _a = _this.getTypePolicy(supertype), fields = _a.fields, rest = tslib.__rest(_a, ["fields"]);
1583 Object.assign(policy_1, rest);
1584 Object.assign(policy_1.fields, fields);
1585 });
1586 }
1587 }
1588 var inbox = this.toBeAdded[typename];
1589 if (inbox && inbox.length) {
1590 inbox.splice(0).forEach(function (policy) {
1591 _this.updateTypePolicy(typename, policy);
1592 });
1593 }
1594 return this.typePolicies[typename];
1595 };
1596 Policies.prototype.getFieldPolicy = function (typename, fieldName, createIfMissing) {
1597 if (typename) {
1598 var fieldPolicies = this.getTypePolicy(typename).fields;
1599 return (fieldPolicies[fieldName] ||
1600 (createIfMissing && (fieldPolicies[fieldName] = Object.create(null))));
1601 }
1602 };
1603 Policies.prototype.getSupertypeSet = function (subtype, createIfMissing) {
1604 var supertypeSet = this.supertypeMap.get(subtype);
1605 if (!supertypeSet && createIfMissing) {
1606 this.supertypeMap.set(subtype, (supertypeSet = new Set()));
1607 }
1608 return supertypeSet;
1609 };
1610 Policies.prototype.fragmentMatches = function (fragment, typename, result, variables) {
1611 var _this = this;
1612 if (!fragment.typeCondition)
1613 return true;
1614 if (!typename)
1615 return false;
1616 var supertype = fragment.typeCondition.name.value;
1617 if (typename === supertype)
1618 return true;
1619 if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {
1620 var typenameSupertypeSet = this.getSupertypeSet(typename, true);
1621 var workQueue_1 = [typenameSupertypeSet];
1622 var maybeEnqueue_1 = function (subtype) {
1623 var supertypeSet = _this.getSupertypeSet(subtype, false);
1624 if (supertypeSet &&
1625 supertypeSet.size &&
1626 workQueue_1.indexOf(supertypeSet) < 0) {
1627 workQueue_1.push(supertypeSet);
1628 }
1629 };
1630 var needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);
1631 var checkingFuzzySubtypes = false;
1632 for (var i = 0; i < workQueue_1.length; ++i) {
1633 var supertypeSet = workQueue_1[i];
1634 if (supertypeSet.has(supertype)) {
1635 if (!typenameSupertypeSet.has(supertype)) {
1636 if (checkingFuzzySubtypes) {
1637 globalThis.__DEV__ !== false && globals.invariant.warn(6, typename, supertype);
1638 }
1639 typenameSupertypeSet.add(supertype);
1640 }
1641 return true;
1642 }
1643 supertypeSet.forEach(maybeEnqueue_1);
1644 if (needToCheckFuzzySubtypes &&
1645 i === workQueue_1.length - 1 &&
1646 selectionSetMatchesResult(fragment.selectionSet, result, variables)) {
1647 needToCheckFuzzySubtypes = false;
1648 checkingFuzzySubtypes = true;
1649 this.fuzzySubtypes.forEach(function (regExp, fuzzyString) {
1650 var match = typename.match(regExp);
1651 if (match && match[0] === typename) {
1652 maybeEnqueue_1(fuzzyString);
1653 }
1654 });
1655 }
1656 }
1657 }
1658 return false;
1659 };
1660 Policies.prototype.hasKeyArgs = function (typename, fieldName) {
1661 var policy = this.getFieldPolicy(typename, fieldName, false);
1662 return !!(policy && policy.keyFn);
1663 };
1664 Policies.prototype.getStoreFieldName = function (fieldSpec) {
1665 var typename = fieldSpec.typename, fieldName = fieldSpec.fieldName;
1666 var policy = this.getFieldPolicy(typename, fieldName, false);
1667 var storeFieldName;
1668 var keyFn = policy && policy.keyFn;
1669 if (keyFn && typename) {
1670 var context = {
1671 typename: typename,
1672 fieldName: fieldName,
1673 field: fieldSpec.field || null,
1674 variables: fieldSpec.variables,
1675 };
1676 var args = argsFromFieldSpecifier(fieldSpec);
1677 while (keyFn) {
1678 var specifierOrString = keyFn(args, context);
1679 if (utilities.isArray(specifierOrString)) {
1680 keyFn = keyArgsFnFromSpecifier(specifierOrString);
1681 }
1682 else {
1683 storeFieldName = specifierOrString || fieldName;
1684 break;
1685 }
1686 }
1687 }
1688 if (storeFieldName === void 0) {
1689 storeFieldName =
1690 fieldSpec.field ?
1691 utilities.storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)
1692 : utilities.getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));
1693 }
1694 if (storeFieldName === false) {
1695 return fieldName;
1696 }
1697 return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName
1698 : fieldName + ":" + storeFieldName;
1699 };
1700 Policies.prototype.readField = function (options, context) {
1701 var objectOrReference = options.from;
1702 if (!objectOrReference)
1703 return;
1704 var nameOrField = options.field || options.fieldName;
1705 if (!nameOrField)
1706 return;
1707 if (options.typename === void 0) {
1708 var typename = context.store.getFieldValue(objectOrReference, "__typename");
1709 if (typename)
1710 options.typename = typename;
1711 }
1712 var storeFieldName = this.getStoreFieldName(options);
1713 var fieldName = fieldNameFromStoreName(storeFieldName);
1714 var existing = context.store.getFieldValue(objectOrReference, storeFieldName);
1715 var policy = this.getFieldPolicy(options.typename, fieldName, false);
1716 var read = policy && policy.read;
1717 if (read) {
1718 var readOptions = makeFieldFunctionOptions(this, objectOrReference, options, context, context.store.getStorage(utilities.isReference(objectOrReference) ?
1719 objectOrReference.__ref
1720 : objectOrReference, storeFieldName));
1721 return cacheSlot.withValue(this.cache, read, [
1722 existing,
1723 readOptions,
1724 ]);
1725 }
1726 return existing;
1727 };
1728 Policies.prototype.getReadFunction = function (typename, fieldName) {
1729 var policy = this.getFieldPolicy(typename, fieldName, false);
1730 return policy && policy.read;
1731 };
1732 Policies.prototype.getMergeFunction = function (parentTypename, fieldName, childTypename) {
1733 var policy = this.getFieldPolicy(parentTypename, fieldName, false);
1734 var merge = policy && policy.merge;
1735 if (!merge && childTypename) {
1736 policy = this.getTypePolicy(childTypename);
1737 merge = policy && policy.merge;
1738 }
1739 return merge;
1740 };
1741 Policies.prototype.runMergeFunction = function (existing, incoming, _a, context, storage) {
1742 var field = _a.field, typename = _a.typename, merge = _a.merge;
1743 if (merge === mergeTrueFn) {
1744 return makeMergeObjectsFunction(context.store)(existing, incoming);
1745 }
1746 if (merge === mergeFalseFn) {
1747 return incoming;
1748 }
1749 if (context.overwrite) {
1750 existing = void 0;
1751 }
1752 return merge(existing, incoming, makeFieldFunctionOptions(this,
1753 void 0, {
1754 typename: typename,
1755 fieldName: field.name.value,
1756 field: field,
1757 variables: context.variables,
1758 }, context, storage || Object.create(null)));
1759 };
1760 return Policies;
1761}());
1762function makeFieldFunctionOptions(policies, objectOrReference, fieldSpec, context, storage) {
1763 var storeFieldName = policies.getStoreFieldName(fieldSpec);
1764 var fieldName = fieldNameFromStoreName(storeFieldName);
1765 var variables = fieldSpec.variables || context.variables;
1766 var _a = context.store, toReference = _a.toReference, canRead = _a.canRead;
1767 return {
1768 args: argsFromFieldSpecifier(fieldSpec),
1769 field: fieldSpec.field || null,
1770 fieldName: fieldName,
1771 storeFieldName: storeFieldName,
1772 variables: variables,
1773 isReference: utilities.isReference,
1774 toReference: toReference,
1775 storage: storage,
1776 cache: policies.cache,
1777 canRead: canRead,
1778 readField: function () {
1779 return policies.readField(normalizeReadFieldOptions(arguments, objectOrReference, variables), context);
1780 },
1781 mergeObjects: makeMergeObjectsFunction(context.store),
1782 };
1783}
1784function normalizeReadFieldOptions(readFieldArgs, objectOrReference, variables) {
1785 var fieldNameOrOptions = readFieldArgs[0], from = readFieldArgs[1], argc = readFieldArgs.length;
1786 var options;
1787 if (typeof fieldNameOrOptions === "string") {
1788 options = {
1789 fieldName: fieldNameOrOptions,
1790 from: argc > 1 ? from : objectOrReference,
1791 };
1792 }
1793 else {
1794 options = tslib.__assign({}, fieldNameOrOptions);
1795 if (!hasOwn.call(options, "from")) {
1796 options.from = objectOrReference;
1797 }
1798 }
1799 if (globalThis.__DEV__ !== false && options.from === void 0) {
1800 globalThis.__DEV__ !== false && globals.invariant.warn(7, utilities.stringifyForDisplay(Array.from(readFieldArgs)));
1801 }
1802 if (void 0 === options.variables) {
1803 options.variables = variables;
1804 }
1805 return options;
1806}
1807function makeMergeObjectsFunction(store) {
1808 return function mergeObjects(existing, incoming) {
1809 if (utilities.isArray(existing) || utilities.isArray(incoming)) {
1810 throw globals.newInvariantError(8);
1811 }
1812 if (utilities.isNonNullObject(existing) && utilities.isNonNullObject(incoming)) {
1813 var eType = store.getFieldValue(existing, "__typename");
1814 var iType = store.getFieldValue(incoming, "__typename");
1815 var typesDiffer = eType && iType && eType !== iType;
1816 if (typesDiffer) {
1817 return incoming;
1818 }
1819 if (utilities.isReference(existing) && storeValueIsStoreObject(incoming)) {
1820 store.merge(existing.__ref, incoming);
1821 return existing;
1822 }
1823 if (storeValueIsStoreObject(existing) && utilities.isReference(incoming)) {
1824 store.merge(existing, incoming.__ref);
1825 return incoming;
1826 }
1827 if (storeValueIsStoreObject(existing) &&
1828 storeValueIsStoreObject(incoming)) {
1829 return tslib.__assign(tslib.__assign({}, existing), incoming);
1830 }
1831 }
1832 return incoming;
1833 };
1834}
1835
1836function getContextFlavor(context, clientOnly, deferred) {
1837 var key = "".concat(clientOnly).concat(deferred);
1838 var flavored = context.flavors.get(key);
1839 if (!flavored) {
1840 context.flavors.set(key, (flavored =
1841 context.clientOnly === clientOnly && context.deferred === deferred ?
1842 context
1843 : tslib.__assign(tslib.__assign({}, context), { clientOnly: clientOnly, deferred: deferred })));
1844 }
1845 return flavored;
1846}
1847var StoreWriter = (function () {
1848 function StoreWriter(cache, reader, fragments) {
1849 this.cache = cache;
1850 this.reader = reader;
1851 this.fragments = fragments;
1852 }
1853 StoreWriter.prototype.writeToStore = function (store, _a) {
1854 var _this = this;
1855 var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;
1856 var operationDefinition = utilities.getOperationDefinition(query);
1857 var merger = makeProcessedFieldsMerger();
1858 variables = tslib.__assign(tslib.__assign({}, utilities.getDefaultValues(operationDefinition)), variables);
1859 var context = tslib.__assign(tslib.__assign({ store: store, written: Object.create(null), merge: function (existing, incoming) {
1860 return merger.merge(existing, incoming);
1861 }, variables: variables, varString: utilities.canonicalStringify(variables) }, extractFragmentContext(query, this.fragments)), { overwrite: !!overwrite, incomingById: new Map(), clientOnly: false, deferred: false, flavors: new Map() });
1862 var ref = this.processSelectionSet({
1863 result: result || Object.create(null),
1864 dataId: dataId,
1865 selectionSet: operationDefinition.selectionSet,
1866 mergeTree: { map: new Map() },
1867 context: context,
1868 });
1869 if (!utilities.isReference(ref)) {
1870 throw globals.newInvariantError(11, result);
1871 }
1872 context.incomingById.forEach(function (_a, dataId) {
1873 var storeObject = _a.storeObject, mergeTree = _a.mergeTree, fieldNodeSet = _a.fieldNodeSet;
1874 var entityRef = utilities.makeReference(dataId);
1875 if (mergeTree && mergeTree.map.size) {
1876 var applied = _this.applyMerges(mergeTree, entityRef, storeObject, context);
1877 if (utilities.isReference(applied)) {
1878 return;
1879 }
1880 storeObject = applied;
1881 }
1882 if (globalThis.__DEV__ !== false && !context.overwrite) {
1883 var fieldsWithSelectionSets_1 = Object.create(null);
1884 fieldNodeSet.forEach(function (field) {
1885 if (field.selectionSet) {
1886 fieldsWithSelectionSets_1[field.name.value] = true;
1887 }
1888 });
1889 var hasSelectionSet_1 = function (storeFieldName) {
1890 return fieldsWithSelectionSets_1[fieldNameFromStoreName(storeFieldName)] ===
1891 true;
1892 };
1893 var hasMergeFunction_1 = function (storeFieldName) {
1894 var childTree = mergeTree && mergeTree.map.get(storeFieldName);
1895 return Boolean(childTree && childTree.info && childTree.info.merge);
1896 };
1897 Object.keys(storeObject).forEach(function (storeFieldName) {
1898 if (hasSelectionSet_1(storeFieldName) &&
1899 !hasMergeFunction_1(storeFieldName)) {
1900 warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);
1901 }
1902 });
1903 }
1904 store.merge(dataId, storeObject);
1905 });
1906 store.retain(ref.__ref);
1907 return ref;
1908 };
1909 StoreWriter.prototype.processSelectionSet = function (_a) {
1910 var _this = this;
1911 var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context,
1912 mergeTree = _a.mergeTree;
1913 var policies = this.cache.policies;
1914 var incoming = Object.create(null);
1915 var typename = (dataId && policies.rootTypenamesById[dataId]) ||
1916 utilities.getTypenameFromResult(result, selectionSet, context.fragmentMap) ||
1917 (dataId && context.store.get(dataId, "__typename"));
1918 if ("string" === typeof typename) {
1919 incoming.__typename = typename;
1920 }
1921 var readField = function () {
1922 var options = normalizeReadFieldOptions(arguments, incoming, context.variables);
1923 if (utilities.isReference(options.from)) {
1924 var info = context.incomingById.get(options.from.__ref);
1925 if (info) {
1926 var result_1 = policies.readField(tslib.__assign(tslib.__assign({}, options), { from: info.storeObject }), context);
1927 if (result_1 !== void 0) {
1928 return result_1;
1929 }
1930 }
1931 }
1932 return policies.readField(options, context);
1933 };
1934 var fieldNodeSet = new Set();
1935 this.flattenFields(selectionSet, result,
1936 context, typename).forEach(function (context, field) {
1937 var _a;
1938 var resultFieldKey = utilities.resultKeyNameFromField(field);
1939 var value = result[resultFieldKey];
1940 fieldNodeSet.add(field);
1941 if (value !== void 0) {
1942 var storeFieldName = policies.getStoreFieldName({
1943 typename: typename,
1944 fieldName: field.name.value,
1945 field: field,
1946 variables: context.variables,
1947 });
1948 var childTree = getChildMergeTree(mergeTree, storeFieldName);
1949 var incomingValue = _this.processFieldValue(value, field,
1950 field.selectionSet ?
1951 getContextFlavor(context, false, false)
1952 : context, childTree);
1953 var childTypename = void 0;
1954 if (field.selectionSet &&
1955 (utilities.isReference(incomingValue) || storeValueIsStoreObject(incomingValue))) {
1956 childTypename = readField("__typename", incomingValue);
1957 }
1958 var merge = policies.getMergeFunction(typename, field.name.value, childTypename);
1959 if (merge) {
1960 childTree.info = {
1961 field: field,
1962 typename: typename,
1963 merge: merge,
1964 };
1965 }
1966 else {
1967 maybeRecycleChildMergeTree(mergeTree, storeFieldName);
1968 }
1969 incoming = context.merge(incoming, (_a = {},
1970 _a[storeFieldName] = incomingValue,
1971 _a));
1972 }
1973 else if (globalThis.__DEV__ !== false &&
1974 !context.clientOnly &&
1975 !context.deferred &&
1976 !utilities.addTypenameToDocument.added(field) &&
1977 !policies.getReadFunction(typename, field.name.value)) {
1978 globalThis.__DEV__ !== false && globals.invariant.error(12, utilities.resultKeyNameFromField(field), result);
1979 }
1980 });
1981 try {
1982 var _b = policies.identify(result, {
1983 typename: typename,
1984 selectionSet: selectionSet,
1985 fragmentMap: context.fragmentMap,
1986 storeObject: incoming,
1987 readField: readField,
1988 }), id = _b[0], keyObject = _b[1];
1989 dataId = dataId || id;
1990 if (keyObject) {
1991 incoming = context.merge(incoming, keyObject);
1992 }
1993 }
1994 catch (e) {
1995 if (!dataId)
1996 throw e;
1997 }
1998 if ("string" === typeof dataId) {
1999 var dataRef = utilities.makeReference(dataId);
2000 var sets = context.written[dataId] || (context.written[dataId] = []);
2001 if (sets.indexOf(selectionSet) >= 0)
2002 return dataRef;
2003 sets.push(selectionSet);
2004 if (this.reader &&
2005 this.reader.isFresh(result, dataRef, selectionSet, context)) {
2006 return dataRef;
2007 }
2008 var previous_1 = context.incomingById.get(dataId);
2009 if (previous_1) {
2010 previous_1.storeObject = context.merge(previous_1.storeObject, incoming);
2011 previous_1.mergeTree = mergeMergeTrees(previous_1.mergeTree, mergeTree);
2012 fieldNodeSet.forEach(function (field) { return previous_1.fieldNodeSet.add(field); });
2013 }
2014 else {
2015 context.incomingById.set(dataId, {
2016 storeObject: incoming,
2017 mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,
2018 fieldNodeSet: fieldNodeSet,
2019 });
2020 }
2021 return dataRef;
2022 }
2023 return incoming;
2024 };
2025 StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {
2026 var _this = this;
2027 if (!field.selectionSet || value === null) {
2028 return globalThis.__DEV__ !== false ? utilities.cloneDeep(value) : value;
2029 }
2030 if (utilities.isArray(value)) {
2031 return value.map(function (item, i) {
2032 var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));
2033 maybeRecycleChildMergeTree(mergeTree, i);
2034 return value;
2035 });
2036 }
2037 return this.processSelectionSet({
2038 result: value,
2039 selectionSet: field.selectionSet,
2040 context: context,
2041 mergeTree: mergeTree,
2042 });
2043 };
2044 StoreWriter.prototype.flattenFields = function (selectionSet, result, context, typename) {
2045 if (typename === void 0) { typename = utilities.getTypenameFromResult(result, selectionSet, context.fragmentMap); }
2046 var fieldMap = new Map();
2047 var policies = this.cache.policies;
2048 var limitingTrie = new trie.Trie(false);
2049 (function flatten(selectionSet, inheritedContext) {
2050 var visitedNode = limitingTrie.lookup(selectionSet,
2051 inheritedContext.clientOnly, inheritedContext.deferred);
2052 if (visitedNode.visited)
2053 return;
2054 visitedNode.visited = true;
2055 selectionSet.selections.forEach(function (selection) {
2056 if (!utilities.shouldInclude(selection, context.variables))
2057 return;
2058 var clientOnly = inheritedContext.clientOnly, deferred = inheritedContext.deferred;
2059 if (
2060 !(clientOnly && deferred) &&
2061 utilities.isNonEmptyArray(selection.directives)) {
2062 selection.directives.forEach(function (dir) {
2063 var name = dir.name.value;
2064 if (name === "client")
2065 clientOnly = true;
2066 if (name === "defer") {
2067 var args = utilities.argumentsObjectFromField(dir, context.variables);
2068 if (!args || args.if !== false) {
2069 deferred = true;
2070 }
2071 }
2072 });
2073 }
2074 if (utilities.isField(selection)) {
2075 var existing = fieldMap.get(selection);
2076 if (existing) {
2077 clientOnly = clientOnly && existing.clientOnly;
2078 deferred = deferred && existing.deferred;
2079 }
2080 fieldMap.set(selection, getContextFlavor(context, clientOnly, deferred));
2081 }
2082 else {
2083 var fragment = utilities.getFragmentFromSelection(selection, context.lookupFragment);
2084 if (!fragment && selection.kind === graphql.Kind.FRAGMENT_SPREAD) {
2085 throw globals.newInvariantError(13, selection.name.value);
2086 }
2087 if (fragment &&
2088 policies.fragmentMatches(fragment, typename, result, context.variables)) {
2089 flatten(fragment.selectionSet, getContextFlavor(context, clientOnly, deferred));
2090 }
2091 }
2092 });
2093 })(selectionSet, context);
2094 return fieldMap;
2095 };
2096 StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {
2097 var _a;
2098 var _this = this;
2099 if (mergeTree.map.size && !utilities.isReference(incoming)) {
2100 var e_1 =
2101 (!utilities.isArray(incoming) &&
2102 (utilities.isReference(existing) || storeValueIsStoreObject(existing))) ?
2103 existing
2104 : void 0;
2105 var i_1 = incoming;
2106 if (e_1 && !getStorageArgs) {
2107 getStorageArgs = [utilities.isReference(e_1) ? e_1.__ref : e_1];
2108 }
2109 var changedFields_1;
2110 var getValue_1 = function (from, name) {
2111 return (utilities.isArray(from) ?
2112 typeof name === "number" ?
2113 from[name]
2114 : void 0
2115 : context.store.getFieldValue(from, String(name)));
2116 };
2117 mergeTree.map.forEach(function (childTree, storeFieldName) {
2118 var eVal = getValue_1(e_1, storeFieldName);
2119 var iVal = getValue_1(i_1, storeFieldName);
2120 if (void 0 === iVal)
2121 return;
2122 if (getStorageArgs) {
2123 getStorageArgs.push(storeFieldName);
2124 }
2125 var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);
2126 if (aVal !== iVal) {
2127 changedFields_1 = changedFields_1 || new Map();
2128 changedFields_1.set(storeFieldName, aVal);
2129 }
2130 if (getStorageArgs) {
2131 globals.invariant(getStorageArgs.pop() === storeFieldName);
2132 }
2133 });
2134 if (changedFields_1) {
2135 incoming = (utilities.isArray(i_1) ? i_1.slice(0) : tslib.__assign({}, i_1));
2136 changedFields_1.forEach(function (value, name) {
2137 incoming[name] = value;
2138 });
2139 }
2140 }
2141 if (mergeTree.info) {
2142 return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));
2143 }
2144 return incoming;
2145 };
2146 return StoreWriter;
2147}());
2148var emptyMergeTreePool = [];
2149function getChildMergeTree(_a, name) {
2150 var map = _a.map;
2151 if (!map.has(name)) {
2152 map.set(name, emptyMergeTreePool.pop() || { map: new Map() });
2153 }
2154 return map.get(name);
2155}
2156function mergeMergeTrees(left, right) {
2157 if (left === right || !right || mergeTreeIsEmpty(right))
2158 return left;
2159 if (!left || mergeTreeIsEmpty(left))
2160 return right;
2161 var info = left.info && right.info ? tslib.__assign(tslib.__assign({}, left.info), right.info) : left.info || right.info;
2162 var needToMergeMaps = left.map.size && right.map.size;
2163 var map = needToMergeMaps ? new Map()
2164 : left.map.size ? left.map
2165 : right.map;
2166 var merged = { info: info, map: map };
2167 if (needToMergeMaps) {
2168 var remainingRightKeys_1 = new Set(right.map.keys());
2169 left.map.forEach(function (leftTree, key) {
2170 merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));
2171 remainingRightKeys_1.delete(key);
2172 });
2173 remainingRightKeys_1.forEach(function (key) {
2174 merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));
2175 });
2176 }
2177 return merged;
2178}
2179function mergeTreeIsEmpty(tree) {
2180 return !tree || !(tree.info || tree.map.size);
2181}
2182function maybeRecycleChildMergeTree(_a, name) {
2183 var map = _a.map;
2184 var childTree = map.get(name);
2185 if (childTree && mergeTreeIsEmpty(childTree)) {
2186 emptyMergeTreePool.push(childTree);
2187 map.delete(name);
2188 }
2189}
2190var warnings = new Set();
2191function warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {
2192 var getChild = function (objOrRef) {
2193 var child = store.getFieldValue(objOrRef, storeFieldName);
2194 return typeof child === "object" && child;
2195 };
2196 var existing = getChild(existingRef);
2197 if (!existing)
2198 return;
2199 var incoming = getChild(incomingObj);
2200 if (!incoming)
2201 return;
2202 if (utilities.isReference(existing))
2203 return;
2204 if (equal.equal(existing, incoming))
2205 return;
2206 if (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {
2207 return;
2208 }
2209 var parentType = store.getFieldValue(existingRef, "__typename") ||
2210 store.getFieldValue(incomingObj, "__typename");
2211 var fieldName = fieldNameFromStoreName(storeFieldName);
2212 var typeDotName = "".concat(parentType, ".").concat(fieldName);
2213 if (warnings.has(typeDotName))
2214 return;
2215 warnings.add(typeDotName);
2216 var childTypenames = [];
2217 if (!utilities.isArray(existing) && !utilities.isArray(incoming)) {
2218 [existing, incoming].forEach(function (child) {
2219 var typename = store.getFieldValue(child, "__typename");
2220 if (typeof typename === "string" && !childTypenames.includes(typename)) {
2221 childTypenames.push(typename);
2222 }
2223 });
2224 }
2225 globalThis.__DEV__ !== false && globals.invariant.warn(14, fieldName, parentType, childTypenames.length ?
2226 "either ensure all objects of type " +
2227 childTypenames.join(" and ") +
2228 " have an ID or a custom merge function, or "
2229 : "", typeDotName, tslib.__assign({}, existing), tslib.__assign({}, incoming));
2230}
2231
2232var InMemoryCache = (function (_super) {
2233 tslib.__extends(InMemoryCache, _super);
2234 function InMemoryCache(config) {
2235 if (config === void 0) { config = {}; }
2236 var _this = _super.call(this) || this;
2237 _this.watches = new Set();
2238 _this.addTypenameTransform = new utilities.DocumentTransform(utilities.addTypenameToDocument);
2239 _this.assumeImmutableResults = true;
2240 _this.makeVar = makeVar;
2241 _this.txCount = 0;
2242 _this.config = normalizeConfig(config);
2243 _this.addTypename = !!_this.config.addTypename;
2244 _this.policies = new Policies({
2245 cache: _this,
2246 dataIdFromObject: _this.config.dataIdFromObject,
2247 possibleTypes: _this.config.possibleTypes,
2248 typePolicies: _this.config.typePolicies,
2249 });
2250 _this.init();
2251 return _this;
2252 }
2253 InMemoryCache.prototype.init = function () {
2254 var rootStore = (this.data = new exports.EntityStore.Root({
2255 policies: this.policies,
2256 resultCaching: this.config.resultCaching,
2257 }));
2258 this.optimisticData = rootStore.stump;
2259 this.resetResultCache();
2260 };
2261 InMemoryCache.prototype.resetResultCache = function (resetResultIdentities) {
2262 var _this = this;
2263 var previousReader = this.storeReader;
2264 var fragments = this.config.fragments;
2265 this.storeWriter = new StoreWriter(this, (this.storeReader = new StoreReader({
2266 cache: this,
2267 addTypename: this.addTypename,
2268 resultCacheMaxSize: this.config.resultCacheMaxSize,
2269 canonizeResults: shouldCanonizeResults(this.config),
2270 canon: resetResultIdentities ? void 0 : (previousReader && previousReader.canon),
2271 fragments: fragments,
2272 })), fragments);
2273 this.maybeBroadcastWatch = optimism.wrap(function (c, options) {
2274 return _this.broadcastWatch(c, options);
2275 }, {
2276 max: this.config.resultCacheMaxSize ||
2277 utilities.cacheSizes["inMemoryCache.maybeBroadcastWatch"] ||
2278 5000 ,
2279 makeCacheKey: function (c) {
2280 var store = c.optimistic ? _this.optimisticData : _this.data;
2281 if (supportsResultCaching(store)) {
2282 var optimistic = c.optimistic, id = c.id, variables = c.variables;
2283 return store.makeCacheKey(c.query,
2284 c.callback, utilities.canonicalStringify({ optimistic: optimistic, id: id, variables: variables }));
2285 }
2286 },
2287 });
2288 new Set([this.data.group, this.optimisticData.group]).forEach(function (group) {
2289 return group.resetCaching();
2290 });
2291 };
2292 InMemoryCache.prototype.restore = function (data) {
2293 this.init();
2294 if (data)
2295 this.data.replace(data);
2296 return this;
2297 };
2298 InMemoryCache.prototype.extract = function (optimistic) {
2299 if (optimistic === void 0) { optimistic = false; }
2300 return (optimistic ? this.optimisticData : this.data).extract();
2301 };
2302 InMemoryCache.prototype.read = function (options) {
2303 var
2304 _a = options.returnPartialData,
2305 returnPartialData = _a === void 0 ? false : _a;
2306 try {
2307 return (this.storeReader.diffQueryAgainstStore(tslib.__assign(tslib.__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, config: this.config, returnPartialData: returnPartialData })).result || null);
2308 }
2309 catch (e) {
2310 if (e instanceof MissingFieldError) {
2311 return null;
2312 }
2313 throw e;
2314 }
2315 };
2316 InMemoryCache.prototype.write = function (options) {
2317 try {
2318 ++this.txCount;
2319 return this.storeWriter.writeToStore(this.data, options);
2320 }
2321 finally {
2322 if (!--this.txCount && options.broadcast !== false) {
2323 this.broadcastWatches();
2324 }
2325 }
2326 };
2327 InMemoryCache.prototype.modify = function (options) {
2328 if (hasOwn.call(options, "id") && !options.id) {
2329 return false;
2330 }
2331 var store = ((options.optimistic)
2332 ) ?
2333 this.optimisticData
2334 : this.data;
2335 try {
2336 ++this.txCount;
2337 return store.modify(options.id || "ROOT_QUERY", options.fields);
2338 }
2339 finally {
2340 if (!--this.txCount && options.broadcast !== false) {
2341 this.broadcastWatches();
2342 }
2343 }
2344 };
2345 InMemoryCache.prototype.diff = function (options) {
2346 return this.storeReader.diffQueryAgainstStore(tslib.__assign(tslib.__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, rootId: options.id || "ROOT_QUERY", config: this.config }));
2347 };
2348 InMemoryCache.prototype.watch = function (watch) {
2349 var _this = this;
2350 if (!this.watches.size) {
2351 recallCache(this);
2352 }
2353 this.watches.add(watch);
2354 if (watch.immediate) {
2355 this.maybeBroadcastWatch(watch);
2356 }
2357 return function () {
2358 if (_this.watches.delete(watch) && !_this.watches.size) {
2359 forgetCache(_this);
2360 }
2361 _this.maybeBroadcastWatch.forget(watch);
2362 };
2363 };
2364 InMemoryCache.prototype.gc = function (options) {
2365 var _a;
2366 utilities.canonicalStringify.reset();
2367 utilities.print.reset();
2368 this.addTypenameTransform.resetCache();
2369 (_a = this.config.fragments) === null || _a === void 0 ? void 0 : _a.resetCaches();
2370 var ids = this.optimisticData.gc();
2371 if (options && !this.txCount) {
2372 if (options.resetResultCache) {
2373 this.resetResultCache(options.resetResultIdentities);
2374 }
2375 else if (options.resetResultIdentities) {
2376 this.storeReader.resetCanon();
2377 }
2378 }
2379 return ids;
2380 };
2381 InMemoryCache.prototype.retain = function (rootId, optimistic) {
2382 return (optimistic ? this.optimisticData : this.data).retain(rootId);
2383 };
2384 InMemoryCache.prototype.release = function (rootId, optimistic) {
2385 return (optimistic ? this.optimisticData : this.data).release(rootId);
2386 };
2387 InMemoryCache.prototype.identify = function (object) {
2388 if (utilities.isReference(object))
2389 return object.__ref;
2390 try {
2391 return this.policies.identify(object)[0];
2392 }
2393 catch (e) {
2394 globalThis.__DEV__ !== false && globals.invariant.warn(e);
2395 }
2396 };
2397 InMemoryCache.prototype.evict = function (options) {
2398 if (!options.id) {
2399 if (hasOwn.call(options, "id")) {
2400 return false;
2401 }
2402 options = tslib.__assign(tslib.__assign({}, options), { id: "ROOT_QUERY" });
2403 }
2404 try {
2405 ++this.txCount;
2406 return this.optimisticData.evict(options, this.data);
2407 }
2408 finally {
2409 if (!--this.txCount && options.broadcast !== false) {
2410 this.broadcastWatches();
2411 }
2412 }
2413 };
2414 InMemoryCache.prototype.reset = function (options) {
2415 var _this = this;
2416 this.init();
2417 utilities.canonicalStringify.reset();
2418 if (options && options.discardWatches) {
2419 this.watches.forEach(function (watch) { return _this.maybeBroadcastWatch.forget(watch); });
2420 this.watches.clear();
2421 forgetCache(this);
2422 }
2423 else {
2424 this.broadcastWatches();
2425 }
2426 return Promise.resolve();
2427 };
2428 InMemoryCache.prototype.removeOptimistic = function (idToRemove) {
2429 var newOptimisticData = this.optimisticData.removeLayer(idToRemove);
2430 if (newOptimisticData !== this.optimisticData) {
2431 this.optimisticData = newOptimisticData;
2432 this.broadcastWatches();
2433 }
2434 };
2435 InMemoryCache.prototype.batch = function (options) {
2436 var _this = this;
2437 var update = options.update, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, removeOptimistic = options.removeOptimistic, onWatchUpdated = options.onWatchUpdated;
2438 var updateResult;
2439 var perform = function (layer) {
2440 var _a = _this, data = _a.data, optimisticData = _a.optimisticData;
2441 ++_this.txCount;
2442 if (layer) {
2443 _this.data = _this.optimisticData = layer;
2444 }
2445 try {
2446 return (updateResult = update(_this));
2447 }
2448 finally {
2449 --_this.txCount;
2450 _this.data = data;
2451 _this.optimisticData = optimisticData;
2452 }
2453 };
2454 var alreadyDirty = new Set();
2455 if (onWatchUpdated && !this.txCount) {
2456 this.broadcastWatches(tslib.__assign(tslib.__assign({}, options), { onWatchUpdated: function (watch) {
2457 alreadyDirty.add(watch);
2458 return false;
2459 } }));
2460 }
2461 if (typeof optimistic === "string") {
2462 this.optimisticData = this.optimisticData.addLayer(optimistic, perform);
2463 }
2464 else if (optimistic === false) {
2465 perform(this.data);
2466 }
2467 else {
2468 perform();
2469 }
2470 if (typeof removeOptimistic === "string") {
2471 this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);
2472 }
2473 if (onWatchUpdated && alreadyDirty.size) {
2474 this.broadcastWatches(tslib.__assign(tslib.__assign({}, options), { onWatchUpdated: function (watch, diff) {
2475 var result = onWatchUpdated.call(this, watch, diff);
2476 if (result !== false) {
2477 alreadyDirty.delete(watch);
2478 }
2479 return result;
2480 } }));
2481 if (alreadyDirty.size) {
2482 alreadyDirty.forEach(function (watch) { return _this.maybeBroadcastWatch.dirty(watch); });
2483 }
2484 }
2485 else {
2486 this.broadcastWatches(options);
2487 }
2488 return updateResult;
2489 };
2490 InMemoryCache.prototype.performTransaction = function (update, optimisticId) {
2491 return this.batch({
2492 update: update,
2493 optimistic: optimisticId || optimisticId !== null,
2494 });
2495 };
2496 InMemoryCache.prototype.transformDocument = function (document) {
2497 return this.addTypenameToDocument(this.addFragmentsToDocument(document));
2498 };
2499 InMemoryCache.prototype.broadcastWatches = function (options) {
2500 var _this = this;
2501 if (!this.txCount) {
2502 this.watches.forEach(function (c) { return _this.maybeBroadcastWatch(c, options); });
2503 }
2504 };
2505 InMemoryCache.prototype.addFragmentsToDocument = function (document) {
2506 var fragments = this.config.fragments;
2507 return fragments ? fragments.transform(document) : document;
2508 };
2509 InMemoryCache.prototype.addTypenameToDocument = function (document) {
2510 if (this.addTypename) {
2511 return this.addTypenameTransform.transformDocument(document);
2512 }
2513 return document;
2514 };
2515 InMemoryCache.prototype.broadcastWatch = function (c, options) {
2516 var lastDiff = c.lastDiff;
2517 var diff = this.diff(c);
2518 if (options) {
2519 if (c.optimistic && typeof options.optimistic === "string") {
2520 diff.fromOptimisticTransaction = true;
2521 }
2522 if (options.onWatchUpdated &&
2523 options.onWatchUpdated.call(this, c, diff, lastDiff) === false) {
2524 return;
2525 }
2526 }
2527 if (!lastDiff || !equal.equal(lastDiff.result, diff.result)) {
2528 c.callback((c.lastDiff = diff), lastDiff);
2529 }
2530 };
2531 return InMemoryCache;
2532}(ApolloCache));
2533if (globalThis.__DEV__ !== false) {
2534 InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;
2535}
2536
2537function createFragmentRegistry() {
2538 var fragments = [];
2539 for (var _i = 0; _i < arguments.length; _i++) {
2540 fragments[_i] = arguments[_i];
2541 }
2542 return new (FragmentRegistry.bind.apply(FragmentRegistry, tslib.__spreadArray([void 0], fragments, false)))();
2543}
2544var FragmentRegistry = (function () {
2545 function FragmentRegistry() {
2546 var fragments = [];
2547 for (var _i = 0; _i < arguments.length; _i++) {
2548 fragments[_i] = arguments[_i];
2549 }
2550 this.registry = Object.create(null);
2551 this.resetCaches();
2552 if (fragments.length) {
2553 this.register.apply(this, fragments);
2554 }
2555 }
2556 FragmentRegistry.prototype.register = function () {
2557 var _this = this;
2558 var fragments = [];
2559 for (var _i = 0; _i < arguments.length; _i++) {
2560 fragments[_i] = arguments[_i];
2561 }
2562 var definitions = new Map();
2563 fragments.forEach(function (doc) {
2564 utilities.getFragmentDefinitions(doc).forEach(function (node) {
2565 definitions.set(node.name.value, node);
2566 });
2567 });
2568 definitions.forEach(function (node, name) {
2569 if (node !== _this.registry[name]) {
2570 _this.registry[name] = node;
2571 _this.invalidate(name);
2572 }
2573 });
2574 return this;
2575 };
2576 FragmentRegistry.prototype.invalidate = function (name) { };
2577 FragmentRegistry.prototype.resetCaches = function () {
2578 var proto = FragmentRegistry.prototype;
2579 this.invalidate = (this.lookup = optimism.wrap(proto.lookup.bind(this), {
2580 makeCacheKey: function (arg) { return arg; },
2581 max: utilities.cacheSizes["fragmentRegistry.lookup"] ||
2582 1000 ,
2583 })).dirty;
2584 this.transform = optimism.wrap(proto.transform.bind(this), {
2585 cache: caches.WeakCache,
2586 max: utilities.cacheSizes["fragmentRegistry.transform"] ||
2587 2000 ,
2588 });
2589 this.findFragmentSpreads = optimism.wrap(proto.findFragmentSpreads.bind(this), {
2590 cache: caches.WeakCache,
2591 max: utilities.cacheSizes["fragmentRegistry.findFragmentSpreads"] ||
2592 4000 ,
2593 });
2594 };
2595 FragmentRegistry.prototype.lookup = function (fragmentName) {
2596 return this.registry[fragmentName] || null;
2597 };
2598 FragmentRegistry.prototype.transform = function (document) {
2599 var _this = this;
2600 var defined = new Map();
2601 utilities.getFragmentDefinitions(document).forEach(function (def) {
2602 defined.set(def.name.value, def);
2603 });
2604 var unbound = new Set();
2605 var enqueue = function (spreadName) {
2606 if (!defined.has(spreadName)) {
2607 unbound.add(spreadName);
2608 }
2609 };
2610 var enqueueChildSpreads = function (node) {
2611 return Object.keys(_this.findFragmentSpreads(node)).forEach(enqueue);
2612 };
2613 enqueueChildSpreads(document);
2614 var missing = [];
2615 var map = Object.create(null);
2616 unbound.forEach(function (fragmentName) {
2617 var knownFragmentDef = defined.get(fragmentName);
2618 if (knownFragmentDef) {
2619 enqueueChildSpreads((map[fragmentName] = knownFragmentDef));
2620 }
2621 else {
2622 missing.push(fragmentName);
2623 var def = _this.lookup(fragmentName);
2624 if (def) {
2625 enqueueChildSpreads((map[fragmentName] = def));
2626 }
2627 }
2628 });
2629 if (missing.length) {
2630 var defsToAppend_1 = [];
2631 missing.forEach(function (name) {
2632 var def = map[name];
2633 if (def) {
2634 defsToAppend_1.push(def);
2635 }
2636 });
2637 if (defsToAppend_1.length) {
2638 document = tslib.__assign(tslib.__assign({}, document), { definitions: document.definitions.concat(defsToAppend_1) });
2639 }
2640 }
2641 return document;
2642 };
2643 FragmentRegistry.prototype.findFragmentSpreads = function (root) {
2644 var spreads = Object.create(null);
2645 graphql.visit(root, {
2646 FragmentSpread: function (node) {
2647 spreads[node.name.value] = node;
2648 },
2649 });
2650 return spreads;
2651 };
2652 return FragmentRegistry;
2653}());
2654
2655exports.canonicalStringify = utilities.canonicalStringify;
2656exports.isReference = utilities.isReference;
2657exports.makeReference = utilities.makeReference;
2658exports.ApolloCache = ApolloCache;
2659exports.InMemoryCache = InMemoryCache;
2660exports.MissingFieldError = MissingFieldError;
2661exports.Policies = Policies;
2662exports.cacheSlot = cacheSlot;
2663exports.createFragmentRegistry = createFragmentRegistry;
2664exports.defaultDataIdFromObject = defaultDataIdFromObject;
2665exports.fieldNameFromStoreName = fieldNameFromStoreName;
2666exports.makeVar = makeVar;
2667//# sourceMappingURL=cache.cjs.map