@apollo/client
Version:
A fully-featured caching GraphQL client.
2,353 lines • 110 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var globals = require('../utilities/globals');
var tslib = require('tslib');
var core = require('../link/core');
var http = require('../link/http');
var equality = require('@wry/equality');
var cache = require('../cache');
var utilities = require('../utilities');
var errors = require('../errors');
var graphql = require('graphql');
var utils = require('../link/utils');
var tsInvariant = require('ts-invariant');
var graphqlTag = require('graphql-tag');
var version = '3.7.10';
function isNonEmptyArray(value) {
return Array.isArray(value) && value.length > 0;
}
function isNonNullObject(obj) {
return obj !== null && typeof obj === 'object';
}
var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
var defaultReconciler = function (target, source, property) {
return this.merge(target[property], source[property]);
};
var DeepMerger = (function () {
function DeepMerger(reconciler) {
if (reconciler === void 0) { reconciler = defaultReconciler; }
this.reconciler = reconciler;
this.isObject = isNonNullObject;
this.pastCopies = new Set();
}
DeepMerger.prototype.merge = function (target, source) {
var _this = this;
var context = [];
for (var _i = 2; _i < arguments.length; _i++) {
context[_i - 2] = arguments[_i];
}
if (isNonNullObject(source) && isNonNullObject(target)) {
Object.keys(source).forEach(function (sourceKey) {
if (hasOwnProperty$2.call(target, sourceKey)) {
var targetValue = target[sourceKey];
if (source[sourceKey] !== targetValue) {
var result = _this.reconciler.apply(_this, tslib.__spreadArray([target, source, sourceKey], context, false));
if (result !== targetValue) {
target = _this.shallowCopyForMerge(target);
target[sourceKey] = result;
}
}
}
else {
target = _this.shallowCopyForMerge(target);
target[sourceKey] = source[sourceKey];
}
});
return target;
}
return source;
};
DeepMerger.prototype.shallowCopyForMerge = function (value) {
if (isNonNullObject(value)) {
if (!this.pastCopies.has(value)) {
if (Array.isArray(value)) {
value = value.slice(0);
}
else {
value = tslib.__assign({ __proto__: Object.getPrototypeOf(value) }, value);
}
this.pastCopies.add(value);
}
}
return value;
};
return DeepMerger;
}());
function isExecutionPatchIncrementalResult(value) {
return "incremental" in value;
}
function isExecutionPatchInitialResult(value) {
return "hasNext" in value && "data" in value;
}
function isExecutionPatchResult(value) {
return (isExecutionPatchIncrementalResult(value) ||
isExecutionPatchInitialResult(value));
}
function mergeIncrementalData(prevResult, result) {
var mergedData = prevResult;
var merger = new DeepMerger();
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
result.incremental.forEach(function (_a) {
var data = _a.data, path = _a.path;
for (var i = path.length - 1; i >= 0; --i) {
var key = path[i];
var isNumericKey = !isNaN(+key);
var parent_1 = isNumericKey ? [] : {};
parent_1[key] = data;
data = parent_1;
}
mergedData = merger.merge(mergedData, data);
});
}
return mergedData;
}
exports.NetworkStatus = void 0;
(function (NetworkStatus) {
NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
NetworkStatus[NetworkStatus["error"] = 8] = "error";
})(exports.NetworkStatus || (exports.NetworkStatus = {}));
function isNetworkRequestInFlight(networkStatus) {
return networkStatus ? networkStatus < 7 : false;
}
var assign = Object.assign, hasOwnProperty$1 = Object.hasOwnProperty;
var ObservableQuery = (function (_super) {
tslib.__extends(ObservableQuery, _super);
function ObservableQuery(_a) {
var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;
var _this = _super.call(this, function (observer) {
try {
var subObserver = observer._subscription._observer;
if (subObserver && !subObserver.error) {
subObserver.error = defaultSubscriptionObserverErrorCallback;
}
}
catch (_a) { }
var first = !_this.observers.size;
_this.observers.add(observer);
var last = _this.last;
if (last && last.error) {
observer.error && observer.error(last.error);
}
else if (last && last.result) {
observer.next && observer.next(last.result);
}
if (first) {
_this.reobserve().catch(function () { });
}
return function () {
if (_this.observers.delete(observer) && !_this.observers.size) {
_this.tearDownQuery();
}
};
}) || this;
_this.observers = new Set();
_this.subscriptions = new Set();
_this.queryInfo = queryInfo;
_this.queryManager = queryManager;
_this.isTornDown = false;
var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? "cache-first" : _d;
var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e, _f = options.initialFetchPolicy, initialFetchPolicy = _f === void 0 ? (fetchPolicy === "standby" ? defaultFetchPolicy : fetchPolicy) : _f;
_this.options = tslib.__assign(tslib.__assign({}, options), { initialFetchPolicy: initialFetchPolicy, fetchPolicy: fetchPolicy });
_this.queryId = queryInfo.queryId || queryManager.generateQueryId();
var opDef = utilities.getOperationDefinition(_this.query);
_this.queryName = opDef && opDef.name && opDef.name.value;
return _this;
}
Object.defineProperty(ObservableQuery.prototype, "query", {
get: function () {
return this.queryManager.transform(this.options.query).document;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ObservableQuery.prototype, "variables", {
get: function () {
return this.options.variables;
},
enumerable: false,
configurable: true
});
ObservableQuery.prototype.result = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var observer = {
next: function (result) {
resolve(result);
_this.observers.delete(observer);
if (!_this.observers.size) {
_this.queryManager.removeQuery(_this.queryId);
}
setTimeout(function () {
subscription.unsubscribe();
}, 0);
},
error: reject,
};
var subscription = _this.subscribe(observer);
});
};
ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {
if (saveAsLastResult === void 0) { saveAsLastResult = true; }
var lastResult = this.getLastResult(true);
var networkStatus = this.queryInfo.networkStatus ||
(lastResult && lastResult.networkStatus) ||
exports.NetworkStatus.ready;
var result = tslib.__assign(tslib.__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });
var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a;
if (fetchPolicy === 'network-only' ||
fetchPolicy === 'no-cache' ||
fetchPolicy === 'standby' ||
this.queryManager.transform(this.options.query).hasForcedResolvers) ;
else {
var diff = this.queryInfo.getDiff();
if (diff.complete || this.options.returnPartialData) {
result.data = diff.result;
}
if (equality.equal(result.data, {})) {
result.data = void 0;
}
if (diff.complete) {
delete result.partial;
if (diff.complete &&
result.networkStatus === exports.NetworkStatus.loading &&
(fetchPolicy === 'cache-first' ||
fetchPolicy === 'cache-only')) {
result.networkStatus = exports.NetworkStatus.ready;
result.loading = false;
}
}
else {
result.partial = true;
}
if (__DEV__ &&
!diff.complete &&
!this.options.partialRefetch &&
!result.loading &&
!result.data &&
!result.error) {
logMissingFieldErrors(diff.missing);
}
}
if (saveAsLastResult) {
this.updateLastResult(result);
}
return result;
};
ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {
return (!this.last ||
!equality.equal(this.last.result, newResult) ||
(variables && !equality.equal(this.last.variables, variables)));
};
ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {
var last = this.last;
if (last &&
last[key] &&
(!variablesMustMatch || equality.equal(last.variables, this.variables))) {
return last[key];
}
};
ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {
return this.getLast("result", variablesMustMatch);
};
ObservableQuery.prototype.getLastError = function (variablesMustMatch) {
return this.getLast("error", variablesMustMatch);
};
ObservableQuery.prototype.resetLastResults = function () {
delete this.last;
this.isTornDown = false;
};
ObservableQuery.prototype.resetQueryStoreErrors = function () {
this.queryManager.resetErrors(this.queryId);
};
ObservableQuery.prototype.refetch = function (variables) {
var _a;
var reobserveOptions = {
pollInterval: 0,
};
var fetchPolicy = this.options.fetchPolicy;
if (fetchPolicy === 'cache-and-network') {
reobserveOptions.fetchPolicy = fetchPolicy;
}
else if (fetchPolicy === 'no-cache') {
reobserveOptions.fetchPolicy = 'no-cache';
}
else {
reobserveOptions.fetchPolicy = 'network-only';
}
if (__DEV__ && variables && hasOwnProperty$1.call(variables, "variables")) {
var queryDef = utilities.getQueryDefinition(this.query);
var vars = queryDef.variableDefinitions;
if (!vars || !vars.some(function (v) { return v.variable.name.value === "variables"; })) {
__DEV__ && globals.invariant.warn("Called refetch(".concat(JSON.stringify(variables), ") for query ").concat(((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || JSON.stringify(queryDef), ", which does not declare a $variables variable.\nDid you mean to call refetch(variables) instead of refetch({ variables })?"));
}
}
if (variables && !equality.equal(this.options.variables, variables)) {
reobserveOptions.variables = this.options.variables = tslib.__assign(tslib.__assign({}, this.options.variables), variables);
}
this.queryInfo.resetLastWrite();
return this.reobserve(reobserveOptions, exports.NetworkStatus.refetch);
};
ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
var _this = this;
var combinedOptions = tslib.__assign(tslib.__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, this.options), { query: this.query }), fetchMoreOptions), { variables: tslib.__assign(tslib.__assign({}, this.options.variables), fetchMoreOptions.variables) }))), { fetchPolicy: "no-cache" });
var qid = this.queryManager.generateQueryId();
var queryInfo = this.queryInfo;
var originalNetworkStatus = queryInfo.networkStatus;
queryInfo.networkStatus = exports.NetworkStatus.fetchMore;
if (combinedOptions.notifyOnNetworkStatusChange) {
this.observe();
}
var updatedQuerySet = new Set();
return this.queryManager.fetchQuery(qid, combinedOptions, exports.NetworkStatus.fetchMore).then(function (fetchMoreResult) {
_this.queryManager.removeQuery(qid);
if (queryInfo.networkStatus === exports.NetworkStatus.fetchMore) {
queryInfo.networkStatus = originalNetworkStatus;
}
_this.queryManager.cache.batch({
update: function (cache) {
var updateQuery = fetchMoreOptions.updateQuery;
if (updateQuery) {
cache.updateQuery({
query: _this.query,
variables: _this.variables,
returnPartialData: true,
optimistic: false,
}, function (previous) { return updateQuery(previous, {
fetchMoreResult: fetchMoreResult.data,
variables: combinedOptions.variables,
}); });
}
else {
cache.writeQuery({
query: combinedOptions.query,
variables: combinedOptions.variables,
data: fetchMoreResult.data,
});
}
},
onWatchUpdated: function (watch) {
updatedQuerySet.add(watch.query);
},
});
return fetchMoreResult;
}).finally(function () {
if (!updatedQuerySet.has(_this.query)) {
reobserveCacheFirst(_this);
}
});
};
ObservableQuery.prototype.subscribeToMore = function (options) {
var _this = this;
var subscription = this.queryManager
.startGraphQLSubscription({
query: options.document,
variables: options.variables,
context: options.context,
})
.subscribe({
next: function (subscriptionData) {
var updateQuery = options.updateQuery;
if (updateQuery) {
_this.updateQuery(function (previous, _a) {
var variables = _a.variables;
return updateQuery(previous, {
subscriptionData: subscriptionData,
variables: variables,
});
});
}
},
error: function (err) {
if (options.onError) {
options.onError(err);
return;
}
__DEV__ && globals.invariant.error('Unhandled GraphQL subscription error', err);
},
});
this.subscriptions.add(subscription);
return function () {
if (_this.subscriptions.delete(subscription)) {
subscription.unsubscribe();
}
};
};
ObservableQuery.prototype.setOptions = function (newOptions) {
return this.reobserve(newOptions);
};
ObservableQuery.prototype.setVariables = function (variables) {
if (equality.equal(this.variables, variables)) {
return this.observers.size
? this.result()
: Promise.resolve();
}
this.options.variables = variables;
if (!this.observers.size) {
return Promise.resolve();
}
return this.reobserve({
fetchPolicy: this.options.initialFetchPolicy,
variables: variables,
}, exports.NetworkStatus.setVariables);
};
ObservableQuery.prototype.updateQuery = function (mapFn) {
var queryManager = this.queryManager;
var result = queryManager.cache.diff({
query: this.options.query,
variables: this.variables,
returnPartialData: true,
optimistic: false,
}).result;
var newResult = mapFn(result, {
variables: this.variables,
});
if (newResult) {
queryManager.cache.writeQuery({
query: this.options.query,
data: newResult,
variables: this.variables,
});
queryManager.broadcastQueries();
}
};
ObservableQuery.prototype.startPolling = function (pollInterval) {
this.options.pollInterval = pollInterval;
this.updatePolling();
};
ObservableQuery.prototype.stopPolling = function () {
this.options.pollInterval = 0;
this.updatePolling();
};
ObservableQuery.prototype.applyNextFetchPolicy = function (reason, options) {
if (options.nextFetchPolicy) {
var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;
if (fetchPolicy === "standby") ;
else if (typeof options.nextFetchPolicy === "function") {
options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {
reason: reason,
options: options,
observable: this,
initialFetchPolicy: initialFetchPolicy,
});
}
else if (reason === "variables-changed") {
options.fetchPolicy = initialFetchPolicy;
}
else {
options.fetchPolicy = options.nextFetchPolicy;
}
}
return options.fetchPolicy;
};
ObservableQuery.prototype.fetch = function (options, newNetworkStatus) {
this.queryManager.setObservableQuery(this);
return this.queryManager.fetchQueryObservable(this.queryId, options, newNetworkStatus);
};
ObservableQuery.prototype.updatePolling = function () {
var _this = this;
if (this.queryManager.ssrMode) {
return;
}
var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;
if (!pollInterval) {
if (pollingInfo) {
clearTimeout(pollingInfo.timeout);
delete this.pollingInfo;
}
return;
}
if (pollingInfo &&
pollingInfo.interval === pollInterval) {
return;
}
__DEV__ ? globals.invariant(pollInterval, 'Attempted to start a polling query without a polling interval.') : globals.invariant(pollInterval, 13);
var info = pollingInfo || (this.pollingInfo = {});
info.interval = pollInterval;
var maybeFetch = function () {
if (_this.pollingInfo) {
if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus)) {
_this.reobserve({
fetchPolicy: _this.options.initialFetchPolicy === 'no-cache' ? 'no-cache' : 'network-only',
}, exports.NetworkStatus.poll).then(poll, poll);
}
else {
poll();
}
}
};
var poll = function () {
var info = _this.pollingInfo;
if (info) {
clearTimeout(info.timeout);
info.timeout = setTimeout(maybeFetch, info.interval);
}
};
poll();
};
ObservableQuery.prototype.updateLastResult = function (newResult, variables) {
if (variables === void 0) { variables = this.variables; }
this.last = tslib.__assign(tslib.__assign({}, this.last), { result: this.queryManager.assumeImmutableResults
? newResult
: utilities.cloneDeep(newResult), variables: variables });
if (!utilities.isNonEmptyArray(newResult.errors)) {
delete this.last.error;
}
return this.last;
};
ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {
var _this = this;
this.isTornDown = false;
var useDisposableConcast = newNetworkStatus === exports.NetworkStatus.refetch ||
newNetworkStatus === exports.NetworkStatus.fetchMore ||
newNetworkStatus === exports.NetworkStatus.poll;
var oldVariables = this.options.variables;
var oldFetchPolicy = this.options.fetchPolicy;
var mergedOptions = utilities.compact(this.options, newOptions || {});
var options = useDisposableConcast
? mergedOptions
: assign(this.options, mergedOptions);
if (!useDisposableConcast) {
this.updatePolling();
if (newOptions &&
newOptions.variables &&
!equality.equal(newOptions.variables, oldVariables) &&
options.fetchPolicy !== "standby" &&
options.fetchPolicy === oldFetchPolicy) {
this.applyNextFetchPolicy("variables-changed", options);
if (newNetworkStatus === void 0) {
newNetworkStatus = exports.NetworkStatus.setVariables;
}
}
}
var variables = options.variables && tslib.__assign({}, options.variables);
var concast = this.fetch(options, newNetworkStatus);
var observer = {
next: function (result) {
_this.reportResult(result, variables);
},
error: function (error) {
_this.reportError(error, variables);
},
};
if (!useDisposableConcast) {
if (this.concast && this.observer) {
this.concast.removeObserver(this.observer);
}
this.concast = concast;
this.observer = observer;
}
concast.addObserver(observer);
return concast.promise;
};
ObservableQuery.prototype.observe = function () {
this.reportResult(this.getCurrentResult(false), this.variables);
};
ObservableQuery.prototype.reportResult = function (result, variables) {
var lastError = this.getLastError();
if (lastError || this.isDifferentFromLastResult(result, variables)) {
if (lastError || !result.partial || this.options.returnPartialData) {
this.updateLastResult(result, variables);
}
utilities.iterateObserversSafely(this.observers, 'next', result);
}
};
ObservableQuery.prototype.reportError = function (error, variables) {
var errorResult = tslib.__assign(tslib.__assign({}, this.getLastResult()), { error: error, errors: error.graphQLErrors, networkStatus: exports.NetworkStatus.error, loading: false });
this.updateLastResult(errorResult, variables);
utilities.iterateObserversSafely(this.observers, 'error', this.last.error = error);
};
ObservableQuery.prototype.hasObservers = function () {
return this.observers.size > 0;
};
ObservableQuery.prototype.tearDownQuery = function () {
if (this.isTornDown)
return;
if (this.concast && this.observer) {
this.concast.removeObserver(this.observer);
delete this.concast;
delete this.observer;
}
this.stopPolling();
this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
this.subscriptions.clear();
this.queryManager.stopQuery(this.queryId);
this.observers.clear();
this.isTornDown = true;
};
return ObservableQuery;
}(utilities.Observable));
utilities.fixObservableSubclass(ObservableQuery);
function reobserveCacheFirst(obsQuery) {
var _a = obsQuery.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;
if (fetchPolicy === "cache-and-network" ||
fetchPolicy === "network-only") {
return obsQuery.reobserve({
fetchPolicy: "cache-first",
nextFetchPolicy: function () {
this.nextFetchPolicy = nextFetchPolicy;
if (typeof nextFetchPolicy === "function") {
return nextFetchPolicy.apply(this, arguments);
}
return fetchPolicy;
},
});
}
return obsQuery.reobserve();
}
function defaultSubscriptionObserverErrorCallback(error) {
__DEV__ && globals.invariant.error('Unhandled error', error.message, error.stack);
}
function logMissingFieldErrors(missing) {
if (__DEV__ && missing) {
__DEV__ && globals.invariant.debug("Missing cache result fields: ".concat(JSON.stringify(missing)), missing);
}
}
var LocalState = (function () {
function LocalState(_a) {
var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
this.selectionsToResolveCache = new WeakMap();
this.cache = cache;
if (client) {
this.client = client;
}
if (resolvers) {
this.addResolvers(resolvers);
}
if (fragmentMatcher) {
this.setFragmentMatcher(fragmentMatcher);
}
}
LocalState.prototype.addResolvers = function (resolvers) {
var _this = this;
this.resolvers = this.resolvers || {};
if (Array.isArray(resolvers)) {
resolvers.forEach(function (resolverGroup) {
_this.resolvers = utilities.mergeDeep(_this.resolvers, resolverGroup);
});
}
else {
this.resolvers = utilities.mergeDeep(this.resolvers, resolvers);
}
};
LocalState.prototype.setResolvers = function (resolvers) {
this.resolvers = {};
this.addResolvers(resolvers);
};
LocalState.prototype.getResolvers = function () {
return this.resolvers || {};
};
LocalState.prototype.runResolvers = function (_a) {
var document = _a.document, remoteResult = _a.remoteResult, context = _a.context, variables = _a.variables, _b = _a.onlyRunForcedResolvers, onlyRunForcedResolvers = _b === void 0 ? false : _b;
return tslib.__awaiter(this, void 0, void 0, function () {
return tslib.__generator(this, function (_c) {
if (document) {
return [2, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (tslib.__assign(tslib.__assign({}, remoteResult), { data: localResult.result })); })];
}
return [2, remoteResult];
});
});
};
LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
this.fragmentMatcher = fragmentMatcher;
};
LocalState.prototype.getFragmentMatcher = function () {
return this.fragmentMatcher;
};
LocalState.prototype.clientQuery = function (document) {
if (utilities.hasDirectives(['client'], document)) {
if (this.resolvers) {
return document;
}
}
return null;
};
LocalState.prototype.serverQuery = function (document) {
return utilities.removeClientSetsFromDocument(document);
};
LocalState.prototype.prepareContext = function (context) {
var cache = this.cache;
return tslib.__assign(tslib.__assign({}, context), { cache: cache, getCacheKey: function (obj) {
return cache.identify(obj);
} });
};
LocalState.prototype.addExportedVariables = function (document, variables, context) {
if (variables === void 0) { variables = {}; }
if (context === void 0) { context = {}; }
return tslib.__awaiter(this, void 0, void 0, function () {
return tslib.__generator(this, function (_a) {
if (document) {
return [2, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (tslib.__assign(tslib.__assign({}, variables), data.exportedVariables)); })];
}
return [2, tslib.__assign({}, variables)];
});
});
};
LocalState.prototype.shouldForceResolvers = function (document) {
var forceResolvers = false;
graphql.visit(document, {
Directive: {
enter: function (node) {
if (node.name.value === 'client' && node.arguments) {
forceResolvers = node.arguments.some(function (arg) {
return arg.name.value === 'always' &&
arg.value.kind === 'BooleanValue' &&
arg.value.value === true;
});
if (forceResolvers) {
return graphql.BREAK;
}
}
},
},
});
return forceResolvers;
};
LocalState.prototype.buildRootValueFromCache = function (document, variables) {
return this.cache.diff({
query: utilities.buildQueryFromSelectionSet(document),
variables: variables,
returnPartialData: true,
optimistic: false,
}).result;
};
LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
if (context === void 0) { context = {}; }
if (variables === void 0) { variables = {}; }
if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
return tslib.__awaiter(this, void 0, void 0, function () {
var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;
return tslib.__generator(this, function (_b) {
mainDefinition = utilities.getMainDefinition(document);
fragments = utilities.getFragmentDefinitions(document);
fragmentMap = utilities.createFragmentMap(fragments);
selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);
definitionOperation = mainDefinition.operation;
defaultOperationType = definitionOperation
? definitionOperation.charAt(0).toUpperCase() +
definitionOperation.slice(1)
: 'Query';
_a = this, cache = _a.cache, client = _a.client;
execContext = {
fragmentMap: fragmentMap,
context: tslib.__assign(tslib.__assign({}, context), { cache: cache, client: client }),
variables: variables,
fragmentMatcher: fragmentMatcher,
defaultOperationType: defaultOperationType,
exportedVariables: {},
selectionsToResolve: selectionsToResolve,
onlyRunForcedResolvers: onlyRunForcedResolvers,
};
isClientFieldDescendant = false;
return [2, this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({
result: result,
exportedVariables: execContext.exportedVariables,
}); })];
});
});
};
LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {
return tslib.__awaiter(this, void 0, void 0, function () {
var fragmentMap, context, variables, resultsToMerge, execute;
var _this = this;
return tslib.__generator(this, function (_a) {
fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
resultsToMerge = [rootValue];
execute = function (selection) { return tslib.__awaiter(_this, void 0, void 0, function () {
var fragment, typeCondition;
return tslib.__generator(this, function (_a) {
if (!isClientFieldDescendant && !execContext.selectionsToResolve.has(selection)) {
return [2];
}
if (!utilities.shouldInclude(selection, variables)) {
return [2];
}
if (utilities.isField(selection)) {
return [2, this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {
var _a;
if (typeof fieldResult !== 'undefined') {
resultsToMerge.push((_a = {},
_a[utilities.resultKeyNameFromField(selection)] = fieldResult,
_a));
}
})];
}
if (utilities.isInlineFragment(selection)) {
fragment = selection;
}
else {
fragment = fragmentMap[selection.name.value];
__DEV__ ? globals.invariant(fragment, "No fragment named ".concat(selection.name.value)) : globals.invariant(fragment, 11);
}
if (fragment && fragment.typeCondition) {
typeCondition = fragment.typeCondition.name.value;
if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
return [2, this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {
resultsToMerge.push(fragmentResult);
})];
}
}
return [2];
});
}); };
return [2, Promise.all(selectionSet.selections.map(execute)).then(function () {
return utilities.mergeDeepArray(resultsToMerge);
})];
});
});
};
LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {
return tslib.__awaiter(this, void 0, void 0, function () {
var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
var _this = this;
return tslib.__generator(this, function (_a) {
if (!rootValue) {
return [2, null];
}
variables = execContext.variables;
fieldName = field.name.value;
aliasedFieldName = utilities.resultKeyNameFromField(field);
aliasUsed = fieldName !== aliasedFieldName;
defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
resultPromise = Promise.resolve(defaultResult);
if (!execContext.onlyRunForcedResolvers ||
this.shouldForceResolvers(field)) {
resolverType = rootValue.__typename || execContext.defaultOperationType;
resolverMap = this.resolvers && this.resolvers[resolverType];
if (resolverMap) {
resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
if (resolve) {
resultPromise = Promise.resolve(cache.cacheSlot.withValue(this.cache, resolve, [
rootValue,
utilities.argumentsObjectFromField(field, variables),
execContext.context,
{ field: field, fragmentMap: execContext.fragmentMap },
]));
}
}
}
return [2, resultPromise.then(function (result) {
var _a, _b;
if (result === void 0) { result = defaultResult; }
if (field.directives) {
field.directives.forEach(function (directive) {
if (directive.name.value === 'export' && directive.arguments) {
directive.arguments.forEach(function (arg) {
if (arg.name.value === 'as' && arg.value.kind === 'StringValue') {
execContext.exportedVariables[arg.value.value] = result;
}
});
}
});
}
if (!field.selectionSet) {
return result;
}
if (result == null) {
return result;
}
var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === 'client'; })) !== null && _b !== void 0 ? _b : false;
if (Array.isArray(result)) {
return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);
}
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);
}
})];
});
});
};
LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {
var _this = this;
return Promise.all(result.map(function (item) {
if (item === null) {
return null;
}
if (Array.isArray(item)) {
return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);
}
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);
}
}));
};
LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {
var isSingleASTNode = function (node) { return !Array.isArray(node); };
var selectionsToResolveCache = this.selectionsToResolveCache;
function collectByDefinition(definitionNode) {
if (!selectionsToResolveCache.has(definitionNode)) {
var matches_1 = new Set();
selectionsToResolveCache.set(definitionNode, matches_1);
graphql.visit(definitionNode, {
Directive: function (node, _, __, ___, ancestors) {
if (node.name.value === 'client') {
ancestors.forEach(function (node) {
if (isSingleASTNode(node) && graphql.isSelectionNode(node)) {
matches_1.add(node);
}
});
}
},
FragmentSpread: function (spread, _, __, ___, ancestors) {
var fragment = fragmentMap[spread.name.value];
__DEV__ ? globals.invariant(fragment, "No fragment named ".concat(spread.name.value)) : globals.invariant(fragment, 12);
var fragmentSelections = collectByDefinition(fragment);
if (fragmentSelections.size > 0) {
ancestors.forEach(function (node) {
if (isSingleASTNode(node) && graphql.isSelectionNode(node)) {
matches_1.add(node);
}
});
matches_1.add(spread);
fragmentSelections.forEach(function (selection) {
matches_1.add(selection);
});
}
}
});
}
return selectionsToResolveCache.get(definitionNode);
}
return collectByDefinition(mainDefinition);
};
return LocalState;
}());
var destructiveMethodCounts = new (utilities.canUseWeakMap ? WeakMap : Map)();
function wrapDestructiveCacheMethod(cache, methodName) {
var original = cache[methodName];
if (typeof original === "function") {
cache[methodName] = function () {
destructiveMethodCounts.set(cache, (destructiveMethodCounts.get(cache) + 1) % 1e15);
return original.apply(this, arguments);
};
}
}
function cancelNotifyTimeout(info) {
if (info["notifyTimeout"]) {
clearTimeout(info["notifyTimeout"]);
info["notifyTimeout"] = void 0;
}
}
var QueryInfo = (function () {
function QueryInfo(queryManager, queryId) {
if (queryId === void 0) { queryId = queryManager.generateQueryId(); }
this.queryId = queryId;
this.listeners = new Set();
this.document = null;
this.lastRequestId = 1;
this.subscriptions = new Set();
this.stopped = false;
this.dirty = false;
this.observableQuery = null;
var cache = this.cache = queryManager.cache;
if (!destructiveMethodCounts.has(cache)) {
destructiveMethodCounts.set(cache, 0);
wrapDestructiveCacheMethod(cache, "evict");
wrapDestructiveCacheMethod(cache, "modify");
wrapDestructiveCacheMethod(cache, "reset");
}
}
QueryInfo.prototype.init = function (query) {
var networkStatus = query.networkStatus || exports.NetworkStatus.loading;
if (this.variables &&
this.networkStatus !== exports.NetworkStatus.loading &&
!equality.equal(this.variables, query.variables)) {
networkStatus = exports.NetworkStatus.setVariables;
}
if (!equality.equal(query.variables, this.variables)) {
this.lastDiff = void 0;
}
Object.assign(this, {
document: query.document,
variables: query.variables,
networkError: null,
graphQLErrors: this.graphQLErrors || [],
networkStatus: networkStatus,
});
if (query.observableQuery) {
this.setObservableQuery(query.observableQuery);
}
if (query.lastRequestId) {
this.lastRequestId = query.lastRequestId;
}
return this;
};
QueryInfo.prototype.reset = function () {
cancelNotifyTimeout(this);
this.dirty = false;
};
QueryInfo.prototype.getDiff = function (variables) {
if (variables === void 0) { variables = this.variables; }
var options = this.getDiffOptions(variables);
if (this.lastDiff && equality.equal(options, this.lastDiff.options)) {
return this.lastDiff.diff;
}
this.updateWatch(this.variables = variables);
var oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return { complete: false };
}
var diff = this.cache.diff(options);
this.updateLastDiff(diff, options);
return diff;
};
QueryInfo.prototype.updateLastDiff = function (diff, options) {
this.lastDiff = diff ? {
diff: diff,
options: options || this.getDiffOptions(),
} : void 0;
};
QueryInfo.prototype.getDiffOptions = function (variables) {
var _a;
if (variables === void 0) { variables = this.variables; }
return {
query: this.document,
variables: variables,
returnPartialData: true,
optimistic: true,
canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,
};
};
QueryInfo.prototype.setDiff = function (diff) {
var _this = this;
var oldDiff = this.lastDiff && this.lastDiff.diff;
this.updateLastDiff(diff);
if (!this.dirty &&
!equality.equal(oldDiff && oldDiff.result, diff && diff.result)) {
this.dirty = true;
if (!this.notifyTimeout) {
this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);
}
}
};
QueryInfo.prototype.setObservableQuery = function (oq) {
var _this = this;
if (oq === this.observableQuery)
return;
if (this.oqListener) {
this.listeners.delete(this.oqListener);
}
this.observableQuery = oq;
if (oq) {
oq["queryInfo"] = this;
this.listeners.add(this.oqListener = function () {
var diff = _this.getDiff();
if (diff.fromOptimisticTransaction) {
oq["observe"]();
}
else {
reobserveCacheFirst(oq);
}
});
}
else {
delete this.oqListener;
}
};
QueryInfo.prototype.notify = function () {
var _this = this;
cancelNotifyTimeout(this);
if (this.shouldNotify()) {
this.listeners.forEach(function (listener) { return listener(_this); });
}
this.dirty = false;
};
QueryInfo.prototype.shouldNotify = function () {
if (!this.dirty || !this.listeners.size) {
return false;
}
if (isNetworkRequestInFlight(this.networkStatus) &&
this.observableQuery) {
var fetchPolicy = this.observableQuery.options.fetchPolicy;
if (fetchPolicy !== "cache-only" &&
fetchPolicy !== "cache-and-network") {
return false;
}
}
return true;
};
QueryInfo.prototype.stop = function () {
if (!this.stopped) {
this.stopped = true;
this.reset();
this.cancel();
this.cancel = QueryInfo.prototype.cancel;
this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
var oq = this.observableQuery;
if (oq)
oq.stopPolling();
}
};
QueryInfo.prototype.cancel = function () { };
QueryInfo.prototype.updateWatch = function (variables) {
var _this = this;
if (variables === void 0) { variables = this.variables; }
var oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return;
}
var watchOptions = tslib.__assign(tslib.__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });
if (!this.lastWatch ||
!equality.equal(watchOptions, this.lastWatch)) {
this.cancel();
this.cancel = this.cache.watch(this.lastWatch = watchOptions);
}
};
QueryInfo.prototype.resetLastWrite = function () {
this.lastWrite = void 0;
};
QueryInfo.prototype.shouldWrite = function (result, variables) {
var lastWrite = this.lastWrite;
return !(lastWrite &&
lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
equality.equal(variables, lastWrite.variables) &&
equality.equal(result.data, lastWrite.result.data));
};
QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {
var _this = this;
var merger = new utilities.DeepMerger();
var graphQLErrors = utilities.isNonEmptyArray(result.errors)
? result.errors.slice(0)
: [];
this.reset();
if ('incremental' in result && utilities.isNonEmptyArray(result.incremental)) {
var mergedData = mergeIncrementalData(this.getDiff().result, result);
result.data = mergedData;
}
else if ('hasNext' in result && result.hasNext) {
var diff = this.getDiff();
result.data = merger.merge(diff.result, result.data);
}
this.graphQLErrors = graphQLErrors;
if (options.fetchPolicy === 'no-cache') {
this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));
}
else if (cacheWriteBehavior !== 0) {
if (shouldWriteResult(result, options.errorPolicy)) {
this.cache.performTransaction(function (cache) {
if (_this.shouldWrite(result, options.variables)) {
cache.writeQuery({
query: document,
data: result.data,
variables: options.variables,
overwrite: cacheWriteBehavior === 1,
});
_this.lastWrite = {
result: result,
variables: options.variables,
dmCount: destructiveMethodCounts.get(_this.cache),
};
}
else {
if (_this.lastDiff &&
_this.lastDiff.diff.complete) {
result.data = _this.lastDiff.diff.result;
return;
}
}
var diffOptions = _this.getDiffOptions(options.variables);
var diff = cache.diff(diffOptions);
if (!_this.stopped) {
_this.updateWatch(options.variables);
}
_this.updateLastDiff(diff, diffOptions);
if (diff.complete) {
result.data = diff.result;
}
});
}
else {
this.lastWrite = void 0;
}
}
};
QueryInfo.prototype.markReady = function () {
this.networkError = null;
return this.networkStatus = exports.NetworkStatus.ready;
};
QueryInfo.prototype.markError = function (error) {
this.networkStatus = exports.NetworkStatus.error;
this.lastWrite = void 0;
this.reset();
if (error.graphQLErrors) {
this.graphQLErrors = error.graphQLErrors;
}
if (error.networkError) {
this.networkError = error.networkError;
}
return error;
};
return QueryInfo;
}());
function shouldWriteResult(result, errorPolicy) {
if (errorPolicy === void 0) { errorPolicy = "none"; }
var ignoreErrors = errorPolicy === "ignore" ||
errorPolicy === "all";
var writeWithErrors = !utilities.graphQLResultHasError(result);
if (!writeWithErrors && ignoreErrors && result.data) {
writeWithErrors = true;
}
return writeWithErrors;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var QueryManager = (function () {
function QueryManager(_a) {
var cache = _a.cache, link = _a.link, defaultOptions = _a.defaultOptions, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, onBroadcast = _a.onBroadcast, _c = _a.ssrMode, ssrMode = _c === void 0 ? false : _c, _d = _a.clientAwareness, clientAwareness = _d === void 0 ? {} : _d, localState = _a.localState, assumeImmutableResults = _a.assumeImmutableResults;
this.clientAwareness = {};
this.queries = new Map();
this.fetchCancelFns = new Map();
this.transformCache = new (utilities.canUseWeakMap ? WeakMap : Map)();
this.queryIdCounter = 1;
this.requestIdCounter = 1;
this.mutationIdCounter = 1;
this.inFlightLinkObservables = new Map();
this.cache = cache;
this.link = link;
this.defaultOptions = defaultOptions || Object.create(null);
this.queryDeduplication = queryDeduplication;
this.clientAwareness = clientAwareness;
this.localState = localState || new LocalState({ cache: cache });
this.ssrMode = ssrMode;
this.assumeImmutableResults = !!assumeImmutableResults;
if ((this.onBroadcast = onBroadcast)) {
this.mutationStore = Object.create(null);
}
}
QueryManager.prototype.stop = function () {
var _this = this;
this.queries.forEach(function (_info, queryId) {
_this.stopQueryNoBroadcast(queryId);
});
this.cancelPendingFetches(__DEV__ ? new globals.InvariantError('QueryManager stopped while query was in flight') : new globals.InvariantError(14));
};
QueryManager.prototype.cancelPendingFetches = function (error) {
this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
this.fetchCancelFns.clear();
};
QueryManager.prototype.mutate = function (_a) {
var _b, _c;
var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueries = _a.updateQueries, _d = _a.refetchQueries, refetchQueries = _d === void 0 ? [] : _d, _e = _a.awaitRefetchQueries, awaitRefetchQueries = _e === void 0 ? false : _e, updateWithProxyFn = _a.update, onQueryUpdated = _a.onQueryUpdated, _f = _a.fetchPolicy, fetchPolicy = _f === void 0 ? ((_b = this.defaultOptions.mutate) === null || _b === void 0 ? void 0 : _b.fetchPolicy) || "network-only" : _f, _g = _a.errorPolicy, errorPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.errorPolicy) || "none" : _g, keepRootFields = _a.keepRootFields, context = _a.context;
return tslib.__awaiter(this, void 0, void 0, function () {
var mutationId, _h, document, hasClientExports, mutationStoreValue, self;
return tslib.__generator(this, function (_j) {
switch (_j.label) {
case 0:
__DEV__ ? globals.invariant(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.') : globals.invariant(mutation, 15);
__DEV__ ? globals.invariant(fetchPolicy === 'network-only' ||
fetchPolicy === 'no-cache', "Mutations support only 'network-only' or 'no-cache' fetchPolicy strings. The default `network-only` behavior automatically writes mutation results to the cache. Passing `no-cache` skips the cache write.") : globals.invariant(fetchPolicy === 'network-only' ||
fetchPolicy === 'no-cache', 16);
mutationId = this.generateMutationId();
_h = this.transform(mutation), document = _h.document, hasClientExports = _h.hasClientExports;
mutation = this.cache.transformForLink(document);
variables = this.getVariables(mutation, variables);
if (!hasClientExports) return [3, 2];
return [4, this.localState.addExportedVariables(mutation, variables, context)];
case 1:
variables = (_j.sent());
_j.label = 2;
case 2:
mutationStoreValue = this.mutationStore &&
(this.mutationStore[mutationId] = {
mutation: mutation,
variables: variables,
loading: true,
error: null,
});
if (optimisticResponse) {
this.markMutationOptimistic(optimisticResponse, {
mutationId: mutationId,
document: mutation,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
context: context,
updateQueries: updateQueries,
update: updateWithProxyFn,
keepRootFields: keepRootFields,
});
}
this.broadcastQueries();
self = this;
return [2, new Promise(function (resolve, reject) {
return utilities.asyncMap(self.getObservableFromLink(mutation, tslib.__assign(tslib.__assign({}, context), { optimisticResponse: optimisticResponse }), variables, false), function (result) {
if (utilities.graphQLResultHasError(result) && errorPolicy === 'none') {
throw new errors.ApolloError({
graphQLErrors: utilities.getGraphQLErrorsFromResult(result),
});
}
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = null;
}
var storeResult = tslib.__assign({}, result);
if (typeof refetchQueries === "function") {
refetchQueries = refetchQueries(storeResult);
}
if (errorPolicy === 'ignore' &&
utilities.graphQLResultHasError(storeResult)) {
delete storeResult.errors;
}
return self.markMutationResult({
mutationId: mutationId,
result: storeResult,
document: mutation,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
context: context,
update: updateWithProxyFn,
updateQueries: updateQueries,
awaitRefetchQueries: awaitRefetchQueries,
refetchQueries: refetchQueries,
removeOptimistic: optimisticResponse ? mutationId : void 0,
onQueryUpdated: onQueryUpdated,
keepRootFields: keepRootFields,
});
}).subscribe({
next: function (storeResult) {
self.broadcastQueries();
if (!('hasNext' in storeResult) || storeResult.hasNext === false) {
resolve(storeResult);
}
},
error: function (err) {
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = err;
}
if (optimisticResponse) {
self.cache.removeOptimistic(mutationId);
}
self.broadcastQueries();
reject(err instanceof errors.ApolloError ? err : new errors.ApolloError({
networkError: err,
}));
},
});
})];
}
});
});
};
QueryManager.prototype.markMutationResult = function (mutation, cache) {
var _this = this;
if (cache === void 0) { cache = this.cache; }
var result = mutation.result;
var cacheWrites = [];
var skipCache = mutation.fetchPolicy === "no-cache";
if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
if (!isExecutionPatchIncrementalResult(result)) {
cacheWrites.push({
result: result.data,
dataId: 'ROOT_MUTATION',
query: mutation.document,
variables: mutation.variables,
});
}
if (isExecutionPatchIncrementalResult(result) && utilities.isNonEmptyArray(result.incremental)) {
var diff = cache.diff({
id: "ROOT_MUTATION",
query: this.transform(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
var mergedData = void 0;
if (diff.result) {
mergedData = mergeIncrementalData(diff.result, result);
}
if (typeof mergedData !== 'undefined') {
result.data = mergedData;
cacheWrites.push({
result: mergedData,
dataId: 'ROOT_MUTATION',
query: mutation.document,
variables: mutation.variables,
});
}
}
var updateQueries_1 = mutation.updateQueries;
if (updateQueries_1) {
this.queries.forEach(function (_a, queryId) {
var observableQuery = _a.observableQuery;
var queryName = observableQuery && observableQuery.queryName;
if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {
return;
}
var updater = updateQueries_1[queryName];
var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;
var _c = cache.diff({
query: document,
variables: variables,
returnPartialData: true,
optimistic: false,
}), currentQueryResult = _c.result, complete = _c.complete;
if (complete && currentQueryResult) {
var nextQueryResult = updater(currentQueryResult, {
mutationResult: result,
queryName: document && utilities.getOperationName(document) || void 0,
queryVariables: variables,
});
if (nextQueryResult) {
cacheWrites.push({
result: nextQueryResult,
dataId: 'ROOT_QUERY',
query: document,
variables: variables,
});
}
}
});
}
}
if (cacheWrites.length > 0 ||
mutation.refetchQueries ||
mutation.update ||
mutation.onQueryUpdated ||
mutation.removeOptimistic) {
var results_1 = [];
this.refetchQueries({
updateCache: function (cache) {
if (!skipCache) {
cacheWrites.forEach(function (write) { return cache.write(write); });
}
var update = mutation.update;
var isFinalResult = !isExecutionPatchResult(result) ||
(isExecutionPatchIncrementalResult(result) && !result.hasNext);
if (update) {
if (!skipCache) {
var diff = cache.diff({
id: "ROOT_MUTATION",
query: _this.transform(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
if (diff.complete) {
result = tslib.__assign(tslib.__assign({}, result), { data: diff.result });
if ('incremental' in result) {
delete result.incremental;
}
if ('hasNext' in result) {
delete result.hasNext;
}
}
}
if (isFinalResult) {
update(cache, result, {
context: mutation.context,
variables: mutation.variables,
});
}
}
if (!skipCache && !mutation.keepRootFields && isFinalResult) {
cache.modify({
id: 'ROOT_MUTATION',
fields: function (value, _a) {
var fieldName = _a.fieldName, DELETE = _a.DELETE;
return fieldName === "__typename" ? value : DELETE;
},
});
}
},
include: mutation.refetchQueries,
optimistic: false,
removeOptimistic: mutation.removeOptimistic,
onQueryUpdated: mutation.onQueryUpdated || null,
}).forEach(function (result) { return results_1.push(result); });
if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
return Promise.all(results_1).then(function () { return result; });
}
}
return Promise.resolve(result);
};
QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {
var _this = this;
var data = typeof optimisticResponse === "function"
? optimisticResponse(mutation.variables)
: optimisticResponse;
return this.cache.recordOptimisticTransaction(function (cache) {
try {
_this.markMutationResult(tslib.__assign(tslib.__assign({}, mutation), { result: { data: data } }), cache);
}
catch (error) {
__DEV__ && globals.invariant.error(error);
}
}, mutation.mutationId);
};
QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
return this.fetchQueryObservable(queryId, options, networkStatus).promise;
};
QueryManager.prototype.getQueryStore = function () {
var store = Object.create(null);
this.queries.forEach(function (info, queryId) {
store[queryId] = {
variables: info.variables,
networkStatus: info.networkStatus,
networkError: info.networkError,
graphQLErrors: info.graphQLErrors,
};
});
return store;
};
QueryManager.prototype.resetErrors = function (queryId) {
var queryInfo = this.queries.get(queryId);
if (queryInfo) {
queryInfo.networkError = undefined;
queryInfo.graphQLErrors = [];
}
};
QueryManager.prototype.transform = function (document) {
var transformCache = this.transformCache;
if (!transformCache.has(document)) {
var transformed = this.cache.transformDocument(document);
var noConnection = utilities.removeConnectionDirectiveFromDocument(transformed);
var clientQuery = this.localState.clientQuery(transformed);
var serverQuery = noConnection && this.localState.serverQuery(noConnection);
var cacheEntry_1 = {
document: transformed,
hasClientExports: utilities.hasClientExports(transformed),
hasForcedResolvers: this.localState.shouldForceResolvers(transformed),
clientQuery: clientQuery,
serverQuery: serverQuery,
defaultVars: utilities.getDefaultValues(utilities.getOperationDefinition(transformed)),
asQuery: tslib.__assign(tslib.__assign({}, transformed), { definitions: transformed.definitions.map(function (def) {
if (def.kind === "OperationDefinition" &&
def.operation !== "query") {
return tslib.__assign(tslib.__assign({}, def), { operation: "query" });
}
return def;
}) })
};
var add = function (doc) {
if (doc && !transformCache.has(doc)) {
transformCache.set(doc, cacheEntry_1);
}
};
add(document);
add(transformed);
add(clientQuery);
add(serverQuery);
}
return transformCache.get(document);
};
QueryManager.prototype.getVariables = function (document, variables) {
return tslib.__assign(tslib.__assign({}, this.transform(document).defaultVars), variables);
};
QueryManager.prototype.watchQuery = function (options) {
options = tslib.__assign(tslib.__assign({}, options), { variables: this.getVariables(options.query, options.variables) });
if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
options.notifyOnNetworkStatusChange = false;
}
var queryInfo = new QueryInfo(this);
var observable = new ObservableQuery({
queryManager: this,
queryInfo: queryInfo,
options: options,
});
this.queries.set(observable.queryId, queryInfo);
queryInfo.init({
document: observable.query,
observableQuery: observable,
variables: observable.variables,
});
return observable;
};
QueryManager.prototype.query = function (options, queryId) {
var _this = this;
if (queryId === void 0) { queryId = this.generateQueryId(); }
__DEV__ ? globals.invariant(options.query, 'query option is required. You must specify your GraphQL document ' +
'in the query option.') : globals.invariant(options.query, 17);
__DEV__ ? globals.invariant(options.query.kind === 'Document', 'You must wrap the query string in a "gql" tag.') : globals.invariant(options.query.kind === 'Document', 18);
__DEV__ ? globals.invariant(!options.returnPartialData, 'returnPartialData option only supported on watchQuery.') : globals.invariant(!options.returnPartialData, 19);
__DEV__ ? globals.invariant(!options.pollInterval, 'pollInterval option only supported on watchQuery.') : globals.invariant(!options.pollInterval, 20);
return this.fetchQuery(queryId, options).finally(function () { return _this.stopQuery(queryId); });
};
QueryManager.prototype.generateQueryId = function () {
return String(this.queryIdCounter++);
};
QueryManager.prototype.generateRequestId = function () {
return this.requestIdCounter++;
};
QueryManager.prototype.generateMutationId = function () {
return String(this.mutationIdCounter++);
};
QueryManager.prototype.stopQueryInStore = function (queryId) {
this.stopQueryInStoreNoBroadcast(queryId);
this.broadcastQueries();
};
QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
var queryInfo = this.queries.get(queryId);
if (queryInfo)
queryInfo.stop();
};
QueryManager.prototype.clearStore = function (options) {
if (options === void 0) { options = {
discardWatches: true,
}; }
this.cancelPendingFetches(__DEV__ ? new globals.InvariantError('Store reset while query was in flight (not completed in link chain)') : new globals.InvariantError(21));
this.queries.forEach(function (queryInfo) {
if (queryInfo.observableQuery) {
queryInfo.networkStatus = exports.NetworkStatus.loading;
}
else {
queryInfo.stop();
}
});
if (this.mutationStore) {
this.mutationStore = Object.create(null);
}
return this.cache.reset(options);
};
QueryManager.prototype.getObservableQueries = function (include) {
var _this = this;
if (include === void 0) { include = "active"; }
var queries = new Map();
var queryNamesAndDocs = new Map();
var legacyQueryOptions = new Set();
if (Array.isArray(include)) {
include.forEach(function (desc) {
if (typeof desc === "string") {
queryNamesAndDocs.set(desc, false);
}
else if (utilities.isDocumentNode(desc)) {
queryNamesAndDocs.set(_this.transform(desc).document, false);
}
else if (utilities.isNonNullObject(desc) && desc.query) {
legacyQueryOptions.add(desc);
}
});
}
this.queries.forEach(function (_a, queryId) {
var oq = _a.observableQuery, document = _a.document;
if (oq) {
if (include === "all") {
queries.set(queryId, oq);
return;
}
var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;
if (fetchPolicy === "standby" ||
(include === "active" && !oq.hasObservers())) {
return;
}
if (include === "active" ||
(queryName && queryNamesAndDocs.has(queryName)) ||
(document && queryNamesAndDocs.has(document))) {
queries.set(queryId, oq);
if (queryName)
queryNamesAndDocs.set(queryName, true);
if (document)
queryNamesAndDocs.set(document, true);
}
}
});
if (legacyQueryOptions.size) {
legacyQueryOptions.forEach(function (options) {
var queryId = utilities.makeUniqueId("legacyOneTimeQuery");
var queryInfo = _this.getQuery(queryId).init({
document: options.query,
variables: options.variables,
});
var oq = new ObservableQuery({
queryManager: _this,
queryInfo: queryInfo,
options: tslib.__assign(tslib.__assign({}, options), { fetchPolicy: "network-only" }),
});
globals.invariant(oq.queryId === queryId);
queryInfo.setObservableQuery(oq);
queries.set(queryId, oq);
});
}
if (__DEV__ && queryNamesAndDocs.size) {
queryNamesAndDocs.forEach(function (included, nameOrDoc) {
if (!included) {
__DEV__ && globals.invariant.warn("Unknown query ".concat(typeof nameOrDoc === "string" ? "named " : "").concat(JSON.stringify(nameOrDoc, null, 2), " requested in refetchQueries options.include array"));
}
});
}
return queries;
};
QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
var _this = this;
if (includeStandby === void 0) { includeStandby = false; }
var observableQueryPromises = [];
this.getObservableQueries(includeStandby ? "all" : "active").forEach(function (observableQuery, queryId) {
var fetchPolicy = observableQuery.options.fetchPolicy;
observableQuery.resetLastResults();
if (includeStandby ||
(fetchPolicy !== "standby" &&
fetchPolicy !== "cache-only")) {
observableQueryPromises.push(observableQuery.refetch());
}
_this.getQuery(queryId).setDiff(null);
});
this.broadcastQueries();
return Promise.all(observableQueryPromises);
};
QueryManager.prototype.setObservableQuery = function (observableQuery) {
this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);
};
QueryManager.prototype.startGraphQLSubscription = function (_a) {
var _this = this;
var query = _a.query, fetchPolicy = _a.fetchPolicy, errorPolicy = _a.errorPolicy, variables = _a.variables, _b = _a.context, context = _b === void 0 ? {} : _b;
query = this.transform(query).document;
variables = this.getVariables(query, variables);
var makeObservable = function (variables) {
return _this.getObservableFromLink(query, context, variables).map(function (result) {
if (fetchPolicy !== 'no-cache') {
if (shouldWriteResult(result, errorPolicy)) {
_this.cache.write({
query: query,
result: result.data,
dataId: 'ROOT_SUBSCRIPTION',
variables: variables,
});
}
_this.broadcastQueries();
}
if (utilities.graphQLResultHasError(result)) {
throw new errors.ApolloError({
graphQLErrors: result.errors,
});
}
return result;
});
};
if (this.transform(query).hasClientExports) {
var observablePromise_1 = this.localState.addExportedVariables(query, variables, context).then(makeObservable);
return new utilities.Observable(function (observer) {
var sub = null;
observablePromise_1.then(function (observable) { return sub = observable.subscribe(observer); }, observer.error);
return function () { return sub && sub.unsubscribe(); };
});
}
return makeObservable(variables);
};
QueryManager.prototype.stopQuery = function (queryId) {
this.stopQueryNoBroadcast(queryId);
this.broadcastQueries();
};
QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
this.stopQueryInStoreNoBroadcast(queryId);
this.removeQuery(queryId);
};
QueryManager.prototype.removeQuery = function (queryId) {
this.fetchCancelFns.delete(queryId);
if (this.queries.has(queryId)) {
this.getQuery(queryId).stop();
this.queries.delete(queryId);
}
};
QueryManager.prototype.broadcastQueries = function () {
if (this.onBroadcast)
this.onBroadcast();
this.queries.forEach(function (info) { return info.notify(); });
};
QueryManager.prototype.getLocalState = function () {
return this.localState;
};
QueryManager.prototype.getObservableFromLink = function (query, context, variables, deduplication) {
var _this = this;
var _a;
if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
var observable;
var serverQuery = this.transform(query).serverQuery;
if (serverQuery) {
var _b = this, inFlightLinkObservables_1 = _b.inFlightLinkObservables, link = _b.link;
var operation = {
query: serverQuery,
variables: variables,
operationName: utilities.getOperationName(serverQuery) || void 0,
context: this.prepareContext(tslib.__assign(tslib.__assign({}, context), { forceFetch: !deduplication })),
};
context = operation.context;
if (deduplication) {
var byVariables_1 = inFlightLinkObservables_1.get(serverQuery) || new Map();
inFlightLinkObservables_1.set(serverQuery, byVariables_1);
var varJson_1 = cache.canonicalStringify(variables);
observable = byVariables_1.get(varJson_1);
if (!observable) {
var concast = new utilities.Concast([
core.execute(link, operation)
]);
byVariables_1.set(varJson_1, observable = concast);
concast.beforeNext(function () {
if (byVariables_1.delete(varJson_1) &&
byVariables_1.size < 1) {
inFlightLinkObservables_1.delete(serverQuery);
}
});
}
}
else {
observable = new utilities.Concast([
core.execute(link, operation)
]);
}
}
else {
observable = new utilities.Concast([
utilities.Observable.of({ data: {} })
]);
context = this.prepareContext(context);
}
var clientQuery = this.transform(query).clientQuery;
if (clientQuery) {
observable = utilities.asyncMap(observable, function (result) {
return _this.localState.runResolvers({
document: clientQuery,
remoteResult: result,
context: context,
variables: variables,
});
});
}
return observable;
};
QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {
var requestId = queryInfo.lastRequestId = this.generateRequestId();
var linkDocument = this.cache.transformForLink(this.transform(queryInfo.document).document);
return utilities.asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {
var graphQLErrors = utilities.getGraphQLErrorsFromResult(result);
var hasErrors = graphQLErrors.length > 0;
if (requestId >= queryInfo.lastRequestId) {
if (hasErrors && options.errorPolicy === "none") {
throw queryInfo.markError(new errors.ApolloError({
graphQLErrors: graphQLErrors,
}));
}
queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);
queryInfo.markReady();
}
var aqr = {
data: result.data,
loading: false,
networkStatus: exports.NetworkStatus.ready,
};
if (hasErrors && options.errorPolicy !== "ignore") {
aqr.errors = graphQLErrors;
aqr.networkStatus = exports.NetworkStatus.error;
}
return aqr;
}, function (networkError) {
var error = errors.isApolloError(networkError)
? networkError
: new errors.ApolloError({ networkError: networkError });
if (requestId >= queryInfo.lastRequestId) {
queryInfo.markError(error);
}
throw error;
});
};
QueryManager.prototype.fetchQueryObservable = function (queryId, options, networkStatus) {
var _this = this;
if (networkStatus === void 0) { networkStatus = exports.NetworkStatus.loading; }
var query = this.transform(options.query).document;
var variables = this.getVariables(query, options.variables);
var queryInfo = this.getQuery(queryId);
var defaults = this.defaultOptions.watchQuery;
var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? defaults && defaults.fetchPolicy || "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? defaults && defaults.errorPolicy || "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
var normalized = Object.assign({}, options, {
query: query,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
returnPartialData: returnPartialData,
notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
context: context,
});
var fromVariables = function (variables) {
normalized.variables = variables;
var concastSources = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
if (normalized.fetchPolicy !== "standby" &&
concastSources.length > 0 &&
queryInfo.observableQuery) {
queryInfo.observableQuery["applyNextFetchPolicy"]("after-fetch", options);
}
return concastSources;
};
var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };
this.fetchCancelFns.set(queryId, function (reason) {
cleanupCancelFn();
setTimeout(function () { return concast.cancel(reason); });
});
var concast = new utilities.Concast(this.transform(normalized.query).hasClientExports
? this.localState.addExportedVariables(normalized.query, normalized.variables, normalized.context).then(fromVariables)
: fromVariables(normalized.variables));
concast.promise.then(cleanupCancelFn, cleanupCancelFn);
return concast;
};
QueryManager.prototype.refetchQueries = function (_a) {
var _this = this;
var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? utilities.makeUniqueId("refetchQueries") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;
var includedQueriesById = new Map();
if (include) {
this.getObservableQueries(include).forEach(function (oq, queryId) {
includedQueriesById.set(queryId, {
oq: oq,
lastDiff: _this.getQuery(queryId).getDiff(),
});
});
}
var results = new Map;
if (updateCache) {
this.cache.batch({
update: updateCache,
optimistic: optimistic && removeOptimistic || false,
removeOptimistic: removeOptimistic,
onWatchUpdated: function (watch, diff, lastDiff) {
var oq = watch.watcher instanceof QueryInfo &&
watch.watcher.observableQuery;
if (oq) {
if (onQueryUpdated) {
includedQueriesById.delete(oq.queryId);
var result = onQueryUpdated(oq, diff, lastDiff);
if (result === true) {
result = oq.refetch();
}
if (result !== false) {
results.set(oq, result);
}
return result;
}
if (onQueryUpdated !== null) {
includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });
}
}
},
});
}
if (includedQueriesById.size) {
includedQueriesById.forEach(function (_a, queryId) {
var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;
var result;
if (onQueryUpdated) {
if (!diff) {
var info = oq["queryInfo"];
info.reset();
diff = info.getDiff();
}
result = onQueryUpdated(oq, diff, lastDiff);
}
if (!onQueryUpdated || result === true) {
result = oq.refetch();
}
if (result !== false) {
results.set(oq, result);
}
if (queryId.indexOf("legacyOneTimeQuery") >= 0) {
_this.stopQueryNoBroadcast(queryId);
}
});
}
if (removeOptimistic) {
this.cache.removeOptimistic(removeOptimistic);
}
return results;
};
QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a, networkStatus) {
var _this = this;
var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;
var oldNetworkStatus = queryInfo.networkStatus;
queryInfo.init({
document: this.transform(query).document,
variables: variables,
networkStatus: networkStatus,
});
var readCache = function () { return queryInfo.getDiff(variables); };
var resultsFromCache = function (diff, networkStatus) {
if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || exports.NetworkStatus.loading; }
var data = diff.result;
if (__DEV__ &&
!returnPartialData &&
!equality.equal(data, {})) {
logMissingFieldErrors(diff.missing);
}
var fromData = function (data) { return utilities.Observable.of(tslib.__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true }))); };
if (data && _this.transform(query).hasForcedResolvers) {
return _this.localState.runResolvers({
document: query,
remoteResult: { data: data },
context: context,
variables: variables,
onlyRunForcedResolvers: true,
}).then(function (resolved) { return fromData(resolved.data || void 0); });
}
if (errorPolicy === 'none' &&
networkStatus === exports.NetworkStatus.refetch &&
Array.isArray(diff.missing)) {
return fromData(void 0);
}
return fromData(data);
};
var cacheWriteBehavior = fetchPolicy === "no-cache" ? 0 :
(networkStatus === exports.NetworkStatus.refetch &&
refetchWritePolicy !== "merge") ? 1
: 2;
var resultsFromLink = function () { return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {
variables: variables,
context: context,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
}); };
var shouldNotify = notifyOnNetworkStatusChange &&
typeof oldNetworkStatus === "number" &&
oldNetworkStatus !== networkStatus &&
isNetworkRequestInFlight(networkStatus);
switch (fetchPolicy) {
default:
case "cache-first": {
var diff = readCache();
if (diff.complete) {
return [
resultsFromCache(diff, queryInfo.markReady()),
];
}
if (returnPartialData || shouldNotify) {
return [
resultsFromCache(diff),
resultsFromLink(),
];
}
return [
resultsFromLink(),
];
}
case "cache-and-network": {
var diff = readCache();
if (diff.complete || returnPartialData || shouldNotify) {
return [
resultsFromCache(diff),
resultsFromLink(),
];
}
return [
resultsFromLink(),
];
}
case "cache-only":
return [
resultsFromCache(readCache(), queryInfo.markReady()),
];
case "network-only":
if (shouldNotify) {
return [
resultsFromCache(readCache()),
resultsFromLink(),
];
}
return [resultsFromLink()];
case "no-cache":
if (shouldNotify) {
return [
resultsFromCache(queryInfo.getDiff()),
resultsFromLink(),
];
}
return [resultsFromLink()];
case "standby":
return [];
}
};
QueryManager.prototype.getQuery = function (queryId) {
if (queryId && !this.queries.has(queryId)) {
this.queries.set(queryId, new QueryInfo(this, queryId));
}
return this.queries.get(queryId);
};
QueryManager.prototype.prepareContext = function (context) {
if (context === void 0) { context = {}; }
var newContext = this.localState.prepareContext(context);
return tslib.__assign(tslib.__assign({}, newContext), { clientAwareness: this.clientAwareness });
};
return QueryManager;
}());
var hasSuggestedDevtools = false;
var ApolloClient = (function () {
function ApolloClient(options) {
var _this = this;
this.resetStoreCallbacks = [];
this.clearStoreCallbacks = [];
var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, _c = options.connectToDevTools, connectToDevTools = _c === void 0 ? typeof window === 'object' &&
!window.__APOLLO_CLIENT__ &&
__DEV__ : _c, _d = options.queryDeduplication, queryDeduplication = _d === void 0 ? true : _d, defaultOptions = options.defaultOptions, _e = options.assumeImmutableResults, assumeImmutableResults = _e === void 0 ? false : _e, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version;
var link = options.link;
if (!link) {
link = uri
? new http.HttpLink({ uri: uri, credentials: credentials, headers: headers })
: core.ApolloLink.empty();
}
if (!cache) {
throw __DEV__ ? new globals.InvariantError("To initialize Apollo Client, you must specify a 'cache' property " +
"in the options object. \n" +
"For more information, please visit: https://go.apollo.dev/c/docs") : new globals.InvariantError(9);
}
this.link = link;
this.cache = cache;
this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
this.queryDeduplication = queryDeduplication;
this.defaultOptions = defaultOptions || Object.create(null);
this.typeDefs = typeDefs;
if (ssrForceFetchDelay) {
setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
}
this.watchQuery = this.watchQuery.bind(this);
this.query = this.query.bind(this);
this.mutate = this.mutate.bind(this);
this.resetStore = this.resetStore.bind(this);
this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
if (connectToDevTools && typeof window === 'object') {
window.__APOLLO_CLIENT__ = this;
}
if (!hasSuggestedDevtools && connectToDevTools && __DEV__) {
hasSuggestedDevtools = true;
if (typeof window !== 'undefined' &&
window.document &&
window.top === window.self &&
!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {
var nav = window.navigator;
var ua = nav && nav.userAgent;
var url = void 0;
if (typeof ua === "string") {
if (ua.indexOf("Chrome/") > -1) {
url = "https://chrome.google.com/webstore/detail/" +
"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm";
}
else if (ua.indexOf("Firefox/") > -1) {
url = "https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/";
}
}
if (url) {
__DEV__ && globals.invariant.log("Download the Apollo DevTools for a better development " +
"experience: " + url);
}
}
}
this.version = version;
this.localState = new LocalState({
cache: cache,
client: this,
resolvers: resolvers,
fragmentMatcher: fragmentMatcher,
});
this.queryManager = new QueryManager({
cache: this.cache,
link: this.link,
defaultOptions: this.defaultOptions,
queryDeduplication: queryDeduplication,
ssrMode: ssrMode,
clientAwareness: {
name: clientAwarenessName,
version: clientAwarenessVersion,
},
localState: this.localState,
assumeImmutableResults: assumeImmutableResults,
onBroadcast: connectToDevTools ? function () {
if (_this.devToolsHookCb) {
_this.devToolsHookCb({
action: {},
state: {
queries: _this.queryManager.getQueryStore(),
mutations: _this.queryManager.mutationStore || {},
},
dataWithOptimisticResults: _this.cache.extract(true),
});
}
} : void 0,
});
}
ApolloClient.prototype.stop = function () {
this.queryManager.stop();
};
ApolloClient.prototype.watchQuery = function (options) {
if (this.defaultOptions.watchQuery) {
options = utilities.mergeOptions(this.defaultOptions.watchQuery, options);
}
if (this.disableNetworkFetches &&
(options.fetchPolicy === 'network-only' ||
options.fetchPolicy === 'cache-and-network')) {
options = tslib.__assign(tslib.__assign({}, options), { fetchPolicy: 'cache-first' });
}
return this.queryManager.watchQuery(options);
};
ApolloClient.prototype.query = function (options) {
if (this.defaultOptions.query) {
options = utilities.mergeOptions(this.defaultOptions.query, options);
}
__DEV__ ? globals.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.') : globals.invariant(options.fetchPolicy !== 'cache-and-network', 10);
if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
options = tslib.__assign(tslib.__assign({}, options), { fetchPolicy: 'cache-first' });
}
return this.queryManager.query(options);
};
ApolloClient.prototype.mutate = function (options) {
if (this.defaultOptions.mutate) {
options = utilities.mergeOptions(this.defaultOptions.mutate, options);
}
return this.queryManager.mutate(options);
};
ApolloClient.prototype.subscribe = function (options) {
return this.queryManager.startGraphQLSubscription(options);
};
ApolloClient.prototype.readQuery = function (options, optimistic) {
if (optimistic === void 0) { optimistic = false; }
return this.cache.readQuery(options, optimistic);
};
ApolloClient.prototype.readFragment = function (options, optimistic) {
if (optimistic === void 0) { optimistic = false; }
return this.cache.readFragment(options, optimistic);
};
ApolloClient.prototype.writeQuery = function (options) {
var ref = this.cache.writeQuery(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
};
ApolloClient.prototype.writeFragment = function (options) {
var ref = this.cache.writeFragment(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
};
ApolloClient.prototype.__actionHookForDevTools = function (cb) {
this.devToolsHookCb = cb;
};
ApolloClient.prototype.__requestRaw = function (payload) {
return core.execute(this.link, payload);
};
ApolloClient.prototype.resetStore = function () {
var _this = this;
return Promise.resolve()
.then(function () { return _this.queryManager.clearStore({
discardWatches: false,
}); })
.then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
.then(function () { return _this.reFetchObservableQueries(); });
};
ApolloClient.prototype.clearStore = function () {
var _this = this;
return Promise.resolve()
.then(function () { return _this.queryManager.clearStore({
discardWatches: true,
}); })
.then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
};
ApolloClient.prototype.onResetStore = function (cb) {
var _this = this;
this.resetStoreCallbacks.push(cb);
return function () {
_this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
};
};
ApolloClient.prototype.onClearStore = function (cb) {
var _this = this;
this.clearStoreCallbacks.push(cb);
return function () {
_this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
};
};
ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
return this.queryManager.reFetchObservableQueries(includeStandby);
};
ApolloClient.prototype.refetchQueries = function (options) {
var map = this.queryManager.refetchQueries(options);
var queries = [];
var results = [];
map.forEach(function (result, obsQuery) {
queries.push(obsQuery);
results.push(result);
});
var result = Promise.all(results);
result.queries = queries;
result.results = results;
result.catch(function (error) {
__DEV__ && globals.invariant.debug("In client.refetchQueries, Promise.all promise rejected with error ".concat(error));
});
return result;
};
ApolloClient.prototype.getObservableQueries = function (include) {
if (include === void 0) { include = "active"; }
return this.queryManager.getObservableQueries(include);
};
ApolloClient.prototype.extract = function (optimistic) {
return this.cache.extract(optimistic);
};
ApolloClient.prototype.restore = function (serializedState) {
return this.cache.restore(serializedState);
};
ApolloClient.prototype.addResolvers = function (resolvers) {
this.localState.addResolvers(resolvers);
};
ApolloClient.prototype.setResolvers = function (resolvers) {
this.localState.setResolvers(resolvers);
};
ApolloClient.prototype.getResolvers = function () {
return this.localState.getResolvers();
};
ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
this.localState.setFragmentMatcher(fragmentMatcher);
};
ApolloClient.prototype.setLink = function (newLink) {
this.link = this.queryManager.link = newLink;
};
return ApolloClient;
}());
tsInvariant.setVerbosity(globals.DEV ? "log" : "silent");
exports.ApolloCache = cache.ApolloCache;
exports.Cache = cache.Cache;
exports.InMemoryCache = cache.InMemoryCache;
exports.MissingFieldError = cache.MissingFieldError;
exports.defaultDataIdFromObject = cache.defaultDataIdFromObject;
exports.makeVar = cache.makeVar;
exports.Observable = utilities.Observable;
exports.isReference = utilities.isReference;
exports.makeReference = utilities.makeReference;
exports.mergeOptions = utilities.mergeOptions;
exports.ApolloError = errors.ApolloError;
exports.isApolloError = errors.isApolloError;
exports.fromError = utils.fromError;
exports.fromPromise = utils.fromPromise;
exports.throwServerError = utils.throwServerError;
exports.toPromise = utils.toPromise;
exports.setLogVerbosity = tsInvariant.setVerbosity;
exports.disableExperimentalFragmentVariables = graphqlTag.disableExperimentalFragmentVariables;
exports.disableFragmentWarnings = graphqlTag.disableFragmentWarnings;
exports.enableExperimentalFragmentVariables = graphqlTag.enableExperimentalFragmentVariables;
exports.gql = graphqlTag.gql;
exports.resetCaches = graphqlTag.resetCaches;
exports.ApolloClient = ApolloClient;
exports.ObservableQuery = ObservableQuery;
for (var k in core) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = core[k];
}
for (var k in http) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = http[k];
}
//# sourceMappingURL=core.cjs.map