UNPKG

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