UNPKG

101 kBJavaScriptView Raw
1import { __extends, __assign, __awaiter, __generator } from 'tslib';
2import { getOperationDefinition, isEqual, tryFunctionOrLogError, cloneDeep, mergeDeep, hasDirectives, removeClientSetsFromDocument, buildQueryFromSelectionSet, getMainDefinition, getFragmentDefinitions, createFragmentMap, mergeDeepArray, resultKeyNameFromField, argumentsObjectFromField, shouldInclude, isField, isInlineFragment, canUseWeakMap, graphQLResultHasError, removeConnectionDirectiveFromDocument, hasClientExports, getDefaultValues, getOperationName } from 'apollo-utilities';
3import { Observable as Observable$1, execute, ApolloLink } from 'apollo-link';
4import $$observable from 'symbol-observable';
5import { InvariantError, invariant } from 'ts-invariant';
6import { visit, BREAK } from 'graphql/language/visitor';
7
8var NetworkStatus;
9(function (NetworkStatus) {
10 NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
11 NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
12 NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
13 NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
14 NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
15 NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
16 NetworkStatus[NetworkStatus["error"] = 8] = "error";
17})(NetworkStatus || (NetworkStatus = {}));
18function isNetworkRequestInFlight(networkStatus) {
19 return networkStatus < 7;
20}
21
22var Observable = (function (_super) {
23 __extends(Observable, _super);
24 function Observable() {
25 return _super !== null && _super.apply(this, arguments) || this;
26 }
27 Observable.prototype[$$observable] = function () {
28 return this;
29 };
30 Observable.prototype['@@observable'] = function () {
31 return this;
32 };
33 return Observable;
34}(Observable$1));
35
36function isNonEmptyArray(value) {
37 return Array.isArray(value) && value.length > 0;
38}
39
40function isApolloError(err) {
41 return err.hasOwnProperty('graphQLErrors');
42}
43var generateErrorMessage = function (err) {
44 var message = '';
45 if (isNonEmptyArray(err.graphQLErrors)) {
46 err.graphQLErrors.forEach(function (graphQLError) {
47 var errorMessage = graphQLError
48 ? graphQLError.message
49 : 'Error message not found.';
50 message += "GraphQL error: " + errorMessage + "\n";
51 });
52 }
53 if (err.networkError) {
54 message += 'Network error: ' + err.networkError.message + '\n';
55 }
56 message = message.replace(/\n$/, '');
57 return message;
58};
59var ApolloError = (function (_super) {
60 __extends(ApolloError, _super);
61 function ApolloError(_a) {
62 var graphQLErrors = _a.graphQLErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;
63 var _this = _super.call(this, errorMessage) || this;
64 _this.graphQLErrors = graphQLErrors || [];
65 _this.networkError = networkError || null;
66 if (!errorMessage) {
67 _this.message = generateErrorMessage(_this);
68 }
69 else {
70 _this.message = errorMessage;
71 }
72 _this.extraInfo = extraInfo;
73 _this.__proto__ = ApolloError.prototype;
74 return _this;
75 }
76 return ApolloError;
77}(Error));
78
79var FetchType;
80(function (FetchType) {
81 FetchType[FetchType["normal"] = 1] = "normal";
82 FetchType[FetchType["refetch"] = 2] = "refetch";
83 FetchType[FetchType["poll"] = 3] = "poll";
84})(FetchType || (FetchType = {}));
85
86var hasError = function (storeValue, policy) {
87 if (policy === void 0) { policy = 'none'; }
88 return storeValue && (storeValue.networkError ||
89 (policy === 'none' && isNonEmptyArray(storeValue.graphQLErrors)));
90};
91var ObservableQuery = (function (_super) {
92 __extends(ObservableQuery, _super);
93 function ObservableQuery(_a) {
94 var queryManager = _a.queryManager, options = _a.options, _b = _a.shouldSubscribe, shouldSubscribe = _b === void 0 ? true : _b;
95 var _this = _super.call(this, function (observer) {
96 return _this.onSubscribe(observer);
97 }) || this;
98 _this.observers = new Set();
99 _this.subscriptions = new Set();
100 _this.isTornDown = false;
101 _this.options = options;
102 _this.variables = options.variables || {};
103 _this.queryId = queryManager.generateQueryId();
104 _this.shouldSubscribe = shouldSubscribe;
105 var opDef = getOperationDefinition(options.query);
106 _this.queryName = opDef && opDef.name && opDef.name.value;
107 _this.queryManager = queryManager;
108 return _this;
109 }
110 ObservableQuery.prototype.result = function () {
111 var _this = this;
112 return new Promise(function (resolve, reject) {
113 var observer = {
114 next: function (result) {
115 resolve(result);
116 _this.observers.delete(observer);
117 if (!_this.observers.size) {
118 _this.queryManager.removeQuery(_this.queryId);
119 }
120 setTimeout(function () {
121 subscription.unsubscribe();
122 }, 0);
123 },
124 error: reject,
125 };
126 var subscription = _this.subscribe(observer);
127 });
128 };
129 ObservableQuery.prototype.currentResult = function () {
130 var result = this.getCurrentResult();
131 if (result.data === undefined) {
132 result.data = {};
133 }
134 return result;
135 };
136 ObservableQuery.prototype.getCurrentResult = function () {
137 if (this.isTornDown) {
138 var lastResult = this.lastResult;
139 return {
140 data: !this.lastError && lastResult && lastResult.data || void 0,
141 error: this.lastError,
142 loading: false,
143 networkStatus: NetworkStatus.error,
144 };
145 }
146 var _a = this.queryManager.getCurrentQueryResult(this), data = _a.data, partial = _a.partial;
147 var queryStoreValue = this.queryManager.queryStore.get(this.queryId);
148 var result;
149 var fetchPolicy = this.options.fetchPolicy;
150 var isNetworkFetchPolicy = fetchPolicy === 'network-only' ||
151 fetchPolicy === 'no-cache';
152 if (queryStoreValue) {
153 var networkStatus = queryStoreValue.networkStatus;
154 if (hasError(queryStoreValue, this.options.errorPolicy)) {
155 return {
156 data: void 0,
157 loading: false,
158 networkStatus: networkStatus,
159 error: new ApolloError({
160 graphQLErrors: queryStoreValue.graphQLErrors,
161 networkError: queryStoreValue.networkError,
162 }),
163 };
164 }
165 if (queryStoreValue.variables) {
166 this.options.variables = __assign(__assign({}, this.options.variables), queryStoreValue.variables);
167 this.variables = this.options.variables;
168 }
169 result = {
170 data: data,
171 loading: isNetworkRequestInFlight(networkStatus),
172 networkStatus: networkStatus,
173 };
174 if (queryStoreValue.graphQLErrors && this.options.errorPolicy === 'all') {
175 result.errors = queryStoreValue.graphQLErrors;
176 }
177 }
178 else {
179 var loading = isNetworkFetchPolicy ||
180 (partial && fetchPolicy !== 'cache-only');
181 result = {
182 data: data,
183 loading: loading,
184 networkStatus: loading ? NetworkStatus.loading : NetworkStatus.ready,
185 };
186 }
187 if (!partial) {
188 this.updateLastResult(__assign(__assign({}, result), { stale: false }));
189 }
190 return __assign(__assign({}, result), { partial: partial });
191 };
192 ObservableQuery.prototype.isDifferentFromLastResult = function (newResult) {
193 var snapshot = this.lastResultSnapshot;
194 return !(snapshot &&
195 newResult &&
196 snapshot.networkStatus === newResult.networkStatus &&
197 snapshot.stale === newResult.stale &&
198 isEqual(snapshot.data, newResult.data));
199 };
200 ObservableQuery.prototype.getLastResult = function () {
201 return this.lastResult;
202 };
203 ObservableQuery.prototype.getLastError = function () {
204 return this.lastError;
205 };
206 ObservableQuery.prototype.resetLastResults = function () {
207 delete this.lastResult;
208 delete this.lastResultSnapshot;
209 delete this.lastError;
210 this.isTornDown = false;
211 };
212 ObservableQuery.prototype.resetQueryStoreErrors = function () {
213 var queryStore = this.queryManager.queryStore.get(this.queryId);
214 if (queryStore) {
215 queryStore.networkError = null;
216 queryStore.graphQLErrors = [];
217 }
218 };
219 ObservableQuery.prototype.refetch = function (variables) {
220 var fetchPolicy = this.options.fetchPolicy;
221 if (fetchPolicy === 'cache-only') {
222 return Promise.reject(process.env.NODE_ENV === "production" ? new InvariantError(3) : new InvariantError('cache-only fetchPolicy option should not be used together with query refetch.'));
223 }
224 if (fetchPolicy !== 'no-cache' &&
225 fetchPolicy !== 'cache-and-network') {
226 fetchPolicy = 'network-only';
227 }
228 if (!isEqual(this.variables, variables)) {
229 this.variables = __assign(__assign({}, this.variables), variables);
230 }
231 if (!isEqual(this.options.variables, this.variables)) {
232 this.options.variables = __assign(__assign({}, this.options.variables), this.variables);
233 }
234 return this.queryManager.fetchQuery(this.queryId, __assign(__assign({}, this.options), { fetchPolicy: fetchPolicy }), FetchType.refetch);
235 };
236 ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
237 var _this = this;
238 process.env.NODE_ENV === "production" ? invariant(fetchMoreOptions.updateQuery, 4) : invariant(fetchMoreOptions.updateQuery, 'updateQuery option is required. This function defines how to update the query data with the new results.');
239 var combinedOptions = __assign(__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : __assign(__assign(__assign({}, this.options), fetchMoreOptions), { variables: __assign(__assign({}, this.variables), fetchMoreOptions.variables) }))), { fetchPolicy: 'network-only' });
240 var qid = this.queryManager.generateQueryId();
241 return this.queryManager
242 .fetchQuery(qid, combinedOptions, FetchType.normal, this.queryId)
243 .then(function (fetchMoreResult) {
244 _this.updateQuery(function (previousResult) {
245 return fetchMoreOptions.updateQuery(previousResult, {
246 fetchMoreResult: fetchMoreResult.data,
247 variables: combinedOptions.variables,
248 });
249 });
250 _this.queryManager.stopQuery(qid);
251 return fetchMoreResult;
252 }, function (error) {
253 _this.queryManager.stopQuery(qid);
254 throw error;
255 });
256 };
257 ObservableQuery.prototype.subscribeToMore = function (options) {
258 var _this = this;
259 var subscription = this.queryManager
260 .startGraphQLSubscription({
261 query: options.document,
262 variables: options.variables,
263 })
264 .subscribe({
265 next: function (subscriptionData) {
266 var updateQuery = options.updateQuery;
267 if (updateQuery) {
268 _this.updateQuery(function (previous, _a) {
269 var variables = _a.variables;
270 return updateQuery(previous, {
271 subscriptionData: subscriptionData,
272 variables: variables,
273 });
274 });
275 }
276 },
277 error: function (err) {
278 if (options.onError) {
279 options.onError(err);
280 return;
281 }
282 process.env.NODE_ENV === "production" || invariant.error('Unhandled GraphQL subscription error', err);
283 },
284 });
285 this.subscriptions.add(subscription);
286 return function () {
287 if (_this.subscriptions.delete(subscription)) {
288 subscription.unsubscribe();
289 }
290 };
291 };
292 ObservableQuery.prototype.setOptions = function (opts) {
293 var oldFetchPolicy = this.options.fetchPolicy;
294 this.options = __assign(__assign({}, this.options), opts);
295 if (opts.pollInterval) {
296 this.startPolling(opts.pollInterval);
297 }
298 else if (opts.pollInterval === 0) {
299 this.stopPolling();
300 }
301 var fetchPolicy = opts.fetchPolicy;
302 return this.setVariables(this.options.variables, oldFetchPolicy !== fetchPolicy && (oldFetchPolicy === 'cache-only' ||
303 oldFetchPolicy === 'standby' ||
304 fetchPolicy === 'network-only'), opts.fetchResults);
305 };
306 ObservableQuery.prototype.setVariables = function (variables, tryFetch, fetchResults) {
307 if (tryFetch === void 0) { tryFetch = false; }
308 if (fetchResults === void 0) { fetchResults = true; }
309 this.isTornDown = false;
310 variables = variables || this.variables;
311 if (!tryFetch && isEqual(variables, this.variables)) {
312 return this.observers.size && fetchResults
313 ? this.result()
314 : Promise.resolve();
315 }
316 this.variables = this.options.variables = variables;
317 if (!this.observers.size) {
318 return Promise.resolve();
319 }
320 return this.queryManager.fetchQuery(this.queryId, this.options);
321 };
322 ObservableQuery.prototype.updateQuery = function (mapFn) {
323 var queryManager = this.queryManager;
324 var _a = queryManager.getQueryWithPreviousResult(this.queryId), previousResult = _a.previousResult, variables = _a.variables, document = _a.document;
325 var newResult = tryFunctionOrLogError(function () {
326 return mapFn(previousResult, { variables: variables });
327 });
328 if (newResult) {
329 queryManager.dataStore.markUpdateQueryResult(document, variables, newResult);
330 queryManager.broadcastQueries();
331 }
332 };
333 ObservableQuery.prototype.stopPolling = function () {
334 this.queryManager.stopPollingQuery(this.queryId);
335 this.options.pollInterval = undefined;
336 };
337 ObservableQuery.prototype.startPolling = function (pollInterval) {
338 assertNotCacheFirstOrOnly(this);
339 this.options.pollInterval = pollInterval;
340 this.queryManager.startPollingQuery(this.options, this.queryId);
341 };
342 ObservableQuery.prototype.updateLastResult = function (newResult) {
343 var previousResult = this.lastResult;
344 this.lastResult = newResult;
345 this.lastResultSnapshot = this.queryManager.assumeImmutableResults
346 ? newResult
347 : cloneDeep(newResult);
348 return previousResult;
349 };
350 ObservableQuery.prototype.onSubscribe = function (observer) {
351 var _this = this;
352 try {
353 var subObserver = observer._subscription._observer;
354 if (subObserver && !subObserver.error) {
355 subObserver.error = defaultSubscriptionObserverErrorCallback;
356 }
357 }
358 catch (_a) { }
359 var first = !this.observers.size;
360 this.observers.add(observer);
361 if (observer.next && this.lastResult)
362 observer.next(this.lastResult);
363 if (observer.error && this.lastError)
364 observer.error(this.lastError);
365 if (first) {
366 this.setUpQuery();
367 }
368 return function () {
369 if (_this.observers.delete(observer) && !_this.observers.size) {
370 _this.tearDownQuery();
371 }
372 };
373 };
374 ObservableQuery.prototype.setUpQuery = function () {
375 var _this = this;
376 var _a = this, queryManager = _a.queryManager, queryId = _a.queryId;
377 if (this.shouldSubscribe) {
378 queryManager.addObservableQuery(queryId, this);
379 }
380 if (this.options.pollInterval) {
381 assertNotCacheFirstOrOnly(this);
382 queryManager.startPollingQuery(this.options, queryId);
383 }
384 var onError = function (error) {
385 _this.updateLastResult(__assign(__assign({}, _this.lastResult), { errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false }));
386 iterateObserversSafely(_this.observers, 'error', _this.lastError = error);
387 };
388 queryManager.observeQuery(queryId, this.options, {
389 next: function (result) {
390 if (_this.lastError || _this.isDifferentFromLastResult(result)) {
391 var previousResult_1 = _this.updateLastResult(result);
392 var _a = _this.options, query_1 = _a.query, variables = _a.variables, fetchPolicy_1 = _a.fetchPolicy;
393 if (queryManager.transform(query_1).hasClientExports) {
394 queryManager.getLocalState().addExportedVariables(query_1, variables).then(function (variables) {
395 var previousVariables = _this.variables;
396 _this.variables = _this.options.variables = variables;
397 if (!result.loading &&
398 previousResult_1 &&
399 fetchPolicy_1 !== 'cache-only' &&
400 queryManager.transform(query_1).serverQuery &&
401 !isEqual(previousVariables, variables)) {
402 _this.refetch();
403 }
404 else {
405 iterateObserversSafely(_this.observers, 'next', result);
406 }
407 });
408 }
409 else {
410 iterateObserversSafely(_this.observers, 'next', result);
411 }
412 }
413 },
414 error: onError,
415 }).catch(onError);
416 };
417 ObservableQuery.prototype.tearDownQuery = function () {
418 var queryManager = this.queryManager;
419 this.isTornDown = true;
420 queryManager.stopPollingQuery(this.queryId);
421 this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
422 this.subscriptions.clear();
423 queryManager.removeObservableQuery(this.queryId);
424 queryManager.stopQuery(this.queryId);
425 this.observers.clear();
426 };
427 return ObservableQuery;
428}(Observable));
429function defaultSubscriptionObserverErrorCallback(error) {
430 process.env.NODE_ENV === "production" || invariant.error('Unhandled error', error.message, error.stack);
431}
432function iterateObserversSafely(observers, method, argument) {
433 var observersWithMethod = [];
434 observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });
435 observersWithMethod.forEach(function (obs) { return obs[method](argument); });
436}
437function assertNotCacheFirstOrOnly(obsQuery) {
438 var fetchPolicy = obsQuery.options.fetchPolicy;
439 process.env.NODE_ENV === "production" ? invariant(fetchPolicy !== 'cache-first' && fetchPolicy !== 'cache-only', 5) : invariant(fetchPolicy !== 'cache-first' && fetchPolicy !== 'cache-only', 'Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.');
440}
441
442var MutationStore = (function () {
443 function MutationStore() {
444 this.store = {};
445 }
446 MutationStore.prototype.getStore = function () {
447 return this.store;
448 };
449 MutationStore.prototype.get = function (mutationId) {
450 return this.store[mutationId];
451 };
452 MutationStore.prototype.initMutation = function (mutationId, mutation, variables) {
453 this.store[mutationId] = {
454 mutation: mutation,
455 variables: variables || {},
456 loading: true,
457 error: null,
458 };
459 };
460 MutationStore.prototype.markMutationError = function (mutationId, error) {
461 var mutation = this.store[mutationId];
462 if (mutation) {
463 mutation.loading = false;
464 mutation.error = error;
465 }
466 };
467 MutationStore.prototype.markMutationResult = function (mutationId) {
468 var mutation = this.store[mutationId];
469 if (mutation) {
470 mutation.loading = false;
471 mutation.error = null;
472 }
473 };
474 MutationStore.prototype.reset = function () {
475 this.store = {};
476 };
477 return MutationStore;
478}());
479
480var QueryStore = (function () {
481 function QueryStore() {
482 this.store = {};
483 }
484 QueryStore.prototype.getStore = function () {
485 return this.store;
486 };
487 QueryStore.prototype.get = function (queryId) {
488 return this.store[queryId];
489 };
490 QueryStore.prototype.initQuery = function (query) {
491 var previousQuery = this.store[query.queryId];
492 process.env.NODE_ENV === "production" ? invariant(!previousQuery ||
493 previousQuery.document === query.document ||
494 isEqual(previousQuery.document, query.document), 19) : invariant(!previousQuery ||
495 previousQuery.document === query.document ||
496 isEqual(previousQuery.document, query.document), 'Internal Error: may not update existing query string in store');
497 var isSetVariables = false;
498 var previousVariables = null;
499 if (query.storePreviousVariables &&
500 previousQuery &&
501 previousQuery.networkStatus !== NetworkStatus.loading) {
502 if (!isEqual(previousQuery.variables, query.variables)) {
503 isSetVariables = true;
504 previousVariables = previousQuery.variables;
505 }
506 }
507 var networkStatus;
508 if (isSetVariables) {
509 networkStatus = NetworkStatus.setVariables;
510 }
511 else if (query.isPoll) {
512 networkStatus = NetworkStatus.poll;
513 }
514 else if (query.isRefetch) {
515 networkStatus = NetworkStatus.refetch;
516 }
517 else {
518 networkStatus = NetworkStatus.loading;
519 }
520 var graphQLErrors = [];
521 if (previousQuery && previousQuery.graphQLErrors) {
522 graphQLErrors = previousQuery.graphQLErrors;
523 }
524 this.store[query.queryId] = {
525 document: query.document,
526 variables: query.variables,
527 previousVariables: previousVariables,
528 networkError: null,
529 graphQLErrors: graphQLErrors,
530 networkStatus: networkStatus,
531 metadata: query.metadata,
532 };
533 if (typeof query.fetchMoreForQueryId === 'string' &&
534 this.store[query.fetchMoreForQueryId]) {
535 this.store[query.fetchMoreForQueryId].networkStatus =
536 NetworkStatus.fetchMore;
537 }
538 };
539 QueryStore.prototype.markQueryResult = function (queryId, result, fetchMoreForQueryId) {
540 if (!this.store || !this.store[queryId])
541 return;
542 this.store[queryId].networkError = null;
543 this.store[queryId].graphQLErrors = isNonEmptyArray(result.errors) ? result.errors : [];
544 this.store[queryId].previousVariables = null;
545 this.store[queryId].networkStatus = NetworkStatus.ready;
546 if (typeof fetchMoreForQueryId === 'string' &&
547 this.store[fetchMoreForQueryId]) {
548 this.store[fetchMoreForQueryId].networkStatus = NetworkStatus.ready;
549 }
550 };
551 QueryStore.prototype.markQueryError = function (queryId, error, fetchMoreForQueryId) {
552 if (!this.store || !this.store[queryId])
553 return;
554 this.store[queryId].networkError = error;
555 this.store[queryId].networkStatus = NetworkStatus.error;
556 if (typeof fetchMoreForQueryId === 'string') {
557 this.markQueryResultClient(fetchMoreForQueryId, true);
558 }
559 };
560 QueryStore.prototype.markQueryResultClient = function (queryId, complete) {
561 var storeValue = this.store && this.store[queryId];
562 if (storeValue) {
563 storeValue.networkError = null;
564 storeValue.previousVariables = null;
565 if (complete) {
566 storeValue.networkStatus = NetworkStatus.ready;
567 }
568 }
569 };
570 QueryStore.prototype.stopQuery = function (queryId) {
571 delete this.store[queryId];
572 };
573 QueryStore.prototype.reset = function (observableQueryIds) {
574 var _this = this;
575 Object.keys(this.store).forEach(function (queryId) {
576 if (observableQueryIds.indexOf(queryId) < 0) {
577 _this.stopQuery(queryId);
578 }
579 else {
580 _this.store[queryId].networkStatus = NetworkStatus.loading;
581 }
582 });
583 };
584 return QueryStore;
585}());
586
587function capitalizeFirstLetter(str) {
588 return str.charAt(0).toUpperCase() + str.slice(1);
589}
590
591var LocalState = (function () {
592 function LocalState(_a) {
593 var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
594 this.cache = cache;
595 if (client) {
596 this.client = client;
597 }
598 if (resolvers) {
599 this.addResolvers(resolvers);
600 }
601 if (fragmentMatcher) {
602 this.setFragmentMatcher(fragmentMatcher);
603 }
604 }
605 LocalState.prototype.addResolvers = function (resolvers) {
606 var _this = this;
607 this.resolvers = this.resolvers || {};
608 if (Array.isArray(resolvers)) {
609 resolvers.forEach(function (resolverGroup) {
610 _this.resolvers = mergeDeep(_this.resolvers, resolverGroup);
611 });
612 }
613 else {
614 this.resolvers = mergeDeep(this.resolvers, resolvers);
615 }
616 };
617 LocalState.prototype.setResolvers = function (resolvers) {
618 this.resolvers = {};
619 this.addResolvers(resolvers);
620 };
621 LocalState.prototype.getResolvers = function () {
622 return this.resolvers || {};
623 };
624 LocalState.prototype.runResolvers = function (_a) {
625 var document = _a.document, remoteResult = _a.remoteResult, context = _a.context, variables = _a.variables, _b = _a.onlyRunForcedResolvers, onlyRunForcedResolvers = _b === void 0 ? false : _b;
626 return __awaiter(this, void 0, void 0, function () {
627 return __generator(this, function (_c) {
628 if (document) {
629 return [2, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (__assign(__assign({}, remoteResult), { data: localResult.result })); })];
630 }
631 return [2, remoteResult];
632 });
633 });
634 };
635 LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
636 this.fragmentMatcher = fragmentMatcher;
637 };
638 LocalState.prototype.getFragmentMatcher = function () {
639 return this.fragmentMatcher;
640 };
641 LocalState.prototype.clientQuery = function (document) {
642 if (hasDirectives(['client'], document)) {
643 if (this.resolvers) {
644 return document;
645 }
646 process.env.NODE_ENV === "production" || invariant.warn('Found @client directives in a query but no ApolloClient resolvers ' +
647 'were specified. This means ApolloClient local resolver handling ' +
648 'has been disabled, and @client directives will be passed through ' +
649 'to your link chain.');
650 }
651 return null;
652 };
653 LocalState.prototype.serverQuery = function (document) {
654 return this.resolvers ? removeClientSetsFromDocument(document) : document;
655 };
656 LocalState.prototype.prepareContext = function (context) {
657 if (context === void 0) { context = {}; }
658 var cache = this.cache;
659 var newContext = __assign(__assign({}, context), { cache: cache, getCacheKey: function (obj) {
660 if (cache.config) {
661 return cache.config.dataIdFromObject(obj);
662 }
663 else {
664 process.env.NODE_ENV === "production" ? invariant(false, 6) : invariant(false, 'To use context.getCacheKey, you need to use a cache that has ' +
665 'a configurable dataIdFromObject, like apollo-cache-inmemory.');
666 }
667 } });
668 return newContext;
669 };
670 LocalState.prototype.addExportedVariables = function (document, variables, context) {
671 if (variables === void 0) { variables = {}; }
672 if (context === void 0) { context = {}; }
673 return __awaiter(this, void 0, void 0, function () {
674 return __generator(this, function (_a) {
675 if (document) {
676 return [2, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (__assign(__assign({}, variables), data.exportedVariables)); })];
677 }
678 return [2, __assign({}, variables)];
679 });
680 });
681 };
682 LocalState.prototype.shouldForceResolvers = function (document) {
683 var forceResolvers = false;
684 visit(document, {
685 Directive: {
686 enter: function (node) {
687 if (node.name.value === 'client' && node.arguments) {
688 forceResolvers = node.arguments.some(function (arg) {
689 return arg.name.value === 'always' &&
690 arg.value.kind === 'BooleanValue' &&
691 arg.value.value === true;
692 });
693 if (forceResolvers) {
694 return BREAK;
695 }
696 }
697 },
698 },
699 });
700 return forceResolvers;
701 };
702 LocalState.prototype.buildRootValueFromCache = function (document, variables) {
703 return this.cache.diff({
704 query: buildQueryFromSelectionSet(document),
705 variables: variables,
706 returnPartialData: true,
707 optimistic: false,
708 }).result;
709 };
710 LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
711 if (context === void 0) { context = {}; }
712 if (variables === void 0) { variables = {}; }
713 if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
714 if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
715 return __awaiter(this, void 0, void 0, function () {
716 var mainDefinition, fragments, fragmentMap, definitionOperation, defaultOperationType, _a, cache, client, execContext;
717 return __generator(this, function (_b) {
718 mainDefinition = getMainDefinition(document);
719 fragments = getFragmentDefinitions(document);
720 fragmentMap = createFragmentMap(fragments);
721 definitionOperation = mainDefinition
722 .operation;
723 defaultOperationType = definitionOperation
724 ? capitalizeFirstLetter(definitionOperation)
725 : 'Query';
726 _a = this, cache = _a.cache, client = _a.client;
727 execContext = {
728 fragmentMap: fragmentMap,
729 context: __assign(__assign({}, context), { cache: cache,
730 client: client }),
731 variables: variables,
732 fragmentMatcher: fragmentMatcher,
733 defaultOperationType: defaultOperationType,
734 exportedVariables: {},
735 onlyRunForcedResolvers: onlyRunForcedResolvers,
736 };
737 return [2, this.resolveSelectionSet(mainDefinition.selectionSet, rootValue, execContext).then(function (result) { return ({
738 result: result,
739 exportedVariables: execContext.exportedVariables,
740 }); })];
741 });
742 });
743 };
744 LocalState.prototype.resolveSelectionSet = function (selectionSet, rootValue, execContext) {
745 return __awaiter(this, void 0, void 0, function () {
746 var fragmentMap, context, variables, resultsToMerge, execute;
747 var _this = this;
748 return __generator(this, function (_a) {
749 fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
750 resultsToMerge = [rootValue];
751 execute = function (selection) { return __awaiter(_this, void 0, void 0, function () {
752 var fragment, typeCondition;
753 return __generator(this, function (_a) {
754 if (!shouldInclude(selection, variables)) {
755 return [2];
756 }
757 if (isField(selection)) {
758 return [2, this.resolveField(selection, rootValue, execContext).then(function (fieldResult) {
759 var _a;
760 if (typeof fieldResult !== 'undefined') {
761 resultsToMerge.push((_a = {},
762 _a[resultKeyNameFromField(selection)] = fieldResult,
763 _a));
764 }
765 })];
766 }
767 if (isInlineFragment(selection)) {
768 fragment = selection;
769 }
770 else {
771 fragment = fragmentMap[selection.name.value];
772 process.env.NODE_ENV === "production" ? invariant(fragment, 7) : invariant(fragment, "No fragment named " + selection.name.value);
773 }
774 if (fragment && fragment.typeCondition) {
775 typeCondition = fragment.typeCondition.name.value;
776 if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
777 return [2, this.resolveSelectionSet(fragment.selectionSet, rootValue, execContext).then(function (fragmentResult) {
778 resultsToMerge.push(fragmentResult);
779 })];
780 }
781 }
782 return [2];
783 });
784 }); };
785 return [2, Promise.all(selectionSet.selections.map(execute)).then(function () {
786 return mergeDeepArray(resultsToMerge);
787 })];
788 });
789 });
790 };
791 LocalState.prototype.resolveField = function (field, rootValue, execContext) {
792 return __awaiter(this, void 0, void 0, function () {
793 var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
794 var _this = this;
795 return __generator(this, function (_a) {
796 variables = execContext.variables;
797 fieldName = field.name.value;
798 aliasedFieldName = resultKeyNameFromField(field);
799 aliasUsed = fieldName !== aliasedFieldName;
800 defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
801 resultPromise = Promise.resolve(defaultResult);
802 if (!execContext.onlyRunForcedResolvers ||
803 this.shouldForceResolvers(field)) {
804 resolverType = rootValue.__typename || execContext.defaultOperationType;
805 resolverMap = this.resolvers && this.resolvers[resolverType];
806 if (resolverMap) {
807 resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
808 if (resolve) {
809 resultPromise = Promise.resolve(resolve(rootValue, argumentsObjectFromField(field, variables), execContext.context, { field: field, fragmentMap: execContext.fragmentMap }));
810 }
811 }
812 }
813 return [2, resultPromise.then(function (result) {
814 if (result === void 0) { result = defaultResult; }
815 if (field.directives) {
816 field.directives.forEach(function (directive) {
817 if (directive.name.value === 'export' && directive.arguments) {
818 directive.arguments.forEach(function (arg) {
819 if (arg.name.value === 'as' && arg.value.kind === 'StringValue') {
820 execContext.exportedVariables[arg.value.value] = result;
821 }
822 });
823 }
824 });
825 }
826 if (!field.selectionSet) {
827 return result;
828 }
829 if (result == null) {
830 return result;
831 }
832 if (Array.isArray(result)) {
833 return _this.resolveSubSelectedArray(field, result, execContext);
834 }
835 if (field.selectionSet) {
836 return _this.resolveSelectionSet(field.selectionSet, result, execContext);
837 }
838 })];
839 });
840 });
841 };
842 LocalState.prototype.resolveSubSelectedArray = function (field, result, execContext) {
843 var _this = this;
844 return Promise.all(result.map(function (item) {
845 if (item === null) {
846 return null;
847 }
848 if (Array.isArray(item)) {
849 return _this.resolveSubSelectedArray(field, item, execContext);
850 }
851 if (field.selectionSet) {
852 return _this.resolveSelectionSet(field.selectionSet, item, execContext);
853 }
854 }));
855 };
856 return LocalState;
857}());
858
859function multiplex(inner) {
860 var observers = new Set();
861 var sub = null;
862 return new Observable(function (observer) {
863 observers.add(observer);
864 sub = sub || inner.subscribe({
865 next: function (value) {
866 observers.forEach(function (obs) { return obs.next && obs.next(value); });
867 },
868 error: function (error) {
869 observers.forEach(function (obs) { return obs.error && obs.error(error); });
870 },
871 complete: function () {
872 observers.forEach(function (obs) { return obs.complete && obs.complete(); });
873 },
874 });
875 return function () {
876 if (observers.delete(observer) && !observers.size && sub) {
877 sub.unsubscribe();
878 sub = null;
879 }
880 };
881 });
882}
883function asyncMap(observable, mapFn) {
884 return new Observable(function (observer) {
885 var next = observer.next, error = observer.error, complete = observer.complete;
886 var activeNextCount = 0;
887 var completed = false;
888 var handler = {
889 next: function (value) {
890 ++activeNextCount;
891 new Promise(function (resolve) {
892 resolve(mapFn(value));
893 }).then(function (result) {
894 --activeNextCount;
895 next && next.call(observer, result);
896 completed && handler.complete();
897 }, function (e) {
898 --activeNextCount;
899 error && error.call(observer, e);
900 });
901 },
902 error: function (e) {
903 error && error.call(observer, e);
904 },
905 complete: function () {
906 completed = true;
907 if (!activeNextCount) {
908 complete && complete.call(observer);
909 }
910 },
911 };
912 var sub = observable.subscribe(handler);
913 return function () { return sub.unsubscribe(); };
914 });
915}
916
917var hasOwnProperty = Object.prototype.hasOwnProperty;
918var QueryManager = (function () {
919 function QueryManager(_a) {
920 var link = _a.link, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, store = _a.store, _c = _a.onBroadcast, onBroadcast = _c === void 0 ? function () { return undefined; } : _c, _d = _a.ssrMode, ssrMode = _d === void 0 ? false : _d, _e = _a.clientAwareness, clientAwareness = _e === void 0 ? {} : _e, localState = _a.localState, assumeImmutableResults = _a.assumeImmutableResults;
921 this.mutationStore = new MutationStore();
922 this.queryStore = new QueryStore();
923 this.clientAwareness = {};
924 this.idCounter = 1;
925 this.queries = new Map();
926 this.fetchQueryRejectFns = new Map();
927 this.transformCache = new (canUseWeakMap ? WeakMap : Map)();
928 this.inFlightLinkObservables = new Map();
929 this.pollingInfoByQueryId = new Map();
930 this.link = link;
931 this.queryDeduplication = queryDeduplication;
932 this.dataStore = store;
933 this.onBroadcast = onBroadcast;
934 this.clientAwareness = clientAwareness;
935 this.localState = localState || new LocalState({ cache: store.getCache() });
936 this.ssrMode = ssrMode;
937 this.assumeImmutableResults = !!assumeImmutableResults;
938 }
939 QueryManager.prototype.stop = function () {
940 var _this = this;
941 this.queries.forEach(function (_info, queryId) {
942 _this.stopQueryNoBroadcast(queryId);
943 });
944 this.fetchQueryRejectFns.forEach(function (reject) {
945 reject(process.env.NODE_ENV === "production" ? new InvariantError(8) : new InvariantError('QueryManager stopped while query was in flight'));
946 });
947 };
948 QueryManager.prototype.mutate = function (_a) {
949 var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueriesByName = _a.updateQueries, _b = _a.refetchQueries, refetchQueries = _b === void 0 ? [] : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, updateWithProxyFn = _a.update, _d = _a.errorPolicy, errorPolicy = _d === void 0 ? 'none' : _d, fetchPolicy = _a.fetchPolicy, _e = _a.context, context = _e === void 0 ? {} : _e;
950 return __awaiter(this, void 0, void 0, function () {
951 var mutationId, generateUpdateQueriesInfo, self;
952 var _this = this;
953 return __generator(this, function (_f) {
954 switch (_f.label) {
955 case 0:
956 process.env.NODE_ENV === "production" ? invariant(mutation, 9) : invariant(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.');
957 process.env.NODE_ENV === "production" ? invariant(!fetchPolicy || fetchPolicy === 'no-cache', 10) : invariant(!fetchPolicy || fetchPolicy === 'no-cache', "Mutations only support a 'no-cache' fetchPolicy. If you don't want to disable the cache, remove your fetchPolicy setting to proceed with the default mutation behavior.");
958 mutationId = this.generateQueryId();
959 mutation = this.transform(mutation).document;
960 this.setQuery(mutationId, function () { return ({ document: mutation }); });
961 variables = this.getVariables(mutation, variables);
962 if (!this.transform(mutation).hasClientExports) return [3, 2];
963 return [4, this.localState.addExportedVariables(mutation, variables, context)];
964 case 1:
965 variables = _f.sent();
966 _f.label = 2;
967 case 2:
968 generateUpdateQueriesInfo = function () {
969 var ret = {};
970 if (updateQueriesByName) {
971 _this.queries.forEach(function (_a, queryId) {
972 var observableQuery = _a.observableQuery;
973 if (observableQuery) {
974 var queryName = observableQuery.queryName;
975 if (queryName &&
976 hasOwnProperty.call(updateQueriesByName, queryName)) {
977 ret[queryId] = {
978 updater: updateQueriesByName[queryName],
979 query: _this.queryStore.get(queryId),
980 };
981 }
982 }
983 });
984 }
985 return ret;
986 };
987 this.mutationStore.initMutation(mutationId, mutation, variables);
988 this.dataStore.markMutationInit({
989 mutationId: mutationId,
990 document: mutation,
991 variables: variables,
992 updateQueries: generateUpdateQueriesInfo(),
993 update: updateWithProxyFn,
994 optimisticResponse: optimisticResponse,
995 });
996 this.broadcastQueries();
997 self = this;
998 return [2, new Promise(function (resolve, reject) {
999 var storeResult;
1000 var error;
1001 self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: optimisticResponse }), variables, false).subscribe({
1002 next: function (result) {
1003 if (graphQLResultHasError(result) && errorPolicy === 'none') {
1004 error = new ApolloError({
1005 graphQLErrors: result.errors,
1006 });
1007 return;
1008 }
1009 self.mutationStore.markMutationResult(mutationId);
1010 if (fetchPolicy !== 'no-cache') {
1011 self.dataStore.markMutationResult({
1012 mutationId: mutationId,
1013 result: result,
1014 document: mutation,
1015 variables: variables,
1016 updateQueries: generateUpdateQueriesInfo(),
1017 update: updateWithProxyFn,
1018 });
1019 }
1020 storeResult = result;
1021 },
1022 error: function (err) {
1023 self.mutationStore.markMutationError(mutationId, err);
1024 self.dataStore.markMutationComplete({
1025 mutationId: mutationId,
1026 optimisticResponse: optimisticResponse,
1027 });
1028 self.broadcastQueries();
1029 self.setQuery(mutationId, function () { return ({ document: null }); });
1030 reject(new ApolloError({
1031 networkError: err,
1032 }));
1033 },
1034 complete: function () {
1035 if (error) {
1036 self.mutationStore.markMutationError(mutationId, error);
1037 }
1038 self.dataStore.markMutationComplete({
1039 mutationId: mutationId,
1040 optimisticResponse: optimisticResponse,
1041 });
1042 self.broadcastQueries();
1043 if (error) {
1044 reject(error);
1045 return;
1046 }
1047 if (typeof refetchQueries === 'function') {
1048 refetchQueries = refetchQueries(storeResult);
1049 }
1050 var refetchQueryPromises = [];
1051 if (isNonEmptyArray(refetchQueries)) {
1052 refetchQueries.forEach(function (refetchQuery) {
1053 if (typeof refetchQuery === 'string') {
1054 self.queries.forEach(function (_a) {
1055 var observableQuery = _a.observableQuery;
1056 if (observableQuery &&
1057 observableQuery.queryName === refetchQuery) {
1058 refetchQueryPromises.push(observableQuery.refetch());
1059 }
1060 });
1061 }
1062 else {
1063 var queryOptions = {
1064 query: refetchQuery.query,
1065 variables: refetchQuery.variables,
1066 fetchPolicy: 'network-only',
1067 };
1068 if (refetchQuery.context) {
1069 queryOptions.context = refetchQuery.context;
1070 }
1071 refetchQueryPromises.push(self.query(queryOptions));
1072 }
1073 });
1074 }
1075 Promise.all(awaitRefetchQueries ? refetchQueryPromises : []).then(function () {
1076 self.setQuery(mutationId, function () { return ({ document: null }); });
1077 if (errorPolicy === 'ignore' &&
1078 storeResult &&
1079 graphQLResultHasError(storeResult)) {
1080 delete storeResult.errors;
1081 }
1082 resolve(storeResult);
1083 });
1084 },
1085 });
1086 })];
1087 }
1088 });
1089 });
1090 };
1091 QueryManager.prototype.fetchQuery = function (queryId, options, fetchType, fetchMoreForQueryId) {
1092 return __awaiter(this, void 0, void 0, function () {
1093 var _a, metadata, _b, fetchPolicy, _c, context, query, variables, storeResult, isNetworkOnly, needToFetch, _d, complete, result, shouldFetch, requestId, cancel, networkResult;
1094 var _this = this;
1095 return __generator(this, function (_e) {
1096 switch (_e.label) {
1097 case 0:
1098 _a = options.metadata, metadata = _a === void 0 ? null : _a, _b = options.fetchPolicy, fetchPolicy = _b === void 0 ? 'cache-first' : _b, _c = options.context, context = _c === void 0 ? {} : _c;
1099 query = this.transform(options.query).document;
1100 variables = this.getVariables(query, options.variables);
1101 if (!this.transform(query).hasClientExports) return [3, 2];
1102 return [4, this.localState.addExportedVariables(query, variables, context)];
1103 case 1:
1104 variables = _e.sent();
1105 _e.label = 2;
1106 case 2:
1107 options = __assign(__assign({}, options), { variables: variables });
1108 isNetworkOnly = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache';
1109 needToFetch = isNetworkOnly;
1110 if (!isNetworkOnly) {
1111 _d = this.dataStore.getCache().diff({
1112 query: query,
1113 variables: variables,
1114 returnPartialData: true,
1115 optimistic: false,
1116 }), complete = _d.complete, result = _d.result;
1117 needToFetch = !complete || fetchPolicy === 'cache-and-network';
1118 storeResult = result;
1119 }
1120 shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby';
1121 if (hasDirectives(['live'], query))
1122 shouldFetch = true;
1123 requestId = this.idCounter++;
1124 cancel = fetchPolicy !== 'no-cache'
1125 ? this.updateQueryWatch(queryId, query, options)
1126 : undefined;
1127 this.setQuery(queryId, function () { return ({
1128 document: query,
1129 lastRequestId: requestId,
1130 invalidated: true,
1131 cancel: cancel,
1132 }); });
1133 this.invalidate(fetchMoreForQueryId);
1134 this.queryStore.initQuery({
1135 queryId: queryId,
1136 document: query,
1137 storePreviousVariables: shouldFetch,
1138 variables: variables,
1139 isPoll: fetchType === FetchType.poll,
1140 isRefetch: fetchType === FetchType.refetch,
1141 metadata: metadata,
1142 fetchMoreForQueryId: fetchMoreForQueryId,
1143 });
1144 this.broadcastQueries();
1145 if (shouldFetch) {
1146 networkResult = this.fetchRequest({
1147 requestId: requestId,
1148 queryId: queryId,
1149 document: query,
1150 options: options,
1151 fetchMoreForQueryId: fetchMoreForQueryId,
1152 }).catch(function (error) {
1153 if (isApolloError(error)) {
1154 throw error;
1155 }
1156 else {
1157 if (requestId >= _this.getQuery(queryId).lastRequestId) {
1158 _this.queryStore.markQueryError(queryId, error, fetchMoreForQueryId);
1159 _this.invalidate(queryId);
1160 _this.invalidate(fetchMoreForQueryId);
1161 _this.broadcastQueries();
1162 }
1163 throw new ApolloError({ networkError: error });
1164 }
1165 });
1166 if (fetchPolicy !== 'cache-and-network') {
1167 return [2, networkResult];
1168 }
1169 networkResult.catch(function () { });
1170 }
1171 this.queryStore.markQueryResultClient(queryId, !shouldFetch);
1172 this.invalidate(queryId);
1173 this.invalidate(fetchMoreForQueryId);
1174 if (this.transform(query).hasForcedResolvers) {
1175 return [2, this.localState.runResolvers({
1176 document: query,
1177 remoteResult: { data: storeResult },
1178 context: context,
1179 variables: variables,
1180 onlyRunForcedResolvers: true,
1181 }).then(function (result) {
1182 _this.markQueryResult(queryId, result, options, fetchMoreForQueryId);
1183 _this.broadcastQueries();
1184 return result;
1185 })];
1186 }
1187 this.broadcastQueries();
1188 return [2, { data: storeResult }];
1189 }
1190 });
1191 });
1192 };
1193 QueryManager.prototype.markQueryResult = function (queryId, result, _a, fetchMoreForQueryId) {
1194 var fetchPolicy = _a.fetchPolicy, variables = _a.variables, errorPolicy = _a.errorPolicy;
1195 if (fetchPolicy === 'no-cache') {
1196 this.setQuery(queryId, function () { return ({
1197 newData: { result: result.data, complete: true },
1198 }); });
1199 }
1200 else {
1201 this.dataStore.markQueryResult(result, this.getQuery(queryId).document, variables, fetchMoreForQueryId, errorPolicy === 'ignore' || errorPolicy === 'all');
1202 }
1203 };
1204 QueryManager.prototype.queryListenerForObserver = function (queryId, options, observer) {
1205 var _this = this;
1206 function invoke(method, argument) {
1207 if (observer[method]) {
1208 try {
1209 observer[method](argument);
1210 }
1211 catch (e) {
1212 process.env.NODE_ENV === "production" || invariant.error(e);
1213 }
1214 }
1215 else if (method === 'error') {
1216 process.env.NODE_ENV === "production" || invariant.error(argument);
1217 }
1218 }
1219 return function (queryStoreValue, newData) {
1220 _this.invalidate(queryId, false);
1221 if (!queryStoreValue)
1222 return;
1223 var _a = _this.getQuery(queryId), observableQuery = _a.observableQuery, document = _a.document;
1224 var fetchPolicy = observableQuery
1225 ? observableQuery.options.fetchPolicy
1226 : options.fetchPolicy;
1227 if (fetchPolicy === 'standby')
1228 return;
1229 var loading = isNetworkRequestInFlight(queryStoreValue.networkStatus);
1230 var lastResult = observableQuery && observableQuery.getLastResult();
1231 var networkStatusChanged = !!(lastResult &&
1232 lastResult.networkStatus !== queryStoreValue.networkStatus);
1233 var shouldNotifyIfLoading = options.returnPartialData ||
1234 (!newData && queryStoreValue.previousVariables) ||
1235 (networkStatusChanged && options.notifyOnNetworkStatusChange) ||
1236 fetchPolicy === 'cache-only' ||
1237 fetchPolicy === 'cache-and-network';
1238 if (loading && !shouldNotifyIfLoading) {
1239 return;
1240 }
1241 var hasGraphQLErrors = isNonEmptyArray(queryStoreValue.graphQLErrors);
1242 var errorPolicy = observableQuery
1243 && observableQuery.options.errorPolicy
1244 || options.errorPolicy
1245 || 'none';
1246 if (errorPolicy === 'none' && hasGraphQLErrors || queryStoreValue.networkError) {
1247 return invoke('error', new ApolloError({
1248 graphQLErrors: queryStoreValue.graphQLErrors,
1249 networkError: queryStoreValue.networkError,
1250 }));
1251 }
1252 try {
1253 var data = void 0;
1254 var isMissing = void 0;
1255 if (newData) {
1256 if (fetchPolicy !== 'no-cache' && fetchPolicy !== 'network-only') {
1257 _this.setQuery(queryId, function () { return ({ newData: null }); });
1258 }
1259 data = newData.result;
1260 isMissing = !newData.complete;
1261 }
1262 else {
1263 var lastError = observableQuery && observableQuery.getLastError();
1264 var errorStatusChanged = errorPolicy !== 'none' &&
1265 (lastError && lastError.graphQLErrors) !==
1266 queryStoreValue.graphQLErrors;
1267 if (lastResult && lastResult.data && !errorStatusChanged) {
1268 data = lastResult.data;
1269 isMissing = false;
1270 }
1271 else {
1272 var diffResult = _this.dataStore.getCache().diff({
1273 query: document,
1274 variables: queryStoreValue.previousVariables ||
1275 queryStoreValue.variables,
1276 returnPartialData: true,
1277 optimistic: true,
1278 });
1279 data = diffResult.result;
1280 isMissing = !diffResult.complete;
1281 }
1282 }
1283 var stale = isMissing && !(options.returnPartialData ||
1284 fetchPolicy === 'cache-only');
1285 var resultFromStore = {
1286 data: stale ? lastResult && lastResult.data : data,
1287 loading: loading,
1288 networkStatus: queryStoreValue.networkStatus,
1289 stale: stale,
1290 };
1291 if (errorPolicy === 'all' && hasGraphQLErrors) {
1292 resultFromStore.errors = queryStoreValue.graphQLErrors;
1293 }
1294 invoke('next', resultFromStore);
1295 }
1296 catch (networkError) {
1297 invoke('error', new ApolloError({ networkError: networkError }));
1298 }
1299 };
1300 };
1301 QueryManager.prototype.transform = function (document) {
1302 var transformCache = this.transformCache;
1303 if (!transformCache.has(document)) {
1304 var cache = this.dataStore.getCache();
1305 var transformed = cache.transformDocument(document);
1306 var forLink = removeConnectionDirectiveFromDocument(cache.transformForLink(transformed));
1307 var clientQuery = this.localState.clientQuery(transformed);
1308 var serverQuery = this.localState.serverQuery(forLink);
1309 var cacheEntry_1 = {
1310 document: transformed,
1311 hasClientExports: hasClientExports(transformed),
1312 hasForcedResolvers: this.localState.shouldForceResolvers(transformed),
1313 clientQuery: clientQuery,
1314 serverQuery: serverQuery,
1315 defaultVars: getDefaultValues(getOperationDefinition(transformed)),
1316 };
1317 var add = function (doc) {
1318 if (doc && !transformCache.has(doc)) {
1319 transformCache.set(doc, cacheEntry_1);
1320 }
1321 };
1322 add(document);
1323 add(transformed);
1324 add(clientQuery);
1325 add(serverQuery);
1326 }
1327 return transformCache.get(document);
1328 };
1329 QueryManager.prototype.getVariables = function (document, variables) {
1330 return __assign(__assign({}, this.transform(document).defaultVars), variables);
1331 };
1332 QueryManager.prototype.watchQuery = function (options, shouldSubscribe) {
1333 if (shouldSubscribe === void 0) { shouldSubscribe = true; }
1334 process.env.NODE_ENV === "production" ? invariant(options.fetchPolicy !== 'standby', 11) : invariant(options.fetchPolicy !== 'standby', 'client.watchQuery cannot be called with fetchPolicy set to "standby"');
1335 options.variables = this.getVariables(options.query, options.variables);
1336 if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
1337 options.notifyOnNetworkStatusChange = false;
1338 }
1339 var transformedOptions = __assign({}, options);
1340 return new ObservableQuery({
1341 queryManager: this,
1342 options: transformedOptions,
1343 shouldSubscribe: shouldSubscribe,
1344 });
1345 };
1346 QueryManager.prototype.query = function (options) {
1347 var _this = this;
1348 process.env.NODE_ENV === "production" ? invariant(options.query, 12) : invariant(options.query, 'query option is required. You must specify your GraphQL document ' +
1349 'in the query option.');
1350 process.env.NODE_ENV === "production" ? invariant(options.query.kind === 'Document', 13) : invariant(options.query.kind === 'Document', 'You must wrap the query string in a "gql" tag.');
1351 process.env.NODE_ENV === "production" ? invariant(!options.returnPartialData, 14) : invariant(!options.returnPartialData, 'returnPartialData option only supported on watchQuery.');
1352 process.env.NODE_ENV === "production" ? invariant(!options.pollInterval, 15) : invariant(!options.pollInterval, 'pollInterval option only supported on watchQuery.');
1353 return new Promise(function (resolve, reject) {
1354 var watchedQuery = _this.watchQuery(options, false);
1355 _this.fetchQueryRejectFns.set("query:" + watchedQuery.queryId, reject);
1356 watchedQuery
1357 .result()
1358 .then(resolve, reject)
1359 .then(function () {
1360 return _this.fetchQueryRejectFns.delete("query:" + watchedQuery.queryId);
1361 });
1362 });
1363 };
1364 QueryManager.prototype.generateQueryId = function () {
1365 return String(this.idCounter++);
1366 };
1367 QueryManager.prototype.stopQueryInStore = function (queryId) {
1368 this.stopQueryInStoreNoBroadcast(queryId);
1369 this.broadcastQueries();
1370 };
1371 QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
1372 this.stopPollingQuery(queryId);
1373 this.queryStore.stopQuery(queryId);
1374 this.invalidate(queryId);
1375 };
1376 QueryManager.prototype.addQueryListener = function (queryId, listener) {
1377 this.setQuery(queryId, function (_a) {
1378 var listeners = _a.listeners;
1379 listeners.add(listener);
1380 return { invalidated: false };
1381 });
1382 };
1383 QueryManager.prototype.updateQueryWatch = function (queryId, document, options) {
1384 var _this = this;
1385 var cancel = this.getQuery(queryId).cancel;
1386 if (cancel)
1387 cancel();
1388 var previousResult = function () {
1389 var previousResult = null;
1390 var observableQuery = _this.getQuery(queryId).observableQuery;
1391 if (observableQuery) {
1392 var lastResult = observableQuery.getLastResult();
1393 if (lastResult) {
1394 previousResult = lastResult.data;
1395 }
1396 }
1397 return previousResult;
1398 };
1399 return this.dataStore.getCache().watch({
1400 query: document,
1401 variables: options.variables,
1402 optimistic: true,
1403 previousResult: previousResult,
1404 callback: function (newData) {
1405 _this.setQuery(queryId, function () { return ({ invalidated: true, newData: newData }); });
1406 },
1407 });
1408 };
1409 QueryManager.prototype.addObservableQuery = function (queryId, observableQuery) {
1410 this.setQuery(queryId, function () { return ({ observableQuery: observableQuery }); });
1411 };
1412 QueryManager.prototype.removeObservableQuery = function (queryId) {
1413 var cancel = this.getQuery(queryId).cancel;
1414 this.setQuery(queryId, function () { return ({ observableQuery: null }); });
1415 if (cancel)
1416 cancel();
1417 };
1418 QueryManager.prototype.clearStore = function () {
1419 this.fetchQueryRejectFns.forEach(function (reject) {
1420 reject(process.env.NODE_ENV === "production" ? new InvariantError(16) : new InvariantError('Store reset while query was in flight (not completed in link chain)'));
1421 });
1422 var resetIds = [];
1423 this.queries.forEach(function (_a, queryId) {
1424 var observableQuery = _a.observableQuery;
1425 if (observableQuery)
1426 resetIds.push(queryId);
1427 });
1428 this.queryStore.reset(resetIds);
1429 this.mutationStore.reset();
1430 return this.dataStore.reset();
1431 };
1432 QueryManager.prototype.resetStore = function () {
1433 var _this = this;
1434 return this.clearStore().then(function () {
1435 return _this.reFetchObservableQueries();
1436 });
1437 };
1438 QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
1439 var _this = this;
1440 if (includeStandby === void 0) { includeStandby = false; }
1441 var observableQueryPromises = [];
1442 this.queries.forEach(function (_a, queryId) {
1443 var observableQuery = _a.observableQuery;
1444 if (observableQuery) {
1445 var fetchPolicy = observableQuery.options.fetchPolicy;
1446 observableQuery.resetLastResults();
1447 if (fetchPolicy !== 'cache-only' &&
1448 (includeStandby || fetchPolicy !== 'standby')) {
1449 observableQueryPromises.push(observableQuery.refetch());
1450 }
1451 _this.setQuery(queryId, function () { return ({ newData: null }); });
1452 _this.invalidate(queryId);
1453 }
1454 });
1455 this.broadcastQueries();
1456 return Promise.all(observableQueryPromises);
1457 };
1458 QueryManager.prototype.observeQuery = function (queryId, options, observer) {
1459 this.addQueryListener(queryId, this.queryListenerForObserver(queryId, options, observer));
1460 return this.fetchQuery(queryId, options);
1461 };
1462 QueryManager.prototype.startQuery = function (queryId, options, listener) {
1463 process.env.NODE_ENV === "production" || invariant.warn("The QueryManager.startQuery method has been deprecated");
1464 this.addQueryListener(queryId, listener);
1465 this.fetchQuery(queryId, options)
1466 .catch(function () { return undefined; });
1467 return queryId;
1468 };
1469 QueryManager.prototype.startGraphQLSubscription = function (_a) {
1470 var _this = this;
1471 var query = _a.query, fetchPolicy = _a.fetchPolicy, variables = _a.variables;
1472 query = this.transform(query).document;
1473 variables = this.getVariables(query, variables);
1474 var makeObservable = function (variables) {
1475 return _this.getObservableFromLink(query, {}, variables, false).map(function (result) {
1476 if (!fetchPolicy || fetchPolicy !== 'no-cache') {
1477 _this.dataStore.markSubscriptionResult(result, query, variables);
1478 _this.broadcastQueries();
1479 }
1480 if (graphQLResultHasError(result)) {
1481 throw new ApolloError({
1482 graphQLErrors: result.errors,
1483 });
1484 }
1485 return result;
1486 });
1487 };
1488 if (this.transform(query).hasClientExports) {
1489 var observablePromise_1 = this.localState.addExportedVariables(query, variables).then(makeObservable);
1490 return new Observable(function (observer) {
1491 var sub = null;
1492 observablePromise_1.then(function (observable) { return sub = observable.subscribe(observer); }, observer.error);
1493 return function () { return sub && sub.unsubscribe(); };
1494 });
1495 }
1496 return makeObservable(variables);
1497 };
1498 QueryManager.prototype.stopQuery = function (queryId) {
1499 this.stopQueryNoBroadcast(queryId);
1500 this.broadcastQueries();
1501 };
1502 QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
1503 this.stopQueryInStoreNoBroadcast(queryId);
1504 this.removeQuery(queryId);
1505 };
1506 QueryManager.prototype.removeQuery = function (queryId) {
1507 this.fetchQueryRejectFns.delete("query:" + queryId);
1508 this.fetchQueryRejectFns.delete("fetchRequest:" + queryId);
1509 this.getQuery(queryId).subscriptions.forEach(function (x) { return x.unsubscribe(); });
1510 this.queries.delete(queryId);
1511 };
1512 QueryManager.prototype.getCurrentQueryResult = function (observableQuery, optimistic) {
1513 if (optimistic === void 0) { optimistic = true; }
1514 var _a = observableQuery.options, variables = _a.variables, query = _a.query, fetchPolicy = _a.fetchPolicy, returnPartialData = _a.returnPartialData;
1515 var lastResult = observableQuery.getLastResult();
1516 var newData = this.getQuery(observableQuery.queryId).newData;
1517 if (newData && newData.complete) {
1518 return { data: newData.result, partial: false };
1519 }
1520 if (fetchPolicy === 'no-cache' || fetchPolicy === 'network-only') {
1521 return { data: undefined, partial: false };
1522 }
1523 var _b = this.dataStore.getCache().diff({
1524 query: query,
1525 variables: variables,
1526 previousResult: lastResult ? lastResult.data : undefined,
1527 returnPartialData: true,
1528 optimistic: optimistic,
1529 }), result = _b.result, complete = _b.complete;
1530 return {
1531 data: (complete || returnPartialData) ? result : void 0,
1532 partial: !complete,
1533 };
1534 };
1535 QueryManager.prototype.getQueryWithPreviousResult = function (queryIdOrObservable) {
1536 var observableQuery;
1537 if (typeof queryIdOrObservable === 'string') {
1538 var foundObserveableQuery = this.getQuery(queryIdOrObservable).observableQuery;
1539 process.env.NODE_ENV === "production" ? invariant(foundObserveableQuery, 17) : invariant(foundObserveableQuery, "ObservableQuery with this id doesn't exist: " + queryIdOrObservable);
1540 observableQuery = foundObserveableQuery;
1541 }
1542 else {
1543 observableQuery = queryIdOrObservable;
1544 }
1545 var _a = observableQuery.options, variables = _a.variables, query = _a.query;
1546 return {
1547 previousResult: this.getCurrentQueryResult(observableQuery, false).data,
1548 variables: variables,
1549 document: query,
1550 };
1551 };
1552 QueryManager.prototype.broadcastQueries = function () {
1553 var _this = this;
1554 this.onBroadcast();
1555 this.queries.forEach(function (info, id) {
1556 if (info.invalidated) {
1557 info.listeners.forEach(function (listener) {
1558 if (listener) {
1559 listener(_this.queryStore.get(id), info.newData);
1560 }
1561 });
1562 }
1563 });
1564 };
1565 QueryManager.prototype.getLocalState = function () {
1566 return this.localState;
1567 };
1568 QueryManager.prototype.getObservableFromLink = function (query, context, variables, deduplication) {
1569 var _this = this;
1570 if (deduplication === void 0) { deduplication = this.queryDeduplication; }
1571 var observable;
1572 var serverQuery = this.transform(query).serverQuery;
1573 if (serverQuery) {
1574 var _a = this, inFlightLinkObservables_1 = _a.inFlightLinkObservables, link = _a.link;
1575 var operation = {
1576 query: serverQuery,
1577 variables: variables,
1578 operationName: getOperationName(serverQuery) || void 0,
1579 context: this.prepareContext(__assign(__assign({}, context), { forceFetch: !deduplication })),
1580 };
1581 context = operation.context;
1582 if (deduplication) {
1583 var byVariables_1 = inFlightLinkObservables_1.get(serverQuery) || new Map();
1584 inFlightLinkObservables_1.set(serverQuery, byVariables_1);
1585 var varJson_1 = JSON.stringify(variables);
1586 observable = byVariables_1.get(varJson_1);
1587 if (!observable) {
1588 byVariables_1.set(varJson_1, observable = multiplex(execute(link, operation)));
1589 var cleanup = function () {
1590 byVariables_1.delete(varJson_1);
1591 if (!byVariables_1.size)
1592 inFlightLinkObservables_1.delete(serverQuery);
1593 cleanupSub_1.unsubscribe();
1594 };
1595 var cleanupSub_1 = observable.subscribe({
1596 next: cleanup,
1597 error: cleanup,
1598 complete: cleanup,
1599 });
1600 }
1601 }
1602 else {
1603 observable = multiplex(execute(link, operation));
1604 }
1605 }
1606 else {
1607 observable = Observable.of({ data: {} });
1608 context = this.prepareContext(context);
1609 }
1610 var clientQuery = this.transform(query).clientQuery;
1611 if (clientQuery) {
1612 observable = asyncMap(observable, function (result) {
1613 return _this.localState.runResolvers({
1614 document: clientQuery,
1615 remoteResult: result,
1616 context: context,
1617 variables: variables,
1618 });
1619 });
1620 }
1621 return observable;
1622 };
1623 QueryManager.prototype.fetchRequest = function (_a) {
1624 var _this = this;
1625 var requestId = _a.requestId, queryId = _a.queryId, document = _a.document, options = _a.options, fetchMoreForQueryId = _a.fetchMoreForQueryId;
1626 var variables = options.variables, _b = options.errorPolicy, errorPolicy = _b === void 0 ? 'none' : _b, fetchPolicy = options.fetchPolicy;
1627 var resultFromStore;
1628 var errorsFromStore;
1629 return new Promise(function (resolve, reject) {
1630 var observable = _this.getObservableFromLink(document, options.context, variables);
1631 var fqrfId = "fetchRequest:" + queryId;
1632 _this.fetchQueryRejectFns.set(fqrfId, reject);
1633 var cleanup = function () {
1634 _this.fetchQueryRejectFns.delete(fqrfId);
1635 _this.setQuery(queryId, function (_a) {
1636 var subscriptions = _a.subscriptions;
1637 subscriptions.delete(subscription);
1638 });
1639 };
1640 var subscription = observable.map(function (result) {
1641 if (requestId >= _this.getQuery(queryId).lastRequestId) {
1642 _this.markQueryResult(queryId, result, options, fetchMoreForQueryId);
1643 _this.queryStore.markQueryResult(queryId, result, fetchMoreForQueryId);
1644 _this.invalidate(queryId);
1645 _this.invalidate(fetchMoreForQueryId);
1646 _this.broadcastQueries();
1647 }
1648 if (errorPolicy === 'none' && isNonEmptyArray(result.errors)) {
1649 return reject(new ApolloError({
1650 graphQLErrors: result.errors,
1651 }));
1652 }
1653 if (errorPolicy === 'all') {
1654 errorsFromStore = result.errors;
1655 }
1656 if (fetchMoreForQueryId || fetchPolicy === 'no-cache') {
1657 resultFromStore = result.data;
1658 }
1659 else {
1660 var _a = _this.dataStore.getCache().diff({
1661 variables: variables,
1662 query: document,
1663 optimistic: false,
1664 returnPartialData: true,
1665 }), result_1 = _a.result, complete = _a.complete;
1666 if (complete || options.returnPartialData) {
1667 resultFromStore = result_1;
1668 }
1669 }
1670 }).subscribe({
1671 error: function (error) {
1672 cleanup();
1673 reject(error);
1674 },
1675 complete: function () {
1676 cleanup();
1677 resolve({
1678 data: resultFromStore,
1679 errors: errorsFromStore,
1680 loading: false,
1681 networkStatus: NetworkStatus.ready,
1682 stale: false,
1683 });
1684 },
1685 });
1686 _this.setQuery(queryId, function (_a) {
1687 var subscriptions = _a.subscriptions;
1688 subscriptions.add(subscription);
1689 });
1690 });
1691 };
1692 QueryManager.prototype.getQuery = function (queryId) {
1693 return (this.queries.get(queryId) || {
1694 listeners: new Set(),
1695 invalidated: false,
1696 document: null,
1697 newData: null,
1698 lastRequestId: 1,
1699 observableQuery: null,
1700 subscriptions: new Set(),
1701 });
1702 };
1703 QueryManager.prototype.setQuery = function (queryId, updater) {
1704 var prev = this.getQuery(queryId);
1705 var newInfo = __assign(__assign({}, prev), updater(prev));
1706 this.queries.set(queryId, newInfo);
1707 };
1708 QueryManager.prototype.invalidate = function (queryId, invalidated) {
1709 if (invalidated === void 0) { invalidated = true; }
1710 if (queryId) {
1711 this.setQuery(queryId, function () { return ({ invalidated: invalidated }); });
1712 }
1713 };
1714 QueryManager.prototype.prepareContext = function (context) {
1715 if (context === void 0) { context = {}; }
1716 var newContext = this.localState.prepareContext(context);
1717 return __assign(__assign({}, newContext), { clientAwareness: this.clientAwareness });
1718 };
1719 QueryManager.prototype.checkInFlight = function (queryId) {
1720 var query = this.queryStore.get(queryId);
1721 return (query &&
1722 query.networkStatus !== NetworkStatus.ready &&
1723 query.networkStatus !== NetworkStatus.error);
1724 };
1725 QueryManager.prototype.startPollingQuery = function (options, queryId, listener) {
1726 var _this = this;
1727 var pollInterval = options.pollInterval;
1728 process.env.NODE_ENV === "production" ? invariant(pollInterval, 18) : invariant(pollInterval, 'Attempted to start a polling query without a polling interval.');
1729 if (!this.ssrMode) {
1730 var info = this.pollingInfoByQueryId.get(queryId);
1731 if (!info) {
1732 this.pollingInfoByQueryId.set(queryId, (info = {}));
1733 }
1734 info.interval = pollInterval;
1735 info.options = __assign(__assign({}, options), { fetchPolicy: 'network-only' });
1736 var maybeFetch_1 = function () {
1737 var info = _this.pollingInfoByQueryId.get(queryId);
1738 if (info) {
1739 if (_this.checkInFlight(queryId)) {
1740 poll_1();
1741 }
1742 else {
1743 _this.fetchQuery(queryId, info.options, FetchType.poll).then(poll_1, poll_1);
1744 }
1745 }
1746 };
1747 var poll_1 = function () {
1748 var info = _this.pollingInfoByQueryId.get(queryId);
1749 if (info) {
1750 clearTimeout(info.timeout);
1751 info.timeout = setTimeout(maybeFetch_1, info.interval);
1752 }
1753 };
1754 if (listener) {
1755 this.addQueryListener(queryId, listener);
1756 }
1757 poll_1();
1758 }
1759 return queryId;
1760 };
1761 QueryManager.prototype.stopPollingQuery = function (queryId) {
1762 this.pollingInfoByQueryId.delete(queryId);
1763 };
1764 return QueryManager;
1765}());
1766
1767var DataStore = (function () {
1768 function DataStore(initialCache) {
1769 this.cache = initialCache;
1770 }
1771 DataStore.prototype.getCache = function () {
1772 return this.cache;
1773 };
1774 DataStore.prototype.markQueryResult = function (result, document, variables, fetchMoreForQueryId, ignoreErrors) {
1775 if (ignoreErrors === void 0) { ignoreErrors = false; }
1776 var writeWithErrors = !graphQLResultHasError(result);
1777 if (ignoreErrors && graphQLResultHasError(result) && result.data) {
1778 writeWithErrors = true;
1779 }
1780 if (!fetchMoreForQueryId && writeWithErrors) {
1781 this.cache.write({
1782 result: result.data,
1783 dataId: 'ROOT_QUERY',
1784 query: document,
1785 variables: variables,
1786 });
1787 }
1788 };
1789 DataStore.prototype.markSubscriptionResult = function (result, document, variables) {
1790 if (!graphQLResultHasError(result)) {
1791 this.cache.write({
1792 result: result.data,
1793 dataId: 'ROOT_SUBSCRIPTION',
1794 query: document,
1795 variables: variables,
1796 });
1797 }
1798 };
1799 DataStore.prototype.markMutationInit = function (mutation) {
1800 var _this = this;
1801 if (mutation.optimisticResponse) {
1802 var optimistic_1;
1803 if (typeof mutation.optimisticResponse === 'function') {
1804 optimistic_1 = mutation.optimisticResponse(mutation.variables);
1805 }
1806 else {
1807 optimistic_1 = mutation.optimisticResponse;
1808 }
1809 this.cache.recordOptimisticTransaction(function (c) {
1810 var orig = _this.cache;
1811 _this.cache = c;
1812 try {
1813 _this.markMutationResult({
1814 mutationId: mutation.mutationId,
1815 result: { data: optimistic_1 },
1816 document: mutation.document,
1817 variables: mutation.variables,
1818 updateQueries: mutation.updateQueries,
1819 update: mutation.update,
1820 });
1821 }
1822 finally {
1823 _this.cache = orig;
1824 }
1825 }, mutation.mutationId);
1826 }
1827 };
1828 DataStore.prototype.markMutationResult = function (mutation) {
1829 var _this = this;
1830 if (!graphQLResultHasError(mutation.result)) {
1831 var cacheWrites_1 = [{
1832 result: mutation.result.data,
1833 dataId: 'ROOT_MUTATION',
1834 query: mutation.document,
1835 variables: mutation.variables,
1836 }];
1837 var updateQueries_1 = mutation.updateQueries;
1838 if (updateQueries_1) {
1839 Object.keys(updateQueries_1).forEach(function (id) {
1840 var _a = updateQueries_1[id], query = _a.query, updater = _a.updater;
1841 var _b = _this.cache.diff({
1842 query: query.document,
1843 variables: query.variables,
1844 returnPartialData: true,
1845 optimistic: false,
1846 }), currentQueryResult = _b.result, complete = _b.complete;
1847 if (complete) {
1848 var nextQueryResult = tryFunctionOrLogError(function () {
1849 return updater(currentQueryResult, {
1850 mutationResult: mutation.result,
1851 queryName: getOperationName(query.document) || undefined,
1852 queryVariables: query.variables,
1853 });
1854 });
1855 if (nextQueryResult) {
1856 cacheWrites_1.push({
1857 result: nextQueryResult,
1858 dataId: 'ROOT_QUERY',
1859 query: query.document,
1860 variables: query.variables,
1861 });
1862 }
1863 }
1864 });
1865 }
1866 this.cache.performTransaction(function (c) {
1867 cacheWrites_1.forEach(function (write) { return c.write(write); });
1868 var update = mutation.update;
1869 if (update) {
1870 tryFunctionOrLogError(function () { return update(c, mutation.result); });
1871 }
1872 });
1873 }
1874 };
1875 DataStore.prototype.markMutationComplete = function (_a) {
1876 var mutationId = _a.mutationId, optimisticResponse = _a.optimisticResponse;
1877 if (optimisticResponse) {
1878 this.cache.removeOptimistic(mutationId);
1879 }
1880 };
1881 DataStore.prototype.markUpdateQueryResult = function (document, variables, newResult) {
1882 this.cache.write({
1883 result: newResult,
1884 dataId: 'ROOT_QUERY',
1885 variables: variables,
1886 query: document,
1887 });
1888 };
1889 DataStore.prototype.reset = function () {
1890 return this.cache.reset();
1891 };
1892 return DataStore;
1893}());
1894
1895var version = "2.6.8";
1896
1897var hasSuggestedDevtools = false;
1898var ApolloClient = (function () {
1899 function ApolloClient(options) {
1900 var _this = this;
1901 this.defaultOptions = {};
1902 this.resetStoreCallbacks = [];
1903 this.clearStoreCallbacks = [];
1904 var cache = options.cache, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, connectToDevTools = options.connectToDevTools, _c = options.queryDeduplication, queryDeduplication = _c === void 0 ? true : _c, defaultOptions = options.defaultOptions, _d = options.assumeImmutableResults, assumeImmutableResults = _d === void 0 ? false : _d, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version;
1905 var link = options.link;
1906 if (!link && resolvers) {
1907 link = ApolloLink.empty();
1908 }
1909 if (!link || !cache) {
1910 throw process.env.NODE_ENV === "production" ? new InvariantError(1) : new InvariantError("In order to initialize Apollo Client, you must specify 'link' and 'cache' properties in the options object.\n" +
1911 "These options are part of the upgrade requirements when migrating from Apollo Client 1.x to Apollo Client 2.x.\n" +
1912 "For more information, please visit: https://www.apollographql.com/docs/tutorial/client.html#apollo-client-setup");
1913 }
1914 this.link = link;
1915 this.cache = cache;
1916 this.store = new DataStore(cache);
1917 this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
1918 this.queryDeduplication = queryDeduplication;
1919 this.defaultOptions = defaultOptions || {};
1920 this.typeDefs = typeDefs;
1921 if (ssrForceFetchDelay) {
1922 setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
1923 }
1924 this.watchQuery = this.watchQuery.bind(this);
1925 this.query = this.query.bind(this);
1926 this.mutate = this.mutate.bind(this);
1927 this.resetStore = this.resetStore.bind(this);
1928 this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
1929 var defaultConnectToDevTools = process.env.NODE_ENV !== 'production' &&
1930 typeof window !== 'undefined' &&
1931 !window.__APOLLO_CLIENT__;
1932 if (typeof connectToDevTools === 'undefined'
1933 ? defaultConnectToDevTools
1934 : connectToDevTools && typeof window !== 'undefined') {
1935 window.__APOLLO_CLIENT__ = this;
1936 }
1937 if (!hasSuggestedDevtools && process.env.NODE_ENV !== 'production') {
1938 hasSuggestedDevtools = true;
1939 if (typeof window !== 'undefined' &&
1940 window.document &&
1941 window.top === window.self) {
1942 if (typeof window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
1943 if (window.navigator &&
1944 window.navigator.userAgent &&
1945 window.navigator.userAgent.indexOf('Chrome') > -1) {
1946 console.debug('Download the Apollo DevTools ' +
1947 'for a better development experience: ' +
1948 'https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm');
1949 }
1950 }
1951 }
1952 }
1953 this.version = version;
1954 this.localState = new LocalState({
1955 cache: cache,
1956 client: this,
1957 resolvers: resolvers,
1958 fragmentMatcher: fragmentMatcher,
1959 });
1960 this.queryManager = new QueryManager({
1961 link: this.link,
1962 store: this.store,
1963 queryDeduplication: queryDeduplication,
1964 ssrMode: ssrMode,
1965 clientAwareness: {
1966 name: clientAwarenessName,
1967 version: clientAwarenessVersion,
1968 },
1969 localState: this.localState,
1970 assumeImmutableResults: assumeImmutableResults,
1971 onBroadcast: function () {
1972 if (_this.devToolsHookCb) {
1973 _this.devToolsHookCb({
1974 action: {},
1975 state: {
1976 queries: _this.queryManager.queryStore.getStore(),
1977 mutations: _this.queryManager.mutationStore.getStore(),
1978 },
1979 dataWithOptimisticResults: _this.cache.extract(true),
1980 });
1981 }
1982 },
1983 });
1984 }
1985 ApolloClient.prototype.stop = function () {
1986 this.queryManager.stop();
1987 };
1988 ApolloClient.prototype.watchQuery = function (options) {
1989 if (this.defaultOptions.watchQuery) {
1990 options = __assign(__assign({}, this.defaultOptions.watchQuery), options);
1991 }
1992 if (this.disableNetworkFetches &&
1993 (options.fetchPolicy === 'network-only' ||
1994 options.fetchPolicy === 'cache-and-network')) {
1995 options = __assign(__assign({}, options), { fetchPolicy: 'cache-first' });
1996 }
1997 return this.queryManager.watchQuery(options);
1998 };
1999 ApolloClient.prototype.query = function (options) {
2000 if (this.defaultOptions.query) {
2001 options = __assign(__assign({}, this.defaultOptions.query), options);
2002 }
2003 process.env.NODE_ENV === "production" ? invariant(options.fetchPolicy !== 'cache-and-network', 2) : invariant(options.fetchPolicy !== 'cache-and-network', 'The cache-and-network fetchPolicy does not work with client.query, because ' +
2004 'client.query can only return a single result. Please use client.watchQuery ' +
2005 'to receive multiple results from the cache and the network, or consider ' +
2006 'using a different fetchPolicy, such as cache-first or network-only.');
2007 if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
2008 options = __assign(__assign({}, options), { fetchPolicy: 'cache-first' });
2009 }
2010 return this.queryManager.query(options);
2011 };
2012 ApolloClient.prototype.mutate = function (options) {
2013 if (this.defaultOptions.mutate) {
2014 options = __assign(__assign({}, this.defaultOptions.mutate), options);
2015 }
2016 return this.queryManager.mutate(options);
2017 };
2018 ApolloClient.prototype.subscribe = function (options) {
2019 return this.queryManager.startGraphQLSubscription(options);
2020 };
2021 ApolloClient.prototype.readQuery = function (options, optimistic) {
2022 if (optimistic === void 0) { optimistic = false; }
2023 return this.cache.readQuery(options, optimistic);
2024 };
2025 ApolloClient.prototype.readFragment = function (options, optimistic) {
2026 if (optimistic === void 0) { optimistic = false; }
2027 return this.cache.readFragment(options, optimistic);
2028 };
2029 ApolloClient.prototype.writeQuery = function (options) {
2030 var result = this.cache.writeQuery(options);
2031 this.queryManager.broadcastQueries();
2032 return result;
2033 };
2034 ApolloClient.prototype.writeFragment = function (options) {
2035 var result = this.cache.writeFragment(options);
2036 this.queryManager.broadcastQueries();
2037 return result;
2038 };
2039 ApolloClient.prototype.writeData = function (options) {
2040 var result = this.cache.writeData(options);
2041 this.queryManager.broadcastQueries();
2042 return result;
2043 };
2044 ApolloClient.prototype.__actionHookForDevTools = function (cb) {
2045 this.devToolsHookCb = cb;
2046 };
2047 ApolloClient.prototype.__requestRaw = function (payload) {
2048 return execute(this.link, payload);
2049 };
2050 ApolloClient.prototype.initQueryManager = function () {
2051 process.env.NODE_ENV === "production" || invariant.warn('Calling the initQueryManager method is no longer necessary, ' +
2052 'and it will be removed from ApolloClient in version 3.0.');
2053 return this.queryManager;
2054 };
2055 ApolloClient.prototype.resetStore = function () {
2056 var _this = this;
2057 return Promise.resolve()
2058 .then(function () { return _this.queryManager.clearStore(); })
2059 .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
2060 .then(function () { return _this.reFetchObservableQueries(); });
2061 };
2062 ApolloClient.prototype.clearStore = function () {
2063 var _this = this;
2064 return Promise.resolve()
2065 .then(function () { return _this.queryManager.clearStore(); })
2066 .then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
2067 };
2068 ApolloClient.prototype.onResetStore = function (cb) {
2069 var _this = this;
2070 this.resetStoreCallbacks.push(cb);
2071 return function () {
2072 _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
2073 };
2074 };
2075 ApolloClient.prototype.onClearStore = function (cb) {
2076 var _this = this;
2077 this.clearStoreCallbacks.push(cb);
2078 return function () {
2079 _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
2080 };
2081 };
2082 ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
2083 return this.queryManager.reFetchObservableQueries(includeStandby);
2084 };
2085 ApolloClient.prototype.extract = function (optimistic) {
2086 return this.cache.extract(optimistic);
2087 };
2088 ApolloClient.prototype.restore = function (serializedState) {
2089 return this.cache.restore(serializedState);
2090 };
2091 ApolloClient.prototype.addResolvers = function (resolvers) {
2092 this.localState.addResolvers(resolvers);
2093 };
2094 ApolloClient.prototype.setResolvers = function (resolvers) {
2095 this.localState.setResolvers(resolvers);
2096 };
2097 ApolloClient.prototype.getResolvers = function () {
2098 return this.localState.getResolvers();
2099 };
2100 ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
2101 this.localState.setFragmentMatcher(fragmentMatcher);
2102 };
2103 return ApolloClient;
2104}());
2105
2106export default ApolloClient;
2107export { ApolloClient, ApolloError, FetchType, NetworkStatus, ObservableQuery, isApolloError };
2108//# sourceMappingURL=bundle.esm.js.map