UNPKG

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