UNPKG

122 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var tslib = require('tslib');
6var globals = require('../utilities/globals');
7var core = require('../link/core');
8var http = require('../link/http');
9var equal = require('@wry/equality');
10var utilities = require('../utilities');
11var cache = require('../cache');
12var errors = require('../errors');
13var trie = require('@wry/trie');
14var graphql = require('graphql');
15var utils = require('../link/utils');
16var tsInvariant = require('ts-invariant');
17var graphqlTag = require('graphql-tag');
18
19function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
20
21var equal__default = /*#__PURE__*/_interopDefaultLegacy(equal);
22
23var version = "3.11.8";
24
25function isNonNullObject(obj) {
26 return obj !== null && typeof obj === "object";
27}
28
29function isNonEmptyArray(value) {
30 return Array.isArray(value) && value.length > 0;
31}
32
33var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
34var defaultReconciler = function (target, source, property) {
35 return this.merge(target[property], source[property]);
36};
37var DeepMerger = (function () {
38 function DeepMerger(reconciler) {
39 if (reconciler === void 0) { reconciler = defaultReconciler; }
40 this.reconciler = reconciler;
41 this.isObject = isNonNullObject;
42 this.pastCopies = new Set();
43 }
44 DeepMerger.prototype.merge = function (target, source) {
45 var _this = this;
46 var context = [];
47 for (var _i = 2; _i < arguments.length; _i++) {
48 context[_i - 2] = arguments[_i];
49 }
50 if (isNonNullObject(source) && isNonNullObject(target)) {
51 Object.keys(source).forEach(function (sourceKey) {
52 if (hasOwnProperty$2.call(target, sourceKey)) {
53 var targetValue = target[sourceKey];
54 if (source[sourceKey] !== targetValue) {
55 var result = _this.reconciler.apply(_this, tslib.__spreadArray([target,
56 source,
57 sourceKey], context, false));
58 if (result !== targetValue) {
59 target = _this.shallowCopyForMerge(target);
60 target[sourceKey] = result;
61 }
62 }
63 }
64 else {
65 target = _this.shallowCopyForMerge(target);
66 target[sourceKey] = source[sourceKey];
67 }
68 });
69 return target;
70 }
71 return source;
72 };
73 DeepMerger.prototype.shallowCopyForMerge = function (value) {
74 if (isNonNullObject(value)) {
75 if (!this.pastCopies.has(value)) {
76 if (Array.isArray(value)) {
77 value = value.slice(0);
78 }
79 else {
80 value = tslib.__assign({ __proto__: Object.getPrototypeOf(value) }, value);
81 }
82 this.pastCopies.add(value);
83 }
84 }
85 return value;
86 };
87 return DeepMerger;
88}());
89
90function isExecutionPatchIncrementalResult(value) {
91 return "incremental" in value;
92}
93function mergeIncrementalData(prevResult, result) {
94 var mergedData = prevResult;
95 var merger = new DeepMerger();
96 if (isExecutionPatchIncrementalResult(result) &&
97 isNonEmptyArray(result.incremental)) {
98 result.incremental.forEach(function (_a) {
99 var data = _a.data, path = _a.path;
100 for (var i = path.length - 1; i >= 0; --i) {
101 var key = path[i];
102 var isNumericKey = !isNaN(+key);
103 var parent_1 = isNumericKey ? [] : {};
104 parent_1[key] = data;
105 data = parent_1;
106 }
107 mergedData = merger.merge(mergedData, data);
108 });
109 }
110 return mergedData;
111}
112
113exports.NetworkStatus = void 0;
114(function (NetworkStatus) {
115 NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
116 NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
117 NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
118 NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
119 NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
120 NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
121 NetworkStatus[NetworkStatus["error"] = 8] = "error";
122})(exports.NetworkStatus || (exports.NetworkStatus = {}));
123function isNetworkRequestInFlight(networkStatus) {
124 return networkStatus ? networkStatus < 7 : false;
125}
126function isNetworkRequestSettled(networkStatus) {
127 return networkStatus === 7 || networkStatus === 8;
128}
129
130function equalByQuery(query, _a, _b, variables) {
131 var aData = _a.data, aRest = tslib.__rest(_a, ["data"]);
132 var bData = _b.data, bRest = tslib.__rest(_b, ["data"]);
133 return (equal__default(aRest, bRest) &&
134 equalBySelectionSet(utilities.getMainDefinition(query).selectionSet, aData, bData, {
135 fragmentMap: utilities.createFragmentMap(utilities.getFragmentDefinitions(query)),
136 variables: variables,
137 }));
138}
139function equalBySelectionSet(selectionSet, aResult, bResult, context) {
140 if (aResult === bResult) {
141 return true;
142 }
143 var seenSelections = new Set();
144 return selectionSet.selections.every(function (selection) {
145 if (seenSelections.has(selection))
146 return true;
147 seenSelections.add(selection);
148 if (!utilities.shouldInclude(selection, context.variables))
149 return true;
150 if (selectionHasNonreactiveDirective(selection))
151 return true;
152 if (utilities.isField(selection)) {
153 var resultKey = utilities.resultKeyNameFromField(selection);
154 var aResultChild = aResult && aResult[resultKey];
155 var bResultChild = bResult && bResult[resultKey];
156 var childSelectionSet = selection.selectionSet;
157 if (!childSelectionSet) {
158 return equal__default(aResultChild, bResultChild);
159 }
160 var aChildIsArray = Array.isArray(aResultChild);
161 var bChildIsArray = Array.isArray(bResultChild);
162 if (aChildIsArray !== bChildIsArray)
163 return false;
164 if (aChildIsArray && bChildIsArray) {
165 var length_1 = aResultChild.length;
166 if (bResultChild.length !== length_1) {
167 return false;
168 }
169 for (var i = 0; i < length_1; ++i) {
170 if (!equalBySelectionSet(childSelectionSet, aResultChild[i], bResultChild[i], context)) {
171 return false;
172 }
173 }
174 return true;
175 }
176 return equalBySelectionSet(childSelectionSet, aResultChild, bResultChild, context);
177 }
178 else {
179 var fragment = utilities.getFragmentFromSelection(selection, context.fragmentMap);
180 if (fragment) {
181 if (selectionHasNonreactiveDirective(fragment))
182 return true;
183 return equalBySelectionSet(fragment.selectionSet,
184 aResult, bResult, context);
185 }
186 }
187 });
188}
189function selectionHasNonreactiveDirective(selection) {
190 return (!!selection.directives && selection.directives.some(directiveIsNonreactive));
191}
192function directiveIsNonreactive(dir) {
193 return dir.name.value === "nonreactive";
194}
195
196var assign = Object.assign, hasOwnProperty$1 = Object.hasOwnProperty;
197var ObservableQuery = (function (_super) {
198 tslib.__extends(ObservableQuery, _super);
199 function ObservableQuery(_a) {
200 var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;
201 var _this = _super.call(this, function (observer) {
202 try {
203 var subObserver = observer._subscription._observer;
204 if (subObserver && !subObserver.error) {
205 subObserver.error = defaultSubscriptionObserverErrorCallback;
206 }
207 }
208 catch (_a) { }
209 var first = !_this.observers.size;
210 _this.observers.add(observer);
211 var last = _this.last;
212 if (last && last.error) {
213 observer.error && observer.error(last.error);
214 }
215 else if (last && last.result) {
216 observer.next && observer.next(last.result);
217 }
218 if (first) {
219 _this.reobserve().catch(function () { });
220 }
221 return function () {
222 if (_this.observers.delete(observer) && !_this.observers.size) {
223 _this.tearDownQuery();
224 }
225 };
226 }) || this;
227 _this.observers = new Set();
228 _this.subscriptions = new Set();
229 _this.queryInfo = queryInfo;
230 _this.queryManager = queryManager;
231 _this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);
232 _this.isTornDown = false;
233 _this.subscribeToMore = _this.subscribeToMore.bind(_this);
234 var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? "cache-first" : _d;
235 var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e,
236 _f = options.initialFetchPolicy,
237 initialFetchPolicy = _f === void 0 ? fetchPolicy === "standby" ? defaultFetchPolicy : (fetchPolicy) : _f;
238 _this.options = tslib.__assign(tslib.__assign({}, options), {
239 initialFetchPolicy: initialFetchPolicy,
240 fetchPolicy: fetchPolicy });
241 _this.queryId = queryInfo.queryId || queryManager.generateQueryId();
242 var opDef = utilities.getOperationDefinition(_this.query);
243 _this.queryName = opDef && opDef.name && opDef.name.value;
244 return _this;
245 }
246 Object.defineProperty(ObservableQuery.prototype, "query", {
247 get: function () {
248 return this.lastQuery || this.options.query;
249 },
250 enumerable: false,
251 configurable: true
252 });
253 Object.defineProperty(ObservableQuery.prototype, "variables", {
254 get: function () {
255 return this.options.variables;
256 },
257 enumerable: false,
258 configurable: true
259 });
260 ObservableQuery.prototype.result = function () {
261 var _this = this;
262 return new Promise(function (resolve, reject) {
263 var observer = {
264 next: function (result) {
265 resolve(result);
266 _this.observers.delete(observer);
267 if (!_this.observers.size) {
268 _this.queryManager.removeQuery(_this.queryId);
269 }
270 setTimeout(function () {
271 subscription.unsubscribe();
272 }, 0);
273 },
274 error: reject,
275 };
276 var subscription = _this.subscribe(observer);
277 });
278 };
279 ObservableQuery.prototype.resetDiff = function () {
280 this.queryInfo.resetDiff();
281 };
282 ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {
283 if (saveAsLastResult === void 0) { saveAsLastResult = true; }
284 var lastResult = this.getLastResult(true);
285 var networkStatus = this.queryInfo.networkStatus ||
286 (lastResult && lastResult.networkStatus) ||
287 exports.NetworkStatus.ready;
288 var result = tslib.__assign(tslib.__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });
289 var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a;
290 if (
291 skipCacheDataFor(fetchPolicy) ||
292 this.queryManager.getDocumentInfo(this.query).hasForcedResolvers) ;
293 else if (this.waitForOwnResult) {
294 this.queryInfo["updateWatch"]();
295 }
296 else {
297 var diff = this.queryInfo.getDiff();
298 if (diff.complete || this.options.returnPartialData) {
299 result.data = diff.result;
300 }
301 if (equal.equal(result.data, {})) {
302 result.data = void 0;
303 }
304 if (diff.complete) {
305 delete result.partial;
306 if (diff.complete &&
307 result.networkStatus === exports.NetworkStatus.loading &&
308 (fetchPolicy === "cache-first" || fetchPolicy === "cache-only")) {
309 result.networkStatus = exports.NetworkStatus.ready;
310 result.loading = false;
311 }
312 }
313 else {
314 result.partial = true;
315 }
316 if (globalThis.__DEV__ !== false &&
317 !diff.complete &&
318 !this.options.partialRefetch &&
319 !result.loading &&
320 !result.data &&
321 !result.error) {
322 logMissingFieldErrors(diff.missing);
323 }
324 }
325 if (saveAsLastResult) {
326 this.updateLastResult(result);
327 }
328 return result;
329 };
330 ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {
331 if (!this.last) {
332 return true;
333 }
334 var resultIsDifferent = this.queryManager.getDocumentInfo(this.query).hasNonreactiveDirective ?
335 !equalByQuery(this.query, this.last.result, newResult, this.variables)
336 : !equal.equal(this.last.result, newResult);
337 return (resultIsDifferent || (variables && !equal.equal(this.last.variables, variables)));
338 };
339 ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {
340 var last = this.last;
341 if (last &&
342 last[key] &&
343 (!variablesMustMatch || equal.equal(last.variables, this.variables))) {
344 return last[key];
345 }
346 };
347 ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {
348 return this.getLast("result", variablesMustMatch);
349 };
350 ObservableQuery.prototype.getLastError = function (variablesMustMatch) {
351 return this.getLast("error", variablesMustMatch);
352 };
353 ObservableQuery.prototype.resetLastResults = function () {
354 delete this.last;
355 this.isTornDown = false;
356 };
357 ObservableQuery.prototype.resetQueryStoreErrors = function () {
358 this.queryManager.resetErrors(this.queryId);
359 };
360 ObservableQuery.prototype.refetch = function (variables) {
361 var _a;
362 var reobserveOptions = {
363 pollInterval: 0,
364 };
365 var fetchPolicy = this.options.fetchPolicy;
366 if (fetchPolicy === "cache-and-network") {
367 reobserveOptions.fetchPolicy = fetchPolicy;
368 }
369 else if (fetchPolicy === "no-cache") {
370 reobserveOptions.fetchPolicy = "no-cache";
371 }
372 else {
373 reobserveOptions.fetchPolicy = "network-only";
374 }
375 if (globalThis.__DEV__ !== false && variables && hasOwnProperty$1.call(variables, "variables")) {
376 var queryDef = utilities.getQueryDefinition(this.query);
377 var vars = queryDef.variableDefinitions;
378 if (!vars || !vars.some(function (v) { return v.variable.name.value === "variables"; })) {
379 globalThis.__DEV__ !== false && globals.invariant.warn(
380 20,
381 variables,
382 ((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || queryDef
383 );
384 }
385 }
386 if (variables && !equal.equal(this.options.variables, variables)) {
387 reobserveOptions.variables = this.options.variables = tslib.__assign(tslib.__assign({}, this.options.variables), variables);
388 }
389 this.queryInfo.resetLastWrite();
390 return this.reobserve(reobserveOptions, exports.NetworkStatus.refetch);
391 };
392 ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
393 var _this = this;
394 var combinedOptions = tslib.__assign(tslib.__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : (tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, this.options), { query: this.options.query }), fetchMoreOptions), { variables: tslib.__assign(tslib.__assign({}, this.options.variables), fetchMoreOptions.variables) })))), {
395 fetchPolicy: "no-cache" });
396 combinedOptions.query = this.transformDocument(combinedOptions.query);
397 var qid = this.queryManager.generateQueryId();
398 this.lastQuery =
399 fetchMoreOptions.query ?
400 this.transformDocument(this.options.query)
401 : combinedOptions.query;
402 var queryInfo = this.queryInfo;
403 var originalNetworkStatus = queryInfo.networkStatus;
404 queryInfo.networkStatus = exports.NetworkStatus.fetchMore;
405 if (combinedOptions.notifyOnNetworkStatusChange) {
406 this.observe();
407 }
408 var updatedQuerySet = new Set();
409 var updateQuery = fetchMoreOptions === null || fetchMoreOptions === void 0 ? void 0 : fetchMoreOptions.updateQuery;
410 var isCached = this.options.fetchPolicy !== "no-cache";
411 if (!isCached) {
412 globals.invariant(updateQuery, 21);
413 }
414 return this.queryManager
415 .fetchQuery(qid, combinedOptions, exports.NetworkStatus.fetchMore)
416 .then(function (fetchMoreResult) {
417 _this.queryManager.removeQuery(qid);
418 if (queryInfo.networkStatus === exports.NetworkStatus.fetchMore) {
419 queryInfo.networkStatus = originalNetworkStatus;
420 }
421 if (isCached) {
422 _this.queryManager.cache.batch({
423 update: function (cache) {
424 var updateQuery = fetchMoreOptions.updateQuery;
425 if (updateQuery) {
426 cache.updateQuery({
427 query: _this.query,
428 variables: _this.variables,
429 returnPartialData: true,
430 optimistic: false,
431 }, function (previous) {
432 return updateQuery(previous, {
433 fetchMoreResult: fetchMoreResult.data,
434 variables: combinedOptions.variables,
435 });
436 });
437 }
438 else {
439 cache.writeQuery({
440 query: combinedOptions.query,
441 variables: combinedOptions.variables,
442 data: fetchMoreResult.data,
443 });
444 }
445 },
446 onWatchUpdated: function (watch) {
447 updatedQuerySet.add(watch.query);
448 },
449 });
450 }
451 else {
452 var lastResult = _this.getLast("result");
453 var data = updateQuery(lastResult.data, {
454 fetchMoreResult: fetchMoreResult.data,
455 variables: combinedOptions.variables,
456 });
457 _this.reportResult(tslib.__assign(tslib.__assign({}, lastResult), { data: data }), _this.variables);
458 }
459 return fetchMoreResult;
460 })
461 .finally(function () {
462 if (isCached && !updatedQuerySet.has(_this.query)) {
463 reobserveCacheFirst(_this);
464 }
465 });
466 };
467 ObservableQuery.prototype.subscribeToMore = function (options) {
468 var _this = this;
469 var subscription = this.queryManager
470 .startGraphQLSubscription({
471 query: options.document,
472 variables: options.variables,
473 context: options.context,
474 })
475 .subscribe({
476 next: function (subscriptionData) {
477 var updateQuery = options.updateQuery;
478 if (updateQuery) {
479 _this.updateQuery(function (previous, _a) {
480 var variables = _a.variables;
481 return updateQuery(previous, {
482 subscriptionData: subscriptionData,
483 variables: variables,
484 });
485 });
486 }
487 },
488 error: function (err) {
489 if (options.onError) {
490 options.onError(err);
491 return;
492 }
493 globalThis.__DEV__ !== false && globals.invariant.error(22, err);
494 },
495 });
496 this.subscriptions.add(subscription);
497 return function () {
498 if (_this.subscriptions.delete(subscription)) {
499 subscription.unsubscribe();
500 }
501 };
502 };
503 ObservableQuery.prototype.setOptions = function (newOptions) {
504 return this.reobserve(newOptions);
505 };
506 ObservableQuery.prototype.silentSetOptions = function (newOptions) {
507 var mergedOptions = utilities.compact(this.options, newOptions || {});
508 assign(this.options, mergedOptions);
509 };
510 ObservableQuery.prototype.setVariables = function (variables) {
511 if (equal.equal(this.variables, variables)) {
512 return this.observers.size ? this.result() : Promise.resolve();
513 }
514 this.options.variables = variables;
515 if (!this.observers.size) {
516 return Promise.resolve();
517 }
518 return this.reobserve({
519 fetchPolicy: this.options.initialFetchPolicy,
520 variables: variables,
521 }, exports.NetworkStatus.setVariables);
522 };
523 ObservableQuery.prototype.updateQuery = function (mapFn) {
524 var queryManager = this.queryManager;
525 var result = queryManager.cache.diff({
526 query: this.options.query,
527 variables: this.variables,
528 returnPartialData: true,
529 optimistic: false,
530 }).result;
531 var newResult = mapFn(result, {
532 variables: this.variables,
533 });
534 if (newResult) {
535 queryManager.cache.writeQuery({
536 query: this.options.query,
537 data: newResult,
538 variables: this.variables,
539 });
540 queryManager.broadcastQueries();
541 }
542 };
543 ObservableQuery.prototype.startPolling = function (pollInterval) {
544 this.options.pollInterval = pollInterval;
545 this.updatePolling();
546 };
547 ObservableQuery.prototype.stopPolling = function () {
548 this.options.pollInterval = 0;
549 this.updatePolling();
550 };
551 ObservableQuery.prototype.applyNextFetchPolicy = function (reason,
552 options) {
553 if (options.nextFetchPolicy) {
554 var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;
555 if (fetchPolicy === "standby") ;
556 else if (typeof options.nextFetchPolicy === "function") {
557 options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {
558 reason: reason,
559 options: options,
560 observable: this,
561 initialFetchPolicy: initialFetchPolicy,
562 });
563 }
564 else if (reason === "variables-changed") {
565 options.fetchPolicy = initialFetchPolicy;
566 }
567 else {
568 options.fetchPolicy = options.nextFetchPolicy;
569 }
570 }
571 return options.fetchPolicy;
572 };
573 ObservableQuery.prototype.fetch = function (options, newNetworkStatus, query) {
574 this.queryManager.setObservableQuery(this);
575 return this.queryManager["fetchConcastWithInfo"](this.queryId, options, newNetworkStatus, query);
576 };
577 ObservableQuery.prototype.updatePolling = function () {
578 var _this = this;
579 if (this.queryManager.ssrMode) {
580 return;
581 }
582 var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;
583 if (!pollInterval || !this.hasObservers()) {
584 if (pollingInfo) {
585 clearTimeout(pollingInfo.timeout);
586 delete this.pollingInfo;
587 }
588 return;
589 }
590 if (pollingInfo && pollingInfo.interval === pollInterval) {
591 return;
592 }
593 globals.invariant(pollInterval, 23);
594 var info = pollingInfo || (this.pollingInfo = {});
595 info.interval = pollInterval;
596 var maybeFetch = function () {
597 var _a, _b;
598 if (_this.pollingInfo) {
599 if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus) &&
600 !((_b = (_a = _this.options).skipPollAttempt) === null || _b === void 0 ? void 0 : _b.call(_a))) {
601 _this.reobserve({
602 fetchPolicy: _this.options.initialFetchPolicy === "no-cache" ?
603 "no-cache"
604 : "network-only",
605 }, exports.NetworkStatus.poll).then(poll, poll);
606 }
607 else {
608 poll();
609 }
610 }
611 };
612 var poll = function () {
613 var info = _this.pollingInfo;
614 if (info) {
615 clearTimeout(info.timeout);
616 info.timeout = setTimeout(maybeFetch, info.interval);
617 }
618 };
619 poll();
620 };
621 ObservableQuery.prototype.updateLastResult = function (newResult, variables) {
622 if (variables === void 0) { variables = this.variables; }
623 var error = this.getLastError();
624 if (error && this.last && !equal.equal(variables, this.last.variables)) {
625 error = void 0;
626 }
627 return (this.last = tslib.__assign({ result: this.queryManager.assumeImmutableResults ?
628 newResult
629 : utilities.cloneDeep(newResult), variables: variables }, (error ? { error: error } : null)));
630 };
631 ObservableQuery.prototype.reobserveAsConcast = function (newOptions, newNetworkStatus) {
632 var _this = this;
633 this.isTornDown = false;
634 var useDisposableConcast =
635 newNetworkStatus === exports.NetworkStatus.refetch ||
636 newNetworkStatus === exports.NetworkStatus.fetchMore ||
637 newNetworkStatus === exports.NetworkStatus.poll;
638 var oldVariables = this.options.variables;
639 var oldFetchPolicy = this.options.fetchPolicy;
640 var mergedOptions = utilities.compact(this.options, newOptions || {});
641 var options = useDisposableConcast ?
642 mergedOptions
643 : assign(this.options, mergedOptions);
644 var query = this.transformDocument(options.query);
645 this.lastQuery = query;
646 if (!useDisposableConcast) {
647 this.updatePolling();
648 if (newOptions &&
649 newOptions.variables &&
650 !equal.equal(newOptions.variables, oldVariables) &&
651 options.fetchPolicy !== "standby" &&
652 (options.fetchPolicy === oldFetchPolicy ||
653 typeof options.nextFetchPolicy === "function")) {
654 this.applyNextFetchPolicy("variables-changed", options);
655 if (newNetworkStatus === void 0) {
656 newNetworkStatus = exports.NetworkStatus.setVariables;
657 }
658 }
659 }
660 this.waitForOwnResult && (this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy));
661 var finishWaitingForOwnResult = function () {
662 if (_this.concast === concast) {
663 _this.waitForOwnResult = false;
664 }
665 };
666 var variables = options.variables && tslib.__assign({}, options.variables);
667 var _a = this.fetch(options, newNetworkStatus, query), concast = _a.concast, fromLink = _a.fromLink;
668 var observer = {
669 next: function (result) {
670 if (equal.equal(_this.variables, variables)) {
671 finishWaitingForOwnResult();
672 _this.reportResult(result, variables);
673 }
674 },
675 error: function (error) {
676 if (equal.equal(_this.variables, variables)) {
677 if (!errors.isApolloError(error)) {
678 error = new errors.ApolloError({ networkError: error });
679 }
680 finishWaitingForOwnResult();
681 _this.reportError(error, variables);
682 }
683 },
684 };
685 if (!useDisposableConcast && (fromLink || !this.concast)) {
686 if (this.concast && this.observer) {
687 this.concast.removeObserver(this.observer);
688 }
689 this.concast = concast;
690 this.observer = observer;
691 }
692 concast.addObserver(observer);
693 return concast;
694 };
695 ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {
696 return this.reobserveAsConcast(newOptions, newNetworkStatus)
697 .promise;
698 };
699 ObservableQuery.prototype.resubscribeAfterError = function () {
700 var args = [];
701 for (var _i = 0; _i < arguments.length; _i++) {
702 args[_i] = arguments[_i];
703 }
704 var last = this.last;
705 this.resetLastResults();
706 var subscription = this.subscribe.apply(this, args);
707 this.last = last;
708 return subscription;
709 };
710 ObservableQuery.prototype.observe = function () {
711 this.reportResult(
712 this.getCurrentResult(false), this.variables);
713 };
714 ObservableQuery.prototype.reportResult = function (result, variables) {
715 var lastError = this.getLastError();
716 var isDifferent = this.isDifferentFromLastResult(result, variables);
717 if (lastError || !result.partial || this.options.returnPartialData) {
718 this.updateLastResult(result, variables);
719 }
720 if (lastError || isDifferent) {
721 utilities.iterateObserversSafely(this.observers, "next", result);
722 }
723 };
724 ObservableQuery.prototype.reportError = function (error, variables) {
725 var errorResult = tslib.__assign(tslib.__assign({}, this.getLastResult()), { error: error, errors: error.graphQLErrors, networkStatus: exports.NetworkStatus.error, loading: false });
726 this.updateLastResult(errorResult, variables);
727 utilities.iterateObserversSafely(this.observers, "error", (this.last.error = error));
728 };
729 ObservableQuery.prototype.hasObservers = function () {
730 return this.observers.size > 0;
731 };
732 ObservableQuery.prototype.tearDownQuery = function () {
733 if (this.isTornDown)
734 return;
735 if (this.concast && this.observer) {
736 this.concast.removeObserver(this.observer);
737 delete this.concast;
738 delete this.observer;
739 }
740 this.stopPolling();
741 this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
742 this.subscriptions.clear();
743 this.queryManager.stopQuery(this.queryId);
744 this.observers.clear();
745 this.isTornDown = true;
746 };
747 ObservableQuery.prototype.transformDocument = function (document) {
748 return this.queryManager.transform(document);
749 };
750 return ObservableQuery;
751}(utilities.Observable));
752utilities.fixObservableSubclass(ObservableQuery);
753function reobserveCacheFirst(obsQuery) {
754 var _a = obsQuery.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;
755 if (fetchPolicy === "cache-and-network" || fetchPolicy === "network-only") {
756 return obsQuery.reobserve({
757 fetchPolicy: "cache-first",
758 nextFetchPolicy: function (currentFetchPolicy, context) {
759 this.nextFetchPolicy = nextFetchPolicy;
760 if (typeof this.nextFetchPolicy === "function") {
761 return this.nextFetchPolicy(currentFetchPolicy, context);
762 }
763 return fetchPolicy;
764 },
765 });
766 }
767 return obsQuery.reobserve();
768}
769function defaultSubscriptionObserverErrorCallback(error) {
770 globalThis.__DEV__ !== false && globals.invariant.error(24, error.message, error.stack);
771}
772function logMissingFieldErrors(missing) {
773 if (globalThis.__DEV__ !== false && missing) {
774 globalThis.__DEV__ !== false && globals.invariant.debug(25, missing);
775 }
776}
777function skipCacheDataFor(fetchPolicy ) {
778 return (fetchPolicy === "network-only" ||
779 fetchPolicy === "no-cache" ||
780 fetchPolicy === "standby");
781}
782
783var destructiveMethodCounts = new (utilities.canUseWeakMap ? WeakMap : Map)();
784function wrapDestructiveCacheMethod(cache, methodName) {
785 var original = cache[methodName];
786 if (typeof original === "function") {
787 cache[methodName] = function () {
788 destructiveMethodCounts.set(cache,
789 (destructiveMethodCounts.get(cache) + 1) % 1e15);
790 return original.apply(this, arguments);
791 };
792 }
793}
794function cancelNotifyTimeout(info) {
795 if (info["notifyTimeout"]) {
796 clearTimeout(info["notifyTimeout"]);
797 info["notifyTimeout"] = void 0;
798 }
799}
800var QueryInfo = (function () {
801 function QueryInfo(queryManager, queryId) {
802 if (queryId === void 0) { queryId = queryManager.generateQueryId(); }
803 this.queryId = queryId;
804 this.listeners = new Set();
805 this.document = null;
806 this.lastRequestId = 1;
807 this.stopped = false;
808 this.dirty = false;
809 this.observableQuery = null;
810 var cache = (this.cache = queryManager.cache);
811 if (!destructiveMethodCounts.has(cache)) {
812 destructiveMethodCounts.set(cache, 0);
813 wrapDestructiveCacheMethod(cache, "evict");
814 wrapDestructiveCacheMethod(cache, "modify");
815 wrapDestructiveCacheMethod(cache, "reset");
816 }
817 }
818 QueryInfo.prototype.init = function (query) {
819 var networkStatus = query.networkStatus || exports.NetworkStatus.loading;
820 if (this.variables &&
821 this.networkStatus !== exports.NetworkStatus.loading &&
822 !equal.equal(this.variables, query.variables)) {
823 networkStatus = exports.NetworkStatus.setVariables;
824 }
825 if (!equal.equal(query.variables, this.variables)) {
826 this.lastDiff = void 0;
827 }
828 Object.assign(this, {
829 document: query.document,
830 variables: query.variables,
831 networkError: null,
832 graphQLErrors: this.graphQLErrors || [],
833 networkStatus: networkStatus,
834 });
835 if (query.observableQuery) {
836 this.setObservableQuery(query.observableQuery);
837 }
838 if (query.lastRequestId) {
839 this.lastRequestId = query.lastRequestId;
840 }
841 return this;
842 };
843 QueryInfo.prototype.reset = function () {
844 cancelNotifyTimeout(this);
845 this.dirty = false;
846 };
847 QueryInfo.prototype.resetDiff = function () {
848 this.lastDiff = void 0;
849 };
850 QueryInfo.prototype.getDiff = function () {
851 var options = this.getDiffOptions();
852 if (this.lastDiff && equal.equal(options, this.lastDiff.options)) {
853 return this.lastDiff.diff;
854 }
855 this.updateWatch(this.variables);
856 var oq = this.observableQuery;
857 if (oq && oq.options.fetchPolicy === "no-cache") {
858 return { complete: false };
859 }
860 var diff = this.cache.diff(options);
861 this.updateLastDiff(diff, options);
862 return diff;
863 };
864 QueryInfo.prototype.updateLastDiff = function (diff, options) {
865 this.lastDiff =
866 diff ?
867 {
868 diff: diff,
869 options: options || this.getDiffOptions(),
870 }
871 : void 0;
872 };
873 QueryInfo.prototype.getDiffOptions = function (variables) {
874 var _a;
875 if (variables === void 0) { variables = this.variables; }
876 return {
877 query: this.document,
878 variables: variables,
879 returnPartialData: true,
880 optimistic: true,
881 canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,
882 };
883 };
884 QueryInfo.prototype.setDiff = function (diff) {
885 var _this = this;
886 var _a;
887 var oldDiff = this.lastDiff && this.lastDiff.diff;
888 if (diff && !diff.complete && ((_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.getLastError())) {
889 return;
890 }
891 this.updateLastDiff(diff);
892 if (!this.dirty && !equal.equal(oldDiff && oldDiff.result, diff && diff.result)) {
893 this.dirty = true;
894 if (!this.notifyTimeout) {
895 this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);
896 }
897 }
898 };
899 QueryInfo.prototype.setObservableQuery = function (oq) {
900 var _this = this;
901 if (oq === this.observableQuery)
902 return;
903 if (this.oqListener) {
904 this.listeners.delete(this.oqListener);
905 }
906 this.observableQuery = oq;
907 if (oq) {
908 oq["queryInfo"] = this;
909 this.listeners.add((this.oqListener = function () {
910 var diff = _this.getDiff();
911 if (diff.fromOptimisticTransaction) {
912 oq["observe"]();
913 }
914 else {
915 reobserveCacheFirst(oq);
916 }
917 }));
918 }
919 else {
920 delete this.oqListener;
921 }
922 };
923 QueryInfo.prototype.notify = function () {
924 var _this = this;
925 cancelNotifyTimeout(this);
926 if (this.shouldNotify()) {
927 this.listeners.forEach(function (listener) { return listener(_this); });
928 }
929 this.dirty = false;
930 };
931 QueryInfo.prototype.shouldNotify = function () {
932 if (!this.dirty || !this.listeners.size) {
933 return false;
934 }
935 if (isNetworkRequestInFlight(this.networkStatus) && this.observableQuery) {
936 var fetchPolicy = this.observableQuery.options.fetchPolicy;
937 if (fetchPolicy !== "cache-only" && fetchPolicy !== "cache-and-network") {
938 return false;
939 }
940 }
941 return true;
942 };
943 QueryInfo.prototype.stop = function () {
944 if (!this.stopped) {
945 this.stopped = true;
946 this.reset();
947 this.cancel();
948 this.cancel = QueryInfo.prototype.cancel;
949 var oq = this.observableQuery;
950 if (oq)
951 oq.stopPolling();
952 }
953 };
954 QueryInfo.prototype.cancel = function () { };
955 QueryInfo.prototype.updateWatch = function (variables) {
956 var _this = this;
957 if (variables === void 0) { variables = this.variables; }
958 var oq = this.observableQuery;
959 if (oq && oq.options.fetchPolicy === "no-cache") {
960 return;
961 }
962 var watchOptions = tslib.__assign(tslib.__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });
963 if (!this.lastWatch || !equal.equal(watchOptions, this.lastWatch)) {
964 this.cancel();
965 this.cancel = this.cache.watch((this.lastWatch = watchOptions));
966 }
967 };
968 QueryInfo.prototype.resetLastWrite = function () {
969 this.lastWrite = void 0;
970 };
971 QueryInfo.prototype.shouldWrite = function (result, variables) {
972 var lastWrite = this.lastWrite;
973 return !(lastWrite &&
974 lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
975 equal.equal(variables, lastWrite.variables) &&
976 equal.equal(result.data, lastWrite.result.data));
977 };
978 QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {
979 var _this = this;
980 var merger = new utilities.DeepMerger();
981 var graphQLErrors = utilities.isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];
982 this.reset();
983 if ("incremental" in result && utilities.isNonEmptyArray(result.incremental)) {
984 var mergedData = utilities.mergeIncrementalData(this.getDiff().result, result);
985 result.data = mergedData;
986 }
987 else if ("hasNext" in result && result.hasNext) {
988 var diff = this.getDiff();
989 result.data = merger.merge(diff.result, result.data);
990 }
991 this.graphQLErrors = graphQLErrors;
992 if (options.fetchPolicy === "no-cache") {
993 this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));
994 }
995 else if (cacheWriteBehavior !== 0 ) {
996 if (shouldWriteResult(result, options.errorPolicy)) {
997 this.cache.performTransaction(function (cache) {
998 if (_this.shouldWrite(result, options.variables)) {
999 cache.writeQuery({
1000 query: document,
1001 data: result.data,
1002 variables: options.variables,
1003 overwrite: cacheWriteBehavior === 1 ,
1004 });
1005 _this.lastWrite = {
1006 result: result,
1007 variables: options.variables,
1008 dmCount: destructiveMethodCounts.get(_this.cache),
1009 };
1010 }
1011 else {
1012 if (_this.lastDiff && _this.lastDiff.diff.complete) {
1013 result.data = _this.lastDiff.diff.result;
1014 return;
1015 }
1016 }
1017 var diffOptions = _this.getDiffOptions(options.variables);
1018 var diff = cache.diff(diffOptions);
1019 if (!_this.stopped && equal.equal(_this.variables, options.variables)) {
1020 _this.updateWatch(options.variables);
1021 }
1022 _this.updateLastDiff(diff, diffOptions);
1023 if (diff.complete) {
1024 result.data = diff.result;
1025 }
1026 });
1027 }
1028 else {
1029 this.lastWrite = void 0;
1030 }
1031 }
1032 };
1033 QueryInfo.prototype.markReady = function () {
1034 this.networkError = null;
1035 return (this.networkStatus = exports.NetworkStatus.ready);
1036 };
1037 QueryInfo.prototype.markError = function (error) {
1038 this.networkStatus = exports.NetworkStatus.error;
1039 this.lastWrite = void 0;
1040 this.reset();
1041 if (error.graphQLErrors) {
1042 this.graphQLErrors = error.graphQLErrors;
1043 }
1044 if (error.networkError) {
1045 this.networkError = error.networkError;
1046 }
1047 return error;
1048 };
1049 return QueryInfo;
1050}());
1051function shouldWriteResult(result, errorPolicy) {
1052 if (errorPolicy === void 0) { errorPolicy = "none"; }
1053 var ignoreErrors = errorPolicy === "ignore" || errorPolicy === "all";
1054 var writeWithErrors = !utilities.graphQLResultHasError(result);
1055 if (!writeWithErrors && ignoreErrors && result.data) {
1056 writeWithErrors = true;
1057 }
1058 return writeWithErrors;
1059}
1060
1061var hasOwnProperty = Object.prototype.hasOwnProperty;
1062var IGNORE = Object.create(null);
1063var QueryManager = (function () {
1064 function QueryManager(options) {
1065 var _this = this;
1066 this.clientAwareness = {};
1067 this.queries = new Map();
1068 this.fetchCancelFns = new Map();
1069 this.transformCache = new utilities.AutoCleanedWeakCache(utilities.cacheSizes["queryManager.getDocumentInfo"] ||
1070 2000 );
1071 this.queryIdCounter = 1;
1072 this.requestIdCounter = 1;
1073 this.mutationIdCounter = 1;
1074 this.inFlightLinkObservables = new trie.Trie(false);
1075 var defaultDocumentTransform = new utilities.DocumentTransform(function (document) { return _this.cache.transformDocument(document); },
1076 { cache: false });
1077 this.cache = options.cache;
1078 this.link = options.link;
1079 this.defaultOptions = options.defaultOptions;
1080 this.queryDeduplication = options.queryDeduplication;
1081 this.clientAwareness = options.clientAwareness;
1082 this.localState = options.localState;
1083 this.ssrMode = options.ssrMode;
1084 this.assumeImmutableResults = options.assumeImmutableResults;
1085 var documentTransform = options.documentTransform;
1086 this.documentTransform =
1087 documentTransform ?
1088 defaultDocumentTransform
1089 .concat(documentTransform)
1090 .concat(defaultDocumentTransform)
1091 : defaultDocumentTransform;
1092 this.defaultContext = options.defaultContext || Object.create(null);
1093 if ((this.onBroadcast = options.onBroadcast)) {
1094 this.mutationStore = Object.create(null);
1095 }
1096 }
1097 QueryManager.prototype.stop = function () {
1098 var _this = this;
1099 this.queries.forEach(function (_info, queryId) {
1100 _this.stopQueryNoBroadcast(queryId);
1101 });
1102 this.cancelPendingFetches(globals.newInvariantError(26));
1103 };
1104 QueryManager.prototype.cancelPendingFetches = function (error) {
1105 this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
1106 this.fetchCancelFns.clear();
1107 };
1108 QueryManager.prototype.mutate = function (_a) {
1109 return tslib.__awaiter(this, arguments, void 0, function (_b) {
1110 var mutationId, hasClientExports, mutationStoreValue, isOptimistic, self;
1111 var _c, _d;
1112 var mutation = _b.mutation, variables = _b.variables, optimisticResponse = _b.optimisticResponse, updateQueries = _b.updateQueries, _e = _b.refetchQueries, refetchQueries = _e === void 0 ? [] : _e, _f = _b.awaitRefetchQueries, awaitRefetchQueries = _f === void 0 ? false : _f, updateWithProxyFn = _b.update, onQueryUpdated = _b.onQueryUpdated, _g = _b.fetchPolicy, fetchPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.fetchPolicy) || "network-only" : _g, _h = _b.errorPolicy, errorPolicy = _h === void 0 ? ((_d = this.defaultOptions.mutate) === null || _d === void 0 ? void 0 : _d.errorPolicy) || "none" : _h, keepRootFields = _b.keepRootFields, context = _b.context;
1113 return tslib.__generator(this, function (_j) {
1114 switch (_j.label) {
1115 case 0:
1116 globals.invariant(mutation, 27);
1117 globals.invariant(fetchPolicy === "network-only" || fetchPolicy === "no-cache", 28);
1118 mutationId = this.generateMutationId();
1119 mutation = this.cache.transformForLink(this.transform(mutation));
1120 hasClientExports = this.getDocumentInfo(mutation).hasClientExports;
1121 variables = this.getVariables(mutation, variables);
1122 if (!hasClientExports) return [3 , 2];
1123 return [4 , this.localState.addExportedVariables(mutation, variables, context)];
1124 case 1:
1125 variables = (_j.sent());
1126 _j.label = 2;
1127 case 2:
1128 mutationStoreValue = this.mutationStore &&
1129 (this.mutationStore[mutationId] = {
1130 mutation: mutation,
1131 variables: variables,
1132 loading: true,
1133 error: null,
1134 });
1135 isOptimistic = optimisticResponse &&
1136 this.markMutationOptimistic(optimisticResponse, {
1137 mutationId: mutationId,
1138 document: mutation,
1139 variables: variables,
1140 fetchPolicy: fetchPolicy,
1141 errorPolicy: errorPolicy,
1142 context: context,
1143 updateQueries: updateQueries,
1144 update: updateWithProxyFn,
1145 keepRootFields: keepRootFields,
1146 });
1147 this.broadcastQueries();
1148 self = this;
1149 return [2 , new Promise(function (resolve, reject) {
1150 return utilities.asyncMap(self.getObservableFromLink(mutation, tslib.__assign(tslib.__assign({}, context), { optimisticResponse: isOptimistic ? optimisticResponse : void 0 }), variables, {}, false), function (result) {
1151 if (utilities.graphQLResultHasError(result) && errorPolicy === "none") {
1152 throw new errors.ApolloError({
1153 graphQLErrors: utilities.getGraphQLErrorsFromResult(result),
1154 });
1155 }
1156 if (mutationStoreValue) {
1157 mutationStoreValue.loading = false;
1158 mutationStoreValue.error = null;
1159 }
1160 var storeResult = tslib.__assign({}, result);
1161 if (typeof refetchQueries === "function") {
1162 refetchQueries = refetchQueries(storeResult);
1163 }
1164 if (errorPolicy === "ignore" && utilities.graphQLResultHasError(storeResult)) {
1165 delete storeResult.errors;
1166 }
1167 return self.markMutationResult({
1168 mutationId: mutationId,
1169 result: storeResult,
1170 document: mutation,
1171 variables: variables,
1172 fetchPolicy: fetchPolicy,
1173 errorPolicy: errorPolicy,
1174 context: context,
1175 update: updateWithProxyFn,
1176 updateQueries: updateQueries,
1177 awaitRefetchQueries: awaitRefetchQueries,
1178 refetchQueries: refetchQueries,
1179 removeOptimistic: isOptimistic ? mutationId : void 0,
1180 onQueryUpdated: onQueryUpdated,
1181 keepRootFields: keepRootFields,
1182 });
1183 }).subscribe({
1184 next: function (storeResult) {
1185 self.broadcastQueries();
1186 if (!("hasNext" in storeResult) || storeResult.hasNext === false) {
1187 resolve(storeResult);
1188 }
1189 },
1190 error: function (err) {
1191 if (mutationStoreValue) {
1192 mutationStoreValue.loading = false;
1193 mutationStoreValue.error = err;
1194 }
1195 if (isOptimistic) {
1196 self.cache.removeOptimistic(mutationId);
1197 }
1198 self.broadcastQueries();
1199 reject(err instanceof errors.ApolloError ? err : (new errors.ApolloError({
1200 networkError: err,
1201 })));
1202 },
1203 });
1204 })];
1205 }
1206 });
1207 });
1208 };
1209 QueryManager.prototype.markMutationResult = function (mutation, cache) {
1210 var _this = this;
1211 if (cache === void 0) { cache = this.cache; }
1212 var result = mutation.result;
1213 var cacheWrites = [];
1214 var skipCache = mutation.fetchPolicy === "no-cache";
1215 if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
1216 if (!utilities.isExecutionPatchIncrementalResult(result)) {
1217 cacheWrites.push({
1218 result: result.data,
1219 dataId: "ROOT_MUTATION",
1220 query: mutation.document,
1221 variables: mutation.variables,
1222 });
1223 }
1224 if (utilities.isExecutionPatchIncrementalResult(result) &&
1225 utilities.isNonEmptyArray(result.incremental)) {
1226 var diff = cache.diff({
1227 id: "ROOT_MUTATION",
1228 query: this.getDocumentInfo(mutation.document).asQuery,
1229 variables: mutation.variables,
1230 optimistic: false,
1231 returnPartialData: true,
1232 });
1233 var mergedData = void 0;
1234 if (diff.result) {
1235 mergedData = mergeIncrementalData(diff.result, result);
1236 }
1237 if (typeof mergedData !== "undefined") {
1238 result.data = mergedData;
1239 cacheWrites.push({
1240 result: mergedData,
1241 dataId: "ROOT_MUTATION",
1242 query: mutation.document,
1243 variables: mutation.variables,
1244 });
1245 }
1246 }
1247 var updateQueries_1 = mutation.updateQueries;
1248 if (updateQueries_1) {
1249 this.queries.forEach(function (_a, queryId) {
1250 var observableQuery = _a.observableQuery;
1251 var queryName = observableQuery && observableQuery.queryName;
1252 if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {
1253 return;
1254 }
1255 var updater = updateQueries_1[queryName];
1256 var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;
1257 var _c = cache.diff({
1258 query: document,
1259 variables: variables,
1260 returnPartialData: true,
1261 optimistic: false,
1262 }), currentQueryResult = _c.result, complete = _c.complete;
1263 if (complete && currentQueryResult) {
1264 var nextQueryResult = updater(currentQueryResult, {
1265 mutationResult: result,
1266 queryName: (document && utilities.getOperationName(document)) || void 0,
1267 queryVariables: variables,
1268 });
1269 if (nextQueryResult) {
1270 cacheWrites.push({
1271 result: nextQueryResult,
1272 dataId: "ROOT_QUERY",
1273 query: document,
1274 variables: variables,
1275 });
1276 }
1277 }
1278 });
1279 }
1280 }
1281 if (cacheWrites.length > 0 ||
1282 (mutation.refetchQueries || "").length > 0 ||
1283 mutation.update ||
1284 mutation.onQueryUpdated ||
1285 mutation.removeOptimistic) {
1286 var results_1 = [];
1287 this.refetchQueries({
1288 updateCache: function (cache) {
1289 if (!skipCache) {
1290 cacheWrites.forEach(function (write) { return cache.write(write); });
1291 }
1292 var update = mutation.update;
1293 var isFinalResult = !utilities.isExecutionPatchResult(result) ||
1294 (utilities.isExecutionPatchIncrementalResult(result) && !result.hasNext);
1295 if (update) {
1296 if (!skipCache) {
1297 var diff = cache.diff({
1298 id: "ROOT_MUTATION",
1299 query: _this.getDocumentInfo(mutation.document).asQuery,
1300 variables: mutation.variables,
1301 optimistic: false,
1302 returnPartialData: true,
1303 });
1304 if (diff.complete) {
1305 result = tslib.__assign(tslib.__assign({}, result), { data: diff.result });
1306 if ("incremental" in result) {
1307 delete result.incremental;
1308 }
1309 if ("hasNext" in result) {
1310 delete result.hasNext;
1311 }
1312 }
1313 }
1314 if (isFinalResult) {
1315 update(cache, result, {
1316 context: mutation.context,
1317 variables: mutation.variables,
1318 });
1319 }
1320 }
1321 if (!skipCache && !mutation.keepRootFields && isFinalResult) {
1322 cache.modify({
1323 id: "ROOT_MUTATION",
1324 fields: function (value, _a) {
1325 var fieldName = _a.fieldName, DELETE = _a.DELETE;
1326 return fieldName === "__typename" ? value : DELETE;
1327 },
1328 });
1329 }
1330 },
1331 include: mutation.refetchQueries,
1332 optimistic: false,
1333 removeOptimistic: mutation.removeOptimistic,
1334 onQueryUpdated: mutation.onQueryUpdated || null,
1335 }).forEach(function (result) { return results_1.push(result); });
1336 if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
1337 return Promise.all(results_1).then(function () { return result; });
1338 }
1339 }
1340 return Promise.resolve(result);
1341 };
1342 QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {
1343 var _this = this;
1344 var data = typeof optimisticResponse === "function" ?
1345 optimisticResponse(mutation.variables, { IGNORE: IGNORE })
1346 : optimisticResponse;
1347 if (data === IGNORE) {
1348 return false;
1349 }
1350 this.cache.recordOptimisticTransaction(function (cache) {
1351 try {
1352 _this.markMutationResult(tslib.__assign(tslib.__assign({}, mutation), { result: { data: data } }), cache);
1353 }
1354 catch (error) {
1355 globalThis.__DEV__ !== false && globals.invariant.error(error);
1356 }
1357 }, mutation.mutationId);
1358 return true;
1359 };
1360 QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
1361 return this.fetchConcastWithInfo(queryId, options, networkStatus).concast
1362 .promise;
1363 };
1364 QueryManager.prototype.getQueryStore = function () {
1365 var store = Object.create(null);
1366 this.queries.forEach(function (info, queryId) {
1367 store[queryId] = {
1368 variables: info.variables,
1369 networkStatus: info.networkStatus,
1370 networkError: info.networkError,
1371 graphQLErrors: info.graphQLErrors,
1372 };
1373 });
1374 return store;
1375 };
1376 QueryManager.prototype.resetErrors = function (queryId) {
1377 var queryInfo = this.queries.get(queryId);
1378 if (queryInfo) {
1379 queryInfo.networkError = undefined;
1380 queryInfo.graphQLErrors = [];
1381 }
1382 };
1383 QueryManager.prototype.transform = function (document) {
1384 return this.documentTransform.transformDocument(document);
1385 };
1386 QueryManager.prototype.getDocumentInfo = function (document) {
1387 var transformCache = this.transformCache;
1388 if (!transformCache.has(document)) {
1389 var cacheEntry = {
1390 hasClientExports: utilities.hasClientExports(document),
1391 hasForcedResolvers: this.localState.shouldForceResolvers(document),
1392 hasNonreactiveDirective: utilities.hasDirectives(["nonreactive"], document),
1393 clientQuery: this.localState.clientQuery(document),
1394 serverQuery: utilities.removeDirectivesFromDocument([
1395 { name: "client", remove: true },
1396 { name: "connection" },
1397 { name: "nonreactive" },
1398 ], document),
1399 defaultVars: utilities.getDefaultValues(utilities.getOperationDefinition(document)),
1400 asQuery: tslib.__assign(tslib.__assign({}, document), { definitions: document.definitions.map(function (def) {
1401 if (def.kind === "OperationDefinition" &&
1402 def.operation !== "query") {
1403 return tslib.__assign(tslib.__assign({}, def), { operation: "query" });
1404 }
1405 return def;
1406 }) }),
1407 };
1408 transformCache.set(document, cacheEntry);
1409 }
1410 return transformCache.get(document);
1411 };
1412 QueryManager.prototype.getVariables = function (document, variables) {
1413 return tslib.__assign(tslib.__assign({}, this.getDocumentInfo(document).defaultVars), variables);
1414 };
1415 QueryManager.prototype.watchQuery = function (options) {
1416 var query = this.transform(options.query);
1417 options = tslib.__assign(tslib.__assign({}, options), { variables: this.getVariables(query, options.variables) });
1418 if (typeof options.notifyOnNetworkStatusChange === "undefined") {
1419 options.notifyOnNetworkStatusChange = false;
1420 }
1421 var queryInfo = new QueryInfo(this);
1422 var observable = new ObservableQuery({
1423 queryManager: this,
1424 queryInfo: queryInfo,
1425 options: options,
1426 });
1427 observable["lastQuery"] = query;
1428 this.queries.set(observable.queryId, queryInfo);
1429 queryInfo.init({
1430 document: query,
1431 observableQuery: observable,
1432 variables: observable.variables,
1433 });
1434 return observable;
1435 };
1436 QueryManager.prototype.query = function (options, queryId) {
1437 var _this = this;
1438 if (queryId === void 0) { queryId = this.generateQueryId(); }
1439 globals.invariant(options.query, 29);
1440 globals.invariant(options.query.kind === "Document", 30);
1441 globals.invariant(!options.returnPartialData, 31);
1442 globals.invariant(!options.pollInterval, 32);
1443 return this.fetchQuery(queryId, tslib.__assign(tslib.__assign({}, options), { query: this.transform(options.query) })).finally(function () { return _this.stopQuery(queryId); });
1444 };
1445 QueryManager.prototype.generateQueryId = function () {
1446 return String(this.queryIdCounter++);
1447 };
1448 QueryManager.prototype.generateRequestId = function () {
1449 return this.requestIdCounter++;
1450 };
1451 QueryManager.prototype.generateMutationId = function () {
1452 return String(this.mutationIdCounter++);
1453 };
1454 QueryManager.prototype.stopQueryInStore = function (queryId) {
1455 this.stopQueryInStoreNoBroadcast(queryId);
1456 this.broadcastQueries();
1457 };
1458 QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
1459 var queryInfo = this.queries.get(queryId);
1460 if (queryInfo)
1461 queryInfo.stop();
1462 };
1463 QueryManager.prototype.clearStore = function (options) {
1464 if (options === void 0) { options = {
1465 discardWatches: true,
1466 }; }
1467 this.cancelPendingFetches(globals.newInvariantError(33));
1468 this.queries.forEach(function (queryInfo) {
1469 if (queryInfo.observableQuery) {
1470 queryInfo.networkStatus = exports.NetworkStatus.loading;
1471 }
1472 else {
1473 queryInfo.stop();
1474 }
1475 });
1476 if (this.mutationStore) {
1477 this.mutationStore = Object.create(null);
1478 }
1479 return this.cache.reset(options);
1480 };
1481 QueryManager.prototype.getObservableQueries = function (include) {
1482 var _this = this;
1483 if (include === void 0) { include = "active"; }
1484 var queries = new Map();
1485 var queryNamesAndDocs = new Map();
1486 var legacyQueryOptions = new Set();
1487 if (Array.isArray(include)) {
1488 include.forEach(function (desc) {
1489 if (typeof desc === "string") {
1490 queryNamesAndDocs.set(desc, false);
1491 }
1492 else if (utilities.isDocumentNode(desc)) {
1493 queryNamesAndDocs.set(_this.transform(desc), false);
1494 }
1495 else if (utilities.isNonNullObject(desc) && desc.query) {
1496 legacyQueryOptions.add(desc);
1497 }
1498 });
1499 }
1500 this.queries.forEach(function (_a, queryId) {
1501 var oq = _a.observableQuery, document = _a.document;
1502 if (oq) {
1503 if (include === "all") {
1504 queries.set(queryId, oq);
1505 return;
1506 }
1507 var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;
1508 if (fetchPolicy === "standby" ||
1509 (include === "active" && !oq.hasObservers())) {
1510 return;
1511 }
1512 if (include === "active" ||
1513 (queryName && queryNamesAndDocs.has(queryName)) ||
1514 (document && queryNamesAndDocs.has(document))) {
1515 queries.set(queryId, oq);
1516 if (queryName)
1517 queryNamesAndDocs.set(queryName, true);
1518 if (document)
1519 queryNamesAndDocs.set(document, true);
1520 }
1521 }
1522 });
1523 if (legacyQueryOptions.size) {
1524 legacyQueryOptions.forEach(function (options) {
1525 var queryId = utilities.makeUniqueId("legacyOneTimeQuery");
1526 var queryInfo = _this.getQuery(queryId).init({
1527 document: options.query,
1528 variables: options.variables,
1529 });
1530 var oq = new ObservableQuery({
1531 queryManager: _this,
1532 queryInfo: queryInfo,
1533 options: tslib.__assign(tslib.__assign({}, options), { fetchPolicy: "network-only" }),
1534 });
1535 globals.invariant(oq.queryId === queryId);
1536 queryInfo.setObservableQuery(oq);
1537 queries.set(queryId, oq);
1538 });
1539 }
1540 if (globalThis.__DEV__ !== false && queryNamesAndDocs.size) {
1541 queryNamesAndDocs.forEach(function (included, nameOrDoc) {
1542 if (!included) {
1543 globalThis.__DEV__ !== false && globals.invariant.warn(typeof nameOrDoc === "string" ? 34 : 35, nameOrDoc);
1544 }
1545 });
1546 }
1547 return queries;
1548 };
1549 QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
1550 var _this = this;
1551 if (includeStandby === void 0) { includeStandby = false; }
1552 var observableQueryPromises = [];
1553 this.getObservableQueries(includeStandby ? "all" : "active").forEach(function (observableQuery, queryId) {
1554 var fetchPolicy = observableQuery.options.fetchPolicy;
1555 observableQuery.resetLastResults();
1556 if (includeStandby ||
1557 (fetchPolicy !== "standby" && fetchPolicy !== "cache-only")) {
1558 observableQueryPromises.push(observableQuery.refetch());
1559 }
1560 _this.getQuery(queryId).setDiff(null);
1561 });
1562 this.broadcastQueries();
1563 return Promise.all(observableQueryPromises);
1564 };
1565 QueryManager.prototype.setObservableQuery = function (observableQuery) {
1566 this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);
1567 };
1568 QueryManager.prototype.startGraphQLSubscription = function (_a) {
1569 var _this = this;
1570 var query = _a.query, fetchPolicy = _a.fetchPolicy, _b = _a.errorPolicy, errorPolicy = _b === void 0 ? "none" : _b, variables = _a.variables, _c = _a.context, context = _c === void 0 ? {} : _c, _d = _a.extensions, extensions = _d === void 0 ? {} : _d;
1571 query = this.transform(query);
1572 variables = this.getVariables(query, variables);
1573 var makeObservable = function (variables) {
1574 return _this.getObservableFromLink(query, context, variables, extensions).map(function (result) {
1575 if (fetchPolicy !== "no-cache") {
1576 if (shouldWriteResult(result, errorPolicy)) {
1577 _this.cache.write({
1578 query: query,
1579 result: result.data,
1580 dataId: "ROOT_SUBSCRIPTION",
1581 variables: variables,
1582 });
1583 }
1584 _this.broadcastQueries();
1585 }
1586 var hasErrors = utilities.graphQLResultHasError(result);
1587 var hasProtocolErrors = errors.graphQLResultHasProtocolErrors(result);
1588 if (hasErrors || hasProtocolErrors) {
1589 var errors$1 = {};
1590 if (hasErrors) {
1591 errors$1.graphQLErrors = result.errors;
1592 }
1593 if (hasProtocolErrors) {
1594 errors$1.protocolErrors = result.extensions[errors.PROTOCOL_ERRORS_SYMBOL];
1595 }
1596 if (errorPolicy === "none" || hasProtocolErrors) {
1597 throw new errors.ApolloError(errors$1);
1598 }
1599 }
1600 if (errorPolicy === "ignore") {
1601 delete result.errors;
1602 }
1603 return result;
1604 });
1605 };
1606 if (this.getDocumentInfo(query).hasClientExports) {
1607 var observablePromise_1 = this.localState
1608 .addExportedVariables(query, variables, context)
1609 .then(makeObservable);
1610 return new utilities.Observable(function (observer) {
1611 var sub = null;
1612 observablePromise_1.then(function (observable) { return (sub = observable.subscribe(observer)); }, observer.error);
1613 return function () { return sub && sub.unsubscribe(); };
1614 });
1615 }
1616 return makeObservable(variables);
1617 };
1618 QueryManager.prototype.stopQuery = function (queryId) {
1619 this.stopQueryNoBroadcast(queryId);
1620 this.broadcastQueries();
1621 };
1622 QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
1623 this.stopQueryInStoreNoBroadcast(queryId);
1624 this.removeQuery(queryId);
1625 };
1626 QueryManager.prototype.removeQuery = function (queryId) {
1627 this.fetchCancelFns.delete(queryId);
1628 if (this.queries.has(queryId)) {
1629 this.getQuery(queryId).stop();
1630 this.queries.delete(queryId);
1631 }
1632 };
1633 QueryManager.prototype.broadcastQueries = function () {
1634 if (this.onBroadcast)
1635 this.onBroadcast();
1636 this.queries.forEach(function (info) { return info.notify(); });
1637 };
1638 QueryManager.prototype.getLocalState = function () {
1639 return this.localState;
1640 };
1641 QueryManager.prototype.getObservableFromLink = function (query, context, variables, extensions,
1642 deduplication) {
1643 var _this = this;
1644 var _a;
1645 if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
1646 var observable;
1647 var _b = this.getDocumentInfo(query), serverQuery = _b.serverQuery, clientQuery = _b.clientQuery;
1648 if (serverQuery) {
1649 var _c = this, inFlightLinkObservables_1 = _c.inFlightLinkObservables, link = _c.link;
1650 var operation = {
1651 query: serverQuery,
1652 variables: variables,
1653 operationName: utilities.getOperationName(serverQuery) || void 0,
1654 context: this.prepareContext(tslib.__assign(tslib.__assign({}, context), { forceFetch: !deduplication })),
1655 extensions: extensions,
1656 };
1657 context = operation.context;
1658 if (deduplication) {
1659 var printedServerQuery_1 = utilities.print(serverQuery);
1660 var varJson_1 = cache.canonicalStringify(variables);
1661 var entry = inFlightLinkObservables_1.lookup(printedServerQuery_1, varJson_1);
1662 observable = entry.observable;
1663 if (!observable) {
1664 var concast = new utilities.Concast([
1665 core.execute(link, operation),
1666 ]);
1667 observable = entry.observable = concast;
1668 concast.beforeNext(function () {
1669 inFlightLinkObservables_1.remove(printedServerQuery_1, varJson_1);
1670 });
1671 }
1672 }
1673 else {
1674 observable = new utilities.Concast([
1675 core.execute(link, operation),
1676 ]);
1677 }
1678 }
1679 else {
1680 observable = new utilities.Concast([utilities.Observable.of({ data: {} })]);
1681 context = this.prepareContext(context);
1682 }
1683 if (clientQuery) {
1684 observable = utilities.asyncMap(observable, function (result) {
1685 return _this.localState.runResolvers({
1686 document: clientQuery,
1687 remoteResult: result,
1688 context: context,
1689 variables: variables,
1690 });
1691 });
1692 }
1693 return observable;
1694 };
1695 QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {
1696 var requestId = (queryInfo.lastRequestId = this.generateRequestId());
1697 var linkDocument = this.cache.transformForLink(options.query);
1698 return utilities.asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {
1699 var graphQLErrors = utilities.getGraphQLErrorsFromResult(result);
1700 var hasErrors = graphQLErrors.length > 0;
1701 var errorPolicy = options.errorPolicy;
1702 if (requestId >= queryInfo.lastRequestId) {
1703 if (hasErrors && errorPolicy === "none") {
1704 throw queryInfo.markError(new errors.ApolloError({
1705 graphQLErrors: graphQLErrors,
1706 }));
1707 }
1708 queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);
1709 queryInfo.markReady();
1710 }
1711 var aqr = {
1712 data: result.data,
1713 loading: false,
1714 networkStatus: exports.NetworkStatus.ready,
1715 };
1716 if (hasErrors && errorPolicy === "none") {
1717 aqr.data = void 0;
1718 }
1719 if (hasErrors && errorPolicy !== "ignore") {
1720 aqr.errors = graphQLErrors;
1721 aqr.networkStatus = exports.NetworkStatus.error;
1722 }
1723 return aqr;
1724 }, function (networkError) {
1725 var error = errors.isApolloError(networkError) ? networkError : (new errors.ApolloError({ networkError: networkError }));
1726 if (requestId >= queryInfo.lastRequestId) {
1727 queryInfo.markError(error);
1728 }
1729 throw error;
1730 });
1731 };
1732 QueryManager.prototype.fetchConcastWithInfo = function (queryId, options,
1733 networkStatus, query) {
1734 var _this = this;
1735 if (networkStatus === void 0) { networkStatus = exports.NetworkStatus.loading; }
1736 if (query === void 0) { query = options.query; }
1737 var variables = this.getVariables(query, options.variables);
1738 var queryInfo = this.getQuery(queryId);
1739 var defaults = this.defaultOptions.watchQuery;
1740 var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? (defaults && defaults.fetchPolicy) || "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? (defaults && defaults.errorPolicy) || "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
1741 var normalized = Object.assign({}, options, {
1742 query: query,
1743 variables: variables,
1744 fetchPolicy: fetchPolicy,
1745 errorPolicy: errorPolicy,
1746 returnPartialData: returnPartialData,
1747 notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
1748 context: context,
1749 });
1750 var fromVariables = function (variables) {
1751 normalized.variables = variables;
1752 var sourcesWithInfo = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
1753 if (
1754 normalized.fetchPolicy !== "standby" &&
1755 sourcesWithInfo.sources.length > 0 &&
1756 queryInfo.observableQuery) {
1757 queryInfo.observableQuery["applyNextFetchPolicy"]("after-fetch", options);
1758 }
1759 return sourcesWithInfo;
1760 };
1761 var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };
1762 this.fetchCancelFns.set(queryId, function (reason) {
1763 cleanupCancelFn();
1764 setTimeout(function () { return concast.cancel(reason); });
1765 });
1766 var concast, containsDataFromLink;
1767 if (this.getDocumentInfo(normalized.query).hasClientExports) {
1768 concast = new utilities.Concast(this.localState
1769 .addExportedVariables(normalized.query, normalized.variables, normalized.context)
1770 .then(fromVariables)
1771 .then(function (sourcesWithInfo) { return sourcesWithInfo.sources; }));
1772 containsDataFromLink = true;
1773 }
1774 else {
1775 var sourcesWithInfo = fromVariables(normalized.variables);
1776 containsDataFromLink = sourcesWithInfo.fromLink;
1777 concast = new utilities.Concast(sourcesWithInfo.sources);
1778 }
1779 concast.promise.then(cleanupCancelFn, cleanupCancelFn);
1780 return {
1781 concast: concast,
1782 fromLink: containsDataFromLink,
1783 };
1784 };
1785 QueryManager.prototype.refetchQueries = function (_a) {
1786 var _this = this;
1787 var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? utilities.makeUniqueId("refetchQueries") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;
1788 var includedQueriesById = new Map();
1789 if (include) {
1790 this.getObservableQueries(include).forEach(function (oq, queryId) {
1791 includedQueriesById.set(queryId, {
1792 oq: oq,
1793 lastDiff: _this.getQuery(queryId).getDiff(),
1794 });
1795 });
1796 }
1797 var results = new Map();
1798 if (updateCache) {
1799 this.cache.batch({
1800 update: updateCache,
1801 optimistic: (optimistic && removeOptimistic) || false,
1802 removeOptimistic: removeOptimistic,
1803 onWatchUpdated: function (watch, diff, lastDiff) {
1804 var oq = watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;
1805 if (oq) {
1806 if (onQueryUpdated) {
1807 includedQueriesById.delete(oq.queryId);
1808 var result = onQueryUpdated(oq, diff, lastDiff);
1809 if (result === true) {
1810 result = oq.refetch();
1811 }
1812 if (result !== false) {
1813 results.set(oq, result);
1814 }
1815 return result;
1816 }
1817 if (onQueryUpdated !== null) {
1818 includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });
1819 }
1820 }
1821 },
1822 });
1823 }
1824 if (includedQueriesById.size) {
1825 includedQueriesById.forEach(function (_a, queryId) {
1826 var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;
1827 var result;
1828 if (onQueryUpdated) {
1829 if (!diff) {
1830 var info = oq["queryInfo"];
1831 info.reset();
1832 diff = info.getDiff();
1833 }
1834 result = onQueryUpdated(oq, diff, lastDiff);
1835 }
1836 if (!onQueryUpdated || result === true) {
1837 result = oq.refetch();
1838 }
1839 if (result !== false) {
1840 results.set(oq, result);
1841 }
1842 if (queryId.indexOf("legacyOneTimeQuery") >= 0) {
1843 _this.stopQueryNoBroadcast(queryId);
1844 }
1845 });
1846 }
1847 if (removeOptimistic) {
1848 this.cache.removeOptimistic(removeOptimistic);
1849 }
1850 return results;
1851 };
1852 QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a,
1853 networkStatus) {
1854 var _this = this;
1855 var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;
1856 var oldNetworkStatus = queryInfo.networkStatus;
1857 queryInfo.init({
1858 document: query,
1859 variables: variables,
1860 networkStatus: networkStatus,
1861 });
1862 var readCache = function () { return queryInfo.getDiff(); };
1863 var resultsFromCache = function (diff, networkStatus) {
1864 if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || exports.NetworkStatus.loading; }
1865 var data = diff.result;
1866 if (globalThis.__DEV__ !== false && !returnPartialData && !equal.equal(data, {})) {
1867 logMissingFieldErrors(diff.missing);
1868 }
1869 var fromData = function (data) {
1870 return utilities.Observable.of(tslib.__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true })));
1871 };
1872 if (data && _this.getDocumentInfo(query).hasForcedResolvers) {
1873 return _this.localState
1874 .runResolvers({
1875 document: query,
1876 remoteResult: { data: data },
1877 context: context,
1878 variables: variables,
1879 onlyRunForcedResolvers: true,
1880 })
1881 .then(function (resolved) { return fromData(resolved.data || void 0); });
1882 }
1883 if (errorPolicy === "none" &&
1884 networkStatus === exports.NetworkStatus.refetch &&
1885 Array.isArray(diff.missing)) {
1886 return fromData(void 0);
1887 }
1888 return fromData(data);
1889 };
1890 var cacheWriteBehavior = fetchPolicy === "no-cache" ? 0
1891 : (networkStatus === exports.NetworkStatus.refetch &&
1892 refetchWritePolicy !== "merge") ?
1893 1
1894 : 2 ;
1895 var resultsFromLink = function () {
1896 return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {
1897 query: query,
1898 variables: variables,
1899 context: context,
1900 fetchPolicy: fetchPolicy,
1901 errorPolicy: errorPolicy,
1902 });
1903 };
1904 var shouldNotify = notifyOnNetworkStatusChange &&
1905 typeof oldNetworkStatus === "number" &&
1906 oldNetworkStatus !== networkStatus &&
1907 isNetworkRequestInFlight(networkStatus);
1908 switch (fetchPolicy) {
1909 default:
1910 case "cache-first": {
1911 var diff = readCache();
1912 if (diff.complete) {
1913 return {
1914 fromLink: false,
1915 sources: [resultsFromCache(diff, queryInfo.markReady())],
1916 };
1917 }
1918 if (returnPartialData || shouldNotify) {
1919 return {
1920 fromLink: true,
1921 sources: [resultsFromCache(diff), resultsFromLink()],
1922 };
1923 }
1924 return { fromLink: true, sources: [resultsFromLink()] };
1925 }
1926 case "cache-and-network": {
1927 var diff = readCache();
1928 if (diff.complete || returnPartialData || shouldNotify) {
1929 return {
1930 fromLink: true,
1931 sources: [resultsFromCache(diff), resultsFromLink()],
1932 };
1933 }
1934 return { fromLink: true, sources: [resultsFromLink()] };
1935 }
1936 case "cache-only":
1937 return {
1938 fromLink: false,
1939 sources: [resultsFromCache(readCache(), queryInfo.markReady())],
1940 };
1941 case "network-only":
1942 if (shouldNotify) {
1943 return {
1944 fromLink: true,
1945 sources: [resultsFromCache(readCache()), resultsFromLink()],
1946 };
1947 }
1948 return { fromLink: true, sources: [resultsFromLink()] };
1949 case "no-cache":
1950 if (shouldNotify) {
1951 return {
1952 fromLink: true,
1953 sources: [resultsFromCache(queryInfo.getDiff()), resultsFromLink()],
1954 };
1955 }
1956 return { fromLink: true, sources: [resultsFromLink()] };
1957 case "standby":
1958 return { fromLink: false, sources: [] };
1959 }
1960 };
1961 QueryManager.prototype.getQuery = function (queryId) {
1962 if (queryId && !this.queries.has(queryId)) {
1963 this.queries.set(queryId, new QueryInfo(this, queryId));
1964 }
1965 return this.queries.get(queryId);
1966 };
1967 QueryManager.prototype.prepareContext = function (context) {
1968 if (context === void 0) { context = {}; }
1969 var newContext = this.localState.prepareContext(context);
1970 return tslib.__assign(tslib.__assign(tslib.__assign({}, this.defaultContext), newContext), { clientAwareness: this.clientAwareness });
1971 };
1972 return QueryManager;
1973}());
1974
1975var LocalState = (function () {
1976 function LocalState(_a) {
1977 var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
1978 this.selectionsToResolveCache = new WeakMap();
1979 this.cache = cache;
1980 if (client) {
1981 this.client = client;
1982 }
1983 if (resolvers) {
1984 this.addResolvers(resolvers);
1985 }
1986 if (fragmentMatcher) {
1987 this.setFragmentMatcher(fragmentMatcher);
1988 }
1989 }
1990 LocalState.prototype.addResolvers = function (resolvers) {
1991 var _this = this;
1992 this.resolvers = this.resolvers || {};
1993 if (Array.isArray(resolvers)) {
1994 resolvers.forEach(function (resolverGroup) {
1995 _this.resolvers = utilities.mergeDeep(_this.resolvers, resolverGroup);
1996 });
1997 }
1998 else {
1999 this.resolvers = utilities.mergeDeep(this.resolvers, resolvers);
2000 }
2001 };
2002 LocalState.prototype.setResolvers = function (resolvers) {
2003 this.resolvers = {};
2004 this.addResolvers(resolvers);
2005 };
2006 LocalState.prototype.getResolvers = function () {
2007 return this.resolvers || {};
2008 };
2009 LocalState.prototype.runResolvers = function (_a) {
2010 return tslib.__awaiter(this, arguments, void 0, function (_b) {
2011 var document = _b.document, remoteResult = _b.remoteResult, context = _b.context, variables = _b.variables, _c = _b.onlyRunForcedResolvers, onlyRunForcedResolvers = _c === void 0 ? false : _c;
2012 return tslib.__generator(this, function (_d) {
2013 if (document) {
2014 return [2 , this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (tslib.__assign(tslib.__assign({}, remoteResult), { data: localResult.result })); })];
2015 }
2016 return [2 , remoteResult];
2017 });
2018 });
2019 };
2020 LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
2021 this.fragmentMatcher = fragmentMatcher;
2022 };
2023 LocalState.prototype.getFragmentMatcher = function () {
2024 return this.fragmentMatcher;
2025 };
2026 LocalState.prototype.clientQuery = function (document) {
2027 if (utilities.hasDirectives(["client"], document)) {
2028 if (this.resolvers) {
2029 return document;
2030 }
2031 }
2032 return null;
2033 };
2034 LocalState.prototype.serverQuery = function (document) {
2035 return utilities.removeClientSetsFromDocument(document);
2036 };
2037 LocalState.prototype.prepareContext = function (context) {
2038 var cache = this.cache;
2039 return tslib.__assign(tslib.__assign({}, context), { cache: cache,
2040 getCacheKey: function (obj) {
2041 return cache.identify(obj);
2042 } });
2043 };
2044 LocalState.prototype.addExportedVariables = function (document_1) {
2045 return tslib.__awaiter(this, arguments, void 0, function (document, variables, context) {
2046 if (variables === void 0) { variables = {}; }
2047 if (context === void 0) { context = {}; }
2048 return tslib.__generator(this, function (_a) {
2049 if (document) {
2050 return [2 , this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (tslib.__assign(tslib.__assign({}, variables), data.exportedVariables)); })];
2051 }
2052 return [2 , tslib.__assign({}, variables)];
2053 });
2054 });
2055 };
2056 LocalState.prototype.shouldForceResolvers = function (document) {
2057 var forceResolvers = false;
2058 graphql.visit(document, {
2059 Directive: {
2060 enter: function (node) {
2061 if (node.name.value === "client" && node.arguments) {
2062 forceResolvers = node.arguments.some(function (arg) {
2063 return arg.name.value === "always" &&
2064 arg.value.kind === "BooleanValue" &&
2065 arg.value.value === true;
2066 });
2067 if (forceResolvers) {
2068 return graphql.BREAK;
2069 }
2070 }
2071 },
2072 },
2073 });
2074 return forceResolvers;
2075 };
2076 LocalState.prototype.buildRootValueFromCache = function (document, variables) {
2077 return this.cache.diff({
2078 query: utilities.buildQueryFromSelectionSet(document),
2079 variables: variables,
2080 returnPartialData: true,
2081 optimistic: false,
2082 }).result;
2083 };
2084 LocalState.prototype.resolveDocument = function (document_1, rootValue_1) {
2085 return tslib.__awaiter(this, arguments, void 0, function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
2086 var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;
2087 if (context === void 0) { context = {}; }
2088 if (variables === void 0) { variables = {}; }
2089 if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
2090 if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
2091 return tslib.__generator(this, function (_b) {
2092 mainDefinition = utilities.getMainDefinition(document);
2093 fragments = utilities.getFragmentDefinitions(document);
2094 fragmentMap = utilities.createFragmentMap(fragments);
2095 selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);
2096 definitionOperation = mainDefinition.operation;
2097 defaultOperationType = definitionOperation ?
2098 definitionOperation.charAt(0).toUpperCase() +
2099 definitionOperation.slice(1)
2100 : "Query";
2101 _a = this, cache = _a.cache, client = _a.client;
2102 execContext = {
2103 fragmentMap: fragmentMap,
2104 context: tslib.__assign(tslib.__assign({}, context), { cache: cache, client: client }),
2105 variables: variables,
2106 fragmentMatcher: fragmentMatcher,
2107 defaultOperationType: defaultOperationType,
2108 exportedVariables: {},
2109 selectionsToResolve: selectionsToResolve,
2110 onlyRunForcedResolvers: onlyRunForcedResolvers,
2111 };
2112 isClientFieldDescendant = false;
2113 return [2 , this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({
2114 result: result,
2115 exportedVariables: execContext.exportedVariables,
2116 }); })];
2117 });
2118 });
2119 };
2120 LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {
2121 return tslib.__awaiter(this, void 0, void 0, function () {
2122 var fragmentMap, context, variables, resultsToMerge, execute;
2123 var _this = this;
2124 return tslib.__generator(this, function (_a) {
2125 fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
2126 resultsToMerge = [rootValue];
2127 execute = function (selection) { return tslib.__awaiter(_this, void 0, void 0, function () {
2128 var fragment, typeCondition;
2129 return tslib.__generator(this, function (_a) {
2130 if (!isClientFieldDescendant &&
2131 !execContext.selectionsToResolve.has(selection)) {
2132 return [2 ];
2133 }
2134 if (!utilities.shouldInclude(selection, variables)) {
2135 return [2 ];
2136 }
2137 if (utilities.isField(selection)) {
2138 return [2 , this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {
2139 var _a;
2140 if (typeof fieldResult !== "undefined") {
2141 resultsToMerge.push((_a = {},
2142 _a[utilities.resultKeyNameFromField(selection)] = fieldResult,
2143 _a));
2144 }
2145 })];
2146 }
2147 if (utilities.isInlineFragment(selection)) {
2148 fragment = selection;
2149 }
2150 else {
2151 fragment = fragmentMap[selection.name.value];
2152 globals.invariant(fragment, 18, selection.name.value);
2153 }
2154 if (fragment && fragment.typeCondition) {
2155 typeCondition = fragment.typeCondition.name.value;
2156 if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
2157 return [2 , this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {
2158 resultsToMerge.push(fragmentResult);
2159 })];
2160 }
2161 }
2162 return [2 ];
2163 });
2164 }); };
2165 return [2 , Promise.all(selectionSet.selections.map(execute)).then(function () {
2166 return utilities.mergeDeepArray(resultsToMerge);
2167 })];
2168 });
2169 });
2170 };
2171 LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {
2172 return tslib.__awaiter(this, void 0, void 0, function () {
2173 var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
2174 var _this = this;
2175 return tslib.__generator(this, function (_a) {
2176 if (!rootValue) {
2177 return [2 , null];
2178 }
2179 variables = execContext.variables;
2180 fieldName = field.name.value;
2181 aliasedFieldName = utilities.resultKeyNameFromField(field);
2182 aliasUsed = fieldName !== aliasedFieldName;
2183 defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
2184 resultPromise = Promise.resolve(defaultResult);
2185 if (!execContext.onlyRunForcedResolvers ||
2186 this.shouldForceResolvers(field)) {
2187 resolverType = rootValue.__typename || execContext.defaultOperationType;
2188 resolverMap = this.resolvers && this.resolvers[resolverType];
2189 if (resolverMap) {
2190 resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
2191 if (resolve) {
2192 resultPromise = Promise.resolve(
2193 cache.cacheSlot.withValue(this.cache, resolve, [
2194 rootValue,
2195 utilities.argumentsObjectFromField(field, variables),
2196 execContext.context,
2197 { field: field, fragmentMap: execContext.fragmentMap },
2198 ]));
2199 }
2200 }
2201 }
2202 return [2 , resultPromise.then(function (result) {
2203 var _a, _b;
2204 if (result === void 0) { result = defaultResult; }
2205 if (field.directives) {
2206 field.directives.forEach(function (directive) {
2207 if (directive.name.value === "export" && directive.arguments) {
2208 directive.arguments.forEach(function (arg) {
2209 if (arg.name.value === "as" && arg.value.kind === "StringValue") {
2210 execContext.exportedVariables[arg.value.value] = result;
2211 }
2212 });
2213 }
2214 });
2215 }
2216 if (!field.selectionSet) {
2217 return result;
2218 }
2219 if (result == null) {
2220 return result;
2221 }
2222 var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === "client"; })) !== null && _b !== void 0 ? _b : false;
2223 if (Array.isArray(result)) {
2224 return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);
2225 }
2226 if (field.selectionSet) {
2227 return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);
2228 }
2229 })];
2230 });
2231 });
2232 };
2233 LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {
2234 var _this = this;
2235 return Promise.all(result.map(function (item) {
2236 if (item === null) {
2237 return null;
2238 }
2239 if (Array.isArray(item)) {
2240 return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);
2241 }
2242 if (field.selectionSet) {
2243 return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);
2244 }
2245 }));
2246 };
2247 LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {
2248 var isSingleASTNode = function (node) { return !Array.isArray(node); };
2249 var selectionsToResolveCache = this.selectionsToResolveCache;
2250 function collectByDefinition(definitionNode) {
2251 if (!selectionsToResolveCache.has(definitionNode)) {
2252 var matches_1 = new Set();
2253 selectionsToResolveCache.set(definitionNode, matches_1);
2254 graphql.visit(definitionNode, {
2255 Directive: function (node, _, __, ___, ancestors) {
2256 if (node.name.value === "client") {
2257 ancestors.forEach(function (node) {
2258 if (isSingleASTNode(node) && graphql.isSelectionNode(node)) {
2259 matches_1.add(node);
2260 }
2261 });
2262 }
2263 },
2264 FragmentSpread: function (spread, _, __, ___, ancestors) {
2265 var fragment = fragmentMap[spread.name.value];
2266 globals.invariant(fragment, 19, spread.name.value);
2267 var fragmentSelections = collectByDefinition(fragment);
2268 if (fragmentSelections.size > 0) {
2269 ancestors.forEach(function (node) {
2270 if (isSingleASTNode(node) && graphql.isSelectionNode(node)) {
2271 matches_1.add(node);
2272 }
2273 });
2274 matches_1.add(spread);
2275 fragmentSelections.forEach(function (selection) {
2276 matches_1.add(selection);
2277 });
2278 }
2279 },
2280 });
2281 }
2282 return selectionsToResolveCache.get(definitionNode);
2283 }
2284 return collectByDefinition(mainDefinition);
2285 };
2286 return LocalState;
2287}());
2288
2289var cacheSizeSymbol = Symbol.for("apollo.cacheSize");
2290var cacheSizes = tslib.__assign({}, globals.global[cacheSizeSymbol]);
2291
2292var globalCaches = {};
2293var getApolloClientMemoryInternals = globalThis.__DEV__ !== false ?
2294 _getApolloClientMemoryInternals
2295 : undefined;
2296function getCurrentCacheSizes() {
2297 var defaults = {
2298 parser: 1000 ,
2299 canonicalStringify: 1000 ,
2300 print: 2000 ,
2301 "documentTransform.cache": 2000 ,
2302 "queryManager.getDocumentInfo": 2000 ,
2303 "PersistedQueryLink.persistedQueryHashes": 2000 ,
2304 "fragmentRegistry.transform": 2000 ,
2305 "fragmentRegistry.lookup": 1000 ,
2306 "fragmentRegistry.findFragmentSpreads": 4000 ,
2307 "cache.fragmentQueryDocuments": 1000 ,
2308 "removeTypenameFromVariables.getVariableDefinitions": 2000 ,
2309 "inMemoryCache.maybeBroadcastWatch": 5000 ,
2310 "inMemoryCache.executeSelectionSet": 50000 ,
2311 "inMemoryCache.executeSubSelectedArray": 10000 ,
2312 };
2313 return Object.fromEntries(Object.entries(defaults).map(function (_a) {
2314 var k = _a[0], v = _a[1];
2315 return [
2316 k,
2317 cacheSizes[k] || v,
2318 ];
2319 }));
2320}
2321function _getApolloClientMemoryInternals() {
2322 var _a, _b, _c, _d, _e;
2323 if (!(globalThis.__DEV__ !== false))
2324 throw new Error("only supported in development mode");
2325 return {
2326 limits: getCurrentCacheSizes(),
2327 sizes: tslib.__assign({ print: (_a = globalCaches.print) === null || _a === void 0 ? void 0 : _a.call(globalCaches), parser: (_b = globalCaches.parser) === null || _b === void 0 ? void 0 : _b.call(globalCaches), canonicalStringify: (_c = globalCaches.canonicalStringify) === null || _c === void 0 ? void 0 : _c.call(globalCaches), links: linkInfo(this.link), queryManager: {
2328 getDocumentInfo: this["queryManager"]["transformCache"].size,
2329 documentTransforms: transformInfo(this["queryManager"].documentTransform),
2330 } }, (_e = (_d = this.cache).getMemoryInternals) === null || _e === void 0 ? void 0 : _e.call(_d)),
2331 };
2332}
2333function isWrapper(f) {
2334 return !!f && "dirtyKey" in f;
2335}
2336function getWrapperInformation(f) {
2337 return isWrapper(f) ? f.size : undefined;
2338}
2339function isDefined(value) {
2340 return value != null;
2341}
2342function transformInfo(transform) {
2343 return recurseTransformInfo(transform).map(function (cache) { return ({ cache: cache }); });
2344}
2345function recurseTransformInfo(transform) {
2346 return transform ?
2347 tslib.__spreadArray(tslib.__spreadArray([
2348 getWrapperInformation(transform === null || transform === void 0 ? void 0 : transform["performWork"])
2349 ], recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["left"]), true), recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["right"]), true).filter(isDefined)
2350 : [];
2351}
2352function linkInfo(link) {
2353 var _a;
2354 return link ?
2355 tslib.__spreadArray(tslib.__spreadArray([
2356 (_a = link === null || link === void 0 ? void 0 : link.getMemoryInternals) === null || _a === void 0 ? void 0 : _a.call(link)
2357 ], linkInfo(link === null || link === void 0 ? void 0 : link.left), true), linkInfo(link === null || link === void 0 ? void 0 : link.right), true).filter(isDefined)
2358 : [];
2359}
2360
2361var hasSuggestedDevtools = false;
2362var ApolloClient = (function () {
2363 function ApolloClient(options) {
2364 var _this = this;
2365 this.resetStoreCallbacks = [];
2366 this.clearStoreCallbacks = [];
2367 if (!options.cache) {
2368 throw globals.newInvariantError(15);
2369 }
2370 var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, documentTransform = options.documentTransform, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b,
2371 connectToDevTools = options.connectToDevTools, _c = options.queryDeduplication, queryDeduplication = _c === void 0 ? true : _c, defaultOptions = options.defaultOptions, defaultContext = options.defaultContext, _d = options.assumeImmutableResults, assumeImmutableResults = _d === void 0 ? cache.assumeImmutableResults : _d, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version, devtools = options.devtools;
2372 var link = options.link;
2373 if (!link) {
2374 link =
2375 uri ? new http.HttpLink({ uri: uri, credentials: credentials, headers: headers }) : core.ApolloLink.empty();
2376 }
2377 this.link = link;
2378 this.cache = cache;
2379 this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
2380 this.queryDeduplication = queryDeduplication;
2381 this.defaultOptions = defaultOptions || Object.create(null);
2382 this.typeDefs = typeDefs;
2383 this.devtoolsConfig = tslib.__assign(tslib.__assign({}, devtools), { enabled: (devtools === null || devtools === void 0 ? void 0 : devtools.enabled) || connectToDevTools });
2384 if (this.devtoolsConfig.enabled === undefined) {
2385 this.devtoolsConfig.enabled = globalThis.__DEV__ !== false;
2386 }
2387 if (ssrForceFetchDelay) {
2388 setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
2389 }
2390 this.watchQuery = this.watchQuery.bind(this);
2391 this.query = this.query.bind(this);
2392 this.mutate = this.mutate.bind(this);
2393 this.watchFragment = this.watchFragment.bind(this);
2394 this.resetStore = this.resetStore.bind(this);
2395 this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
2396 this.version = version;
2397 this.localState = new LocalState({
2398 cache: cache,
2399 client: this,
2400 resolvers: resolvers,
2401 fragmentMatcher: fragmentMatcher,
2402 });
2403 this.queryManager = new QueryManager({
2404 cache: this.cache,
2405 link: this.link,
2406 defaultOptions: this.defaultOptions,
2407 defaultContext: defaultContext,
2408 documentTransform: documentTransform,
2409 queryDeduplication: queryDeduplication,
2410 ssrMode: ssrMode,
2411 clientAwareness: {
2412 name: clientAwarenessName,
2413 version: clientAwarenessVersion,
2414 },
2415 localState: this.localState,
2416 assumeImmutableResults: assumeImmutableResults,
2417 onBroadcast: this.devtoolsConfig.enabled ?
2418 function () {
2419 if (_this.devToolsHookCb) {
2420 _this.devToolsHookCb({
2421 action: {},
2422 state: {
2423 queries: _this.queryManager.getQueryStore(),
2424 mutations: _this.queryManager.mutationStore || {},
2425 },
2426 dataWithOptimisticResults: _this.cache.extract(true),
2427 });
2428 }
2429 }
2430 : void 0,
2431 });
2432 if (this.devtoolsConfig.enabled)
2433 this.connectToDevTools();
2434 }
2435 ApolloClient.prototype.connectToDevTools = function () {
2436 if (typeof window === "undefined") {
2437 return;
2438 }
2439 var windowWithDevTools = window;
2440 var devtoolsSymbol = Symbol.for("apollo.devtools");
2441 (windowWithDevTools[devtoolsSymbol] =
2442 windowWithDevTools[devtoolsSymbol] || []).push(this);
2443 windowWithDevTools.__APOLLO_CLIENT__ = this;
2444 if (!hasSuggestedDevtools && globalThis.__DEV__ !== false) {
2445 hasSuggestedDevtools = true;
2446 if (window.document &&
2447 window.top === window.self &&
2448 /^(https?|file):$/.test(window.location.protocol)) {
2449 setTimeout(function () {
2450 if (!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {
2451 var nav = window.navigator;
2452 var ua = nav && nav.userAgent;
2453 var url = void 0;
2454 if (typeof ua === "string") {
2455 if (ua.indexOf("Chrome/") > -1) {
2456 url =
2457 "https://chrome.google.com/webstore/detail/" +
2458 "apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm";
2459 }
2460 else if (ua.indexOf("Firefox/") > -1) {
2461 url =
2462 "https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/";
2463 }
2464 }
2465 if (url) {
2466 globalThis.__DEV__ !== false && globals.invariant.log("Download the Apollo DevTools for a better development " +
2467 "experience: %s", url);
2468 }
2469 }
2470 }, 10000);
2471 }
2472 }
2473 };
2474 Object.defineProperty(ApolloClient.prototype, "documentTransform", {
2475 get: function () {
2476 return this.queryManager.documentTransform;
2477 },
2478 enumerable: false,
2479 configurable: true
2480 });
2481 ApolloClient.prototype.stop = function () {
2482 this.queryManager.stop();
2483 };
2484 ApolloClient.prototype.watchQuery = function (options) {
2485 if (this.defaultOptions.watchQuery) {
2486 options = utilities.mergeOptions(this.defaultOptions.watchQuery, options);
2487 }
2488 if (this.disableNetworkFetches &&
2489 (options.fetchPolicy === "network-only" ||
2490 options.fetchPolicy === "cache-and-network")) {
2491 options = tslib.__assign(tslib.__assign({}, options), { fetchPolicy: "cache-first" });
2492 }
2493 return this.queryManager.watchQuery(options);
2494 };
2495 ApolloClient.prototype.query = function (options) {
2496 if (this.defaultOptions.query) {
2497 options = utilities.mergeOptions(this.defaultOptions.query, options);
2498 }
2499 globals.invariant(options.fetchPolicy !== "cache-and-network", 16);
2500 if (this.disableNetworkFetches && options.fetchPolicy === "network-only") {
2501 options = tslib.__assign(tslib.__assign({}, options), { fetchPolicy: "cache-first" });
2502 }
2503 return this.queryManager.query(options);
2504 };
2505 ApolloClient.prototype.mutate = function (options) {
2506 if (this.defaultOptions.mutate) {
2507 options = utilities.mergeOptions(this.defaultOptions.mutate, options);
2508 }
2509 return this.queryManager.mutate(options);
2510 };
2511 ApolloClient.prototype.subscribe = function (options) {
2512 return this.queryManager.startGraphQLSubscription(options);
2513 };
2514 ApolloClient.prototype.readQuery = function (options, optimistic) {
2515 if (optimistic === void 0) { optimistic = false; }
2516 return this.cache.readQuery(options, optimistic);
2517 };
2518 ApolloClient.prototype.watchFragment = function (options) {
2519 return this.cache.watchFragment(options);
2520 };
2521 ApolloClient.prototype.readFragment = function (options, optimistic) {
2522 if (optimistic === void 0) { optimistic = false; }
2523 return this.cache.readFragment(options, optimistic);
2524 };
2525 ApolloClient.prototype.writeQuery = function (options) {
2526 var ref = this.cache.writeQuery(options);
2527 if (options.broadcast !== false) {
2528 this.queryManager.broadcastQueries();
2529 }
2530 return ref;
2531 };
2532 ApolloClient.prototype.writeFragment = function (options) {
2533 var ref = this.cache.writeFragment(options);
2534 if (options.broadcast !== false) {
2535 this.queryManager.broadcastQueries();
2536 }
2537 return ref;
2538 };
2539 ApolloClient.prototype.__actionHookForDevTools = function (cb) {
2540 this.devToolsHookCb = cb;
2541 };
2542 ApolloClient.prototype.__requestRaw = function (payload) {
2543 return core.execute(this.link, payload);
2544 };
2545 ApolloClient.prototype.resetStore = function () {
2546 var _this = this;
2547 return Promise.resolve()
2548 .then(function () {
2549 return _this.queryManager.clearStore({
2550 discardWatches: false,
2551 });
2552 })
2553 .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
2554 .then(function () { return _this.reFetchObservableQueries(); });
2555 };
2556 ApolloClient.prototype.clearStore = function () {
2557 var _this = this;
2558 return Promise.resolve()
2559 .then(function () {
2560 return _this.queryManager.clearStore({
2561 discardWatches: true,
2562 });
2563 })
2564 .then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
2565 };
2566 ApolloClient.prototype.onResetStore = function (cb) {
2567 var _this = this;
2568 this.resetStoreCallbacks.push(cb);
2569 return function () {
2570 _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
2571 };
2572 };
2573 ApolloClient.prototype.onClearStore = function (cb) {
2574 var _this = this;
2575 this.clearStoreCallbacks.push(cb);
2576 return function () {
2577 _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
2578 };
2579 };
2580 ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
2581 return this.queryManager.reFetchObservableQueries(includeStandby);
2582 };
2583 ApolloClient.prototype.refetchQueries = function (options) {
2584 var map = this.queryManager.refetchQueries(options);
2585 var queries = [];
2586 var results = [];
2587 map.forEach(function (result, obsQuery) {
2588 queries.push(obsQuery);
2589 results.push(result);
2590 });
2591 var result = Promise.all(results);
2592 result.queries = queries;
2593 result.results = results;
2594 result.catch(function (error) {
2595 globalThis.__DEV__ !== false && globals.invariant.debug(17, error);
2596 });
2597 return result;
2598 };
2599 ApolloClient.prototype.getObservableQueries = function (include) {
2600 if (include === void 0) { include = "active"; }
2601 return this.queryManager.getObservableQueries(include);
2602 };
2603 ApolloClient.prototype.extract = function (optimistic) {
2604 return this.cache.extract(optimistic);
2605 };
2606 ApolloClient.prototype.restore = function (serializedState) {
2607 return this.cache.restore(serializedState);
2608 };
2609 ApolloClient.prototype.addResolvers = function (resolvers) {
2610 this.localState.addResolvers(resolvers);
2611 };
2612 ApolloClient.prototype.setResolvers = function (resolvers) {
2613 this.localState.setResolvers(resolvers);
2614 };
2615 ApolloClient.prototype.getResolvers = function () {
2616 return this.localState.getResolvers();
2617 };
2618 ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
2619 this.localState.setFragmentMatcher(fragmentMatcher);
2620 };
2621 ApolloClient.prototype.setLink = function (newLink) {
2622 this.link = this.queryManager.link = newLink;
2623 };
2624 Object.defineProperty(ApolloClient.prototype, "defaultContext", {
2625 get: function () {
2626 return this.queryManager.defaultContext;
2627 },
2628 enumerable: false,
2629 configurable: true
2630 });
2631 return ApolloClient;
2632}());
2633if (globalThis.__DEV__ !== false) {
2634 ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;
2635}
2636
2637tsInvariant.setVerbosity(globalThis.__DEV__ !== false ? "log" : "silent");
2638
2639exports.DocumentTransform = utilities.DocumentTransform;
2640exports.Observable = utilities.Observable;
2641exports.isReference = utilities.isReference;
2642exports.makeReference = utilities.makeReference;
2643exports.mergeOptions = utilities.mergeOptions;
2644exports.ApolloCache = cache.ApolloCache;
2645exports.Cache = cache.Cache;
2646exports.InMemoryCache = cache.InMemoryCache;
2647exports.MissingFieldError = cache.MissingFieldError;
2648exports.defaultDataIdFromObject = cache.defaultDataIdFromObject;
2649exports.makeVar = cache.makeVar;
2650exports.ApolloError = errors.ApolloError;
2651exports.isApolloError = errors.isApolloError;
2652exports.fromError = utils.fromError;
2653exports.fromPromise = utils.fromPromise;
2654exports.throwServerError = utils.throwServerError;
2655exports.toPromise = utils.toPromise;
2656exports.setLogVerbosity = tsInvariant.setVerbosity;
2657exports.disableExperimentalFragmentVariables = graphqlTag.disableExperimentalFragmentVariables;
2658exports.disableFragmentWarnings = graphqlTag.disableFragmentWarnings;
2659exports.enableExperimentalFragmentVariables = graphqlTag.enableExperimentalFragmentVariables;
2660exports.gql = graphqlTag.gql;
2661exports.resetCaches = graphqlTag.resetCaches;
2662exports.ApolloClient = ApolloClient;
2663exports.ObservableQuery = ObservableQuery;
2664exports.isNetworkRequestSettled = isNetworkRequestSettled;
2665for (var k in core) {
2666 if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = core[k];
2667}
2668for (var k in http) {
2669 if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = http[k];
2670}
2671//# sourceMappingURL=core.cjs.map