UNPKG

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