UNPKG

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