text: (function (global, factory) {
      typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('zen-observable'), require('apollo-utilities'), require('graphql/language/printer'), require('symbol-observable'), require('graphql-anywhere/lib/async'), require('graphql-tag')) :
      typeof define === 'function' && define.amd ? define(['exports', 'zen-observable', 'apollo-utilities', 'graphql/language/printer', 'symbol-observable', 'graphql-anywhere/lib/async', 'graphql-tag'], factory) :
      (factory((global.apollo = global.apollo || {}, global.apollo.boost = {}),global.zenObservable,global.apolloUtilities,global.print,global.$$observable,global.graphqlAnywhere.async,global.gql));
  }(this, (function (exports,zenObservable,apolloUtilities,printer,$$observable,async,graphqlTag) { 'use strict';
  
      zenObservable = zenObservable && zenObservable.hasOwnProperty('default') ? zenObservable['default'] : zenObservable;
      $$observable = $$observable && $$observable.hasOwnProperty('default') ? $$observable['default'] : $$observable;
      graphqlTag = graphqlTag && graphqlTag.hasOwnProperty('default') ? graphqlTag['default'] : graphqlTag;
  
      (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 < 7;
      }
  
      var Observable = zenObservable;
  
      var __extends = (undefined && undefined.__extends) || (function () {
          var extendStatics = Object.setPrototypeOf ||
              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
              function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var __assign = (undefined && undefined.__assign) || Object.assign || function(t) {
          for (var s, i = 1, n = arguments.length; i < n; i++) {
              s = arguments[i];
              for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                  t[p] = s[p];
          }
          return t;
      };
      function validateOperation(operation) {
          var OPERATION_FIELDS = [
              'query',
              'operationName',
              'variables',
              'extensions',
              'context',
          ];
          for (var _i = 0, _a = Object.keys(operation); _i < _a.length; _i++) {
              var key = _a[_i];
              if (OPERATION_FIELDS.indexOf(key) < 0) {
                  throw new Error("illegal argument: " + key);
              }
          }
          return operation;
      }
      var LinkError = /** @class */ (function (_super) {
          __extends(LinkError, _super);
          function LinkError(message, link) {
              var _this = _super.call(this, message) || this;
              _this.link = link;
              return _this;
          }
          return LinkError;
      }(Error));
      function isTerminating(link) {
          return link.request.length <= 1;
      }
      function transformOperation(operation) {
          var transformedOperation = {
              variables: operation.variables || {},
              extensions: operation.extensions || {},
              operationName: operation.operationName,
              query: operation.query,
          };
          // best guess at an operation name
          if (!transformedOperation.operationName) {
              transformedOperation.operationName =
                  typeof transformedOperation.query !== 'string'
                      ? apolloUtilities.getOperationName(transformedOperation.query)
                      : '';
          }
          return transformedOperation;
      }
      function createOperation(starting, operation) {
          var context = __assign({}, starting);
          var setContext = function (next) {
              if (typeof next === 'function') {
                  context = __assign({}, context, next(context));
              }
              else {
                  context = __assign({}, context, next);
              }
          };
          var getContext = function () { return (__assign({}, context)); };
          Object.defineProperty(operation, 'setContext', {
              enumerable: false,
              value: setContext,
          });
          Object.defineProperty(operation, 'getContext', {
              enumerable: false,
              value: getContext,
          });
          Object.defineProperty(operation, 'toKey', {
              enumerable: false,
              value: function () { return getKey(operation); },
          });
          return operation;
      }
      function getKey(operation) {
          // XXX we're assuming here that variables will be serialized in the same order.
          // that might not always be true
          return printer.print(operation.query) + "|" + JSON.stringify(operation.variables) + "|" + operation.operationName;
      }
  
      var passthrough = function (op, forward) { return (forward ? forward(op) : Observable.of()); };
      var toLink = function (handler) {
          return typeof handler === 'function' ? new ApolloLink(handler) : handler;
      };
      var empty = function () {
          return new ApolloLink(function (op, forward) { return Observable.of(); });
      };
      var from = function (links) {
          if (links.length === 0)
              return empty();
          return links.map(toLink).reduce(function (x, y) { return x.concat(y); });
      };
      var split = function (test, left, right) {
          if (right === void 0) { right = new ApolloLink(passthrough); }
          var leftLink = toLink(left);
          var rightLink = toLink(right);
          if (isTerminating(leftLink) && isTerminating(rightLink)) {
              return new ApolloLink(function (operation) {
                  return test(operation)
                      ? leftLink.request(operation) || Observable.of()
                      : rightLink.request(operation) || Observable.of();
              });
          }
          else {
              return new ApolloLink(function (operation, forward) {
                  return test(operation)
                      ? leftLink.request(operation, forward) || Observable.of()
                      : rightLink.request(operation, forward) || Observable.of();
              });
          }
      };
      // join two Links together
      var concat = function (first, second) {
          var firstLink = toLink(first);
          if (isTerminating(firstLink)) {
              console.warn(new LinkError("You are calling concat on a terminating link, which will have no effect", firstLink));
              return firstLink;
          }
          var nextLink = toLink(second);
          if (isTerminating(nextLink)) {
              return new ApolloLink(function (operation) {
                  return firstLink.request(operation, function (op) { return nextLink.request(op) || Observable.of(); }) || Observable.of();
              });
          }
          else {
              return new ApolloLink(function (operation, forward) {
                  return (firstLink.request(operation, function (op) {
                      return nextLink.request(op, forward) || Observable.of();
                  }) || Observable.of());
              });
          }
      };
      var ApolloLink = /** @class */ (function () {
          function ApolloLink(request) {
              if (request)
                  this.request = request;
          }
          ApolloLink.prototype.split = function (test, left, right) {
              if (right === void 0) { right = new ApolloLink(passthrough); }
              return this.concat(split(test, left, right));
          };
          ApolloLink.prototype.concat = function (next) {
              return concat(this, next);
          };
          ApolloLink.prototype.request = function (operation, forward) {
              throw new Error('request is not implemented');
          };
          ApolloLink.empty = empty;
          ApolloLink.from = from;
          ApolloLink.split = split;
          ApolloLink.execute = execute;
          return ApolloLink;
      }());
      function execute(link, operation) {
          return (link.request(createOperation(operation.context, transformOperation(validateOperation(operation)))) || Observable.of());
      }
  
      var __extends$1 = (undefined && undefined.__extends) || (function () {
          var extendStatics = function (d, b) {
              extendStatics = Object.setPrototypeOf ||
                  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                  function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
              return extendStatics(d, b);
          };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var Observable$1 = (function (_super) {
          __extends$1(Observable$$1, _super);
          function Observable$$1() {
              return _super !== null && _super.apply(this, arguments) || this;
          }
          Observable$$1.prototype[$$observable] = function () {
              return this;
          };
          Observable$$1.prototype['@@observable'] = function () {
              return this;
          };
          return Observable$$1;
      }(Observable));
  
      var __extends$2 = (undefined && undefined.__extends) || (function () {
          var extendStatics = function (d, b) {
              extendStatics = Object.setPrototypeOf ||
                  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                  function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
              return extendStatics(d, b);
          };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      function isApolloError(err) {
          return err.hasOwnProperty('graphQLErrors');
      }
      var generateErrorMessage = function (err) {
          var message = '';
          if (Array.isArray(err.graphQLErrors) && err.graphQLErrors.length !== 0) {
              err.graphQLErrors.forEach(function (graphQLError) {
                  var errorMessage = graphQLError
                      ? graphQLError.message
                      : 'Error message not found.';
                  message += "GraphQL error: " + errorMessage + "\n";
              });
          }
          if (err.networkError) {
              message += 'Network error: ' + err.networkError.message + '\n';
          }
          message = message.replace(/\n$/, '');
          return message;
      };
      var ApolloError = (function (_super) {
          __extends$2(ApolloError, _super);
          function ApolloError(_a) {
              var graphQLErrors = _a.graphQLErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;
              var _this = _super.call(this, errorMessage) || this;
              _this.graphQLErrors = graphQLErrors || [];
              _this.networkError = networkError || null;
              if (!errorMessage) {
                  _this.message = generateErrorMessage(_this);
              }
              else {
                  _this.message = errorMessage;
              }
              _this.extraInfo = extraInfo;
              _this.__proto__ = ApolloError.prototype;
              return _this;
          }
          return ApolloError;
      }(Error));
  
      (function (FetchType) {
          FetchType[FetchType["normal"] = 1] = "normal";
          FetchType[FetchType["refetch"] = 2] = "refetch";
          FetchType[FetchType["poll"] = 3] = "poll";
      })(exports.FetchType || (exports.FetchType = {}));
  
      var __extends$3 = (undefined && undefined.__extends) || (function () {
          var extendStatics = function (d, b) {
              extendStatics = Object.setPrototypeOf ||
                  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                  function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
              return extendStatics(d, b);
          };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var __assign$1 = (undefined && undefined.__assign) || function () {
          __assign$1 = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$1.apply(this, arguments);
      };
      var hasError = function (storeValue, policy) {
          if (policy === void 0) { policy = 'none'; }
          return storeValue &&
              ((storeValue.graphQLErrors &&
                  storeValue.graphQLErrors.length > 0 &&
                  policy === 'none') ||
                  storeValue.networkError);
      };
      var ObservableQuery = (function (_super) {
          __extends$3(ObservableQuery, _super);
          function ObservableQuery(_a) {
              var scheduler = _a.scheduler, options = _a.options, _b = _a.shouldSubscribe, shouldSubscribe = _b === void 0 ? true : _b;
              var _this = _super.call(this, function (observer) {
                  return _this.onSubscribe(observer);
              }) || this;
              _this.isCurrentlyPolling = false;
              _this.isTornDown = false;
              _this.options = options;
              _this.variables = options.variables || {};
              _this.queryId = scheduler.queryManager.generateQueryId();
              _this.shouldSubscribe = shouldSubscribe;
              _this.scheduler = scheduler;
              _this.queryManager = scheduler.queryManager;
              _this.observers = [];
              _this.subscriptionHandles = [];
              return _this;
          }
          ObservableQuery.prototype.result = function () {
              var that = this;
              return new Promise(function (resolve, reject) {
                  var subscription;
                  var observer = {
                      next: function (result) {
                          resolve(result);
                          if (!that.observers.some(function (obs) { return obs !== observer; })) {
                              that.queryManager.removeQuery(that.queryId);
                          }
                          setTimeout(function () {
                              subscription.unsubscribe();
                          }, 0);
                      },
                      error: function (error) {
                          reject(error);
                      },
                  };
                  subscription = that.subscribe(observer);
              });
          };
          ObservableQuery.prototype.currentResult = function () {
              if (this.isTornDown) {
                  return {
                      data: this.lastError ? {} : this.lastResult ? this.lastResult.data : {},
                      error: this.lastError,
                      loading: false,
                      networkStatus: exports.NetworkStatus.error,
                  };
              }
              var queryStoreValue = this.queryManager.queryStore.get(this.queryId);
              if (hasError(queryStoreValue, this.options.errorPolicy)) {
                  return {
                      data: {},
                      loading: false,
                      networkStatus: queryStoreValue.networkStatus,
                      error: new ApolloError({
                          graphQLErrors: queryStoreValue.graphQLErrors,
                          networkError: queryStoreValue.networkError,
                      }),
                  };
              }
              var _a = this.queryManager.getCurrentQueryResult(this), data = _a.data, partial = _a.partial;
              var queryLoading = !queryStoreValue ||
                  queryStoreValue.networkStatus === exports.NetworkStatus.loading;
              var loading = (this.options.fetchPolicy === 'network-only' && queryLoading) ||
                  (partial && this.options.fetchPolicy !== 'cache-only');
              var networkStatus;
              if (queryStoreValue) {
                  networkStatus = queryStoreValue.networkStatus;
              }
              else {
                  networkStatus = loading ? exports.NetworkStatus.loading : exports.NetworkStatus.ready;
              }
              var result = {
                  data: data,
                  loading: isNetworkRequestInFlight(networkStatus),
                  networkStatus: networkStatus,
              };
              if (queryStoreValue &&
                  queryStoreValue.graphQLErrors &&
                  this.options.errorPolicy === 'all') {
                  result.errors = queryStoreValue.graphQLErrors;
              }
              if (!partial) {
                  var stale = false;
                  this.lastResult = __assign$1({}, result, { stale: stale });
              }
              return __assign$1({}, result, { partial: partial });
          };
          ObservableQuery.prototype.getLastResult = function () {
              return this.lastResult;
          };
          ObservableQuery.prototype.getLastError = function () {
              return this.lastError;
          };
          ObservableQuery.prototype.resetLastResults = function () {
              delete this.lastResult;
              delete this.lastError;
              this.isTornDown = false;
          };
          ObservableQuery.prototype.refetch = function (variables) {
              var fetchPolicy = this.options.fetchPolicy;
              if (fetchPolicy === 'cache-only') {
                  return Promise.reject(new Error('cache-only fetchPolicy option should not be used together with query refetch.'));
              }
              if (!apolloUtilities.isEqual(this.variables, variables)) {
                  this.variables = Object.assign({}, this.variables, variables);
              }
              if (!apolloUtilities.isEqual(this.options.variables, this.variables)) {
                  this.options.variables = Object.assign({}, this.options.variables, this.variables);
              }
              var isNetworkFetchPolicy = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache';
              var combinedOptions = __assign$1({}, this.options, { fetchPolicy: isNetworkFetchPolicy ? fetchPolicy : 'network-only' });
              return this.queryManager
                  .fetchQuery(this.queryId, combinedOptions, exports.FetchType.refetch)
                  .then(function (result) { return result; });
          };
          ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
              var _this = this;
              if (!fetchMoreOptions.updateQuery) {
                  throw new Error('updateQuery option is required. This function defines how to update the query data with the new results.');
              }
              var combinedOptions;
              return Promise.resolve()
                  .then(function () {
                  var qid = _this.queryManager.generateQueryId();
                  if (fetchMoreOptions.query) {
                      combinedOptions = fetchMoreOptions;
                  }
                  else {
                      combinedOptions = __assign$1({}, _this.options, fetchMoreOptions, { variables: Object.assign({}, _this.variables, fetchMoreOptions.variables) });
                  }
                  combinedOptions.fetchPolicy = 'network-only';
                  return _this.queryManager.fetchQuery(qid, combinedOptions, exports.FetchType.normal, _this.queryId);
              })
                  .then(function (fetchMoreResult) {
                  _this.updateQuery(function (previousResult) {
                      return fetchMoreOptions.updateQuery(previousResult, {
                          fetchMoreResult: fetchMoreResult.data,
                          variables: combinedOptions.variables,
                      });
                  });
                  return fetchMoreResult;
              });
          };
          ObservableQuery.prototype.subscribeToMore = function (options) {
              var _this = this;
              var subscription = this.queryManager
                  .startGraphQLSubscription({
                  query: options.document,
                  variables: options.variables,
              })
                  .subscribe({
                  next: function (subscriptionData) {
                      if (options.updateQuery) {
                          _this.updateQuery(function (previous, _a) {
                              var variables = _a.variables;
                              return options.updateQuery(previous, {
                                  subscriptionData: subscriptionData,
                                  variables: variables,
                              });
                          });
                      }
                  },
                  error: function (err) {
                      if (options.onError) {
                          options.onError(err);
                          return;
                      }
                      console.error('Unhandled GraphQL subscription error', err);
                  },
              });
              this.subscriptionHandles.push(subscription);
              return function () {
                  var i = _this.subscriptionHandles.indexOf(subscription);
                  if (i >= 0) {
                      _this.subscriptionHandles.splice(i, 1);
                      subscription.unsubscribe();
                  }
              };
          };
          ObservableQuery.prototype.setOptions = function (opts) {
              var oldOptions = this.options;
              this.options = Object.assign({}, this.options, opts);
              if (opts.pollInterval) {
                  this.startPolling(opts.pollInterval);
              }
              else if (opts.pollInterval === 0) {
                  this.stopPolling();
              }
              var tryFetch = (oldOptions.fetchPolicy !== 'network-only' &&
                  opts.fetchPolicy === 'network-only') ||
                  (oldOptions.fetchPolicy === 'cache-only' &&
                      opts.fetchPolicy !== 'cache-only') ||
                  (oldOptions.fetchPolicy === 'standby' &&
                      opts.fetchPolicy !== 'standby') ||
                  false;
              return this.setVariables(this.options.variables, tryFetch, opts.fetchResults);
          };
          ObservableQuery.prototype.setVariables = function (variables, tryFetch, fetchResults) {
              if (tryFetch === void 0) { tryFetch = false; }
              if (fetchResults === void 0) { fetchResults = true; }
              this.isTornDown = false;
              var newVariables = variables ? variables : this.variables;
              if (apolloUtilities.isEqual(newVariables, this.variables) && !tryFetch) {
                  if (this.observers.length === 0 || !fetchResults) {
                      return new Promise(function (resolve) { return resolve(); });
                  }
                  return this.result();
              }
              else {
                  this.variables = newVariables;
                  this.options.variables = newVariables;
                  if (this.observers.length === 0) {
                      return new Promise(function (resolve) { return resolve(); });
                  }
                  return this.queryManager
                      .fetchQuery(this.queryId, __assign$1({}, this.options, { variables: this.variables }))
                      .then(function (result) { return result; });
              }
          };
          ObservableQuery.prototype.updateQuery = function (mapFn) {
              var _a = this.queryManager.getQueryWithPreviousResult(this.queryId), previousResult = _a.previousResult, variables = _a.variables, document = _a.document;
              var newResult = apolloUtilities.tryFunctionOrLogError(function () {
                  return mapFn(previousResult, { variables: variables });
              });
              if (newResult) {
                  this.queryManager.dataStore.markUpdateQueryResult(document, variables, newResult);
                  this.queryManager.broadcastQueries();
              }
          };
          ObservableQuery.prototype.stopPolling = function () {
              if (this.isCurrentlyPolling) {
                  this.scheduler.stopPollingQuery(this.queryId);
                  this.options.pollInterval = undefined;
                  this.isCurrentlyPolling = false;
              }
          };
          ObservableQuery.prototype.startPolling = function (pollInterval) {
              if (this.options.fetchPolicy === 'cache-first' ||
                  this.options.fetchPolicy === 'cache-only') {
                  throw new Error('Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.');
              }
              if (this.isCurrentlyPolling) {
                  this.scheduler.stopPollingQuery(this.queryId);
                  this.isCurrentlyPolling = false;
              }
              this.options.pollInterval = pollInterval;
              this.isCurrentlyPolling = true;
              this.scheduler.startPollingQuery(this.options, this.queryId);
          };
          ObservableQuery.prototype.onSubscribe = function (observer) {
              var _this = this;
              if (observer._subscription &&
                  observer._subscription._observer &&
                  !observer._subscription._observer.error) {
                  observer._subscription._observer.error = function (error) {
                      console.error('Unhandled error', error.message, error.stack);
                  };
              }
              this.observers.push(observer);
              if (observer.next && this.lastResult)
                  observer.next(this.lastResult);
              if (observer.error && this.lastError)
                  observer.error(this.lastError);
              if (this.observers.length === 1)
                  this.setUpQuery();
              return function () {
                  _this.observers = _this.observers.filter(function (obs) { return obs !== observer; });
                  if (_this.observers.length === 0) {
                      _this.tearDownQuery();
                  }
              };
          };
          ObservableQuery.prototype.setUpQuery = function () {
              var _this = this;
              if (this.shouldSubscribe) {
                  this.queryManager.addObservableQuery(this.queryId, this);
              }
              if (!!this.options.pollInterval) {
                  if (this.options.fetchPolicy === 'cache-first' ||
                      this.options.fetchPolicy === 'cache-only') {
                      throw new Error('Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.');
                  }
                  this.isCurrentlyPolling = true;
                  this.scheduler.startPollingQuery(this.options, this.queryId);
              }
              var observer = {
                  next: function (result) {
                      _this.lastResult = result;
                      _this.observers.forEach(function (obs) { return obs.next && obs.next(result); });
                  },
                  error: function (error) {
                      _this.lastError = error;
                      _this.observers.forEach(function (obs) { return obs.error && obs.error(error); });
                  },
              };
              this.queryManager.startQuery(this.queryId, this.options, this.queryManager.queryListenerForObserver(this.queryId, this.options, observer));
          };
          ObservableQuery.prototype.tearDownQuery = function () {
              this.isTornDown = true;
              if (this.isCurrentlyPolling) {
                  this.scheduler.stopPollingQuery(this.queryId);
                  this.isCurrentlyPolling = false;
              }
              this.subscriptionHandles.forEach(function (sub) { return sub.unsubscribe(); });
              this.subscriptionHandles = [];
              this.queryManager.removeObservableQuery(this.queryId);
              this.queryManager.stopQuery(this.queryId);
              this.observers = [];
          };
          return ObservableQuery;
      }(Observable$1));
  
      var __extends$4 = (undefined && undefined.__extends) || (function () {
          var extendStatics = Object.setPrototypeOf ||
              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
              function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      /*
       * Expects context to contain the forceFetch field if no dedup
       */
      var DedupLink = /** @class */ (function (_super) {
          __extends$4(DedupLink, _super);
          function DedupLink() {
              var _this = _super !== null && _super.apply(this, arguments) || this;
              _this.inFlightRequestObservables = new Map();
              _this.subscribers = new Map();
              return _this;
          }
          DedupLink.prototype.request = function (operation, forward) {
              var _this = this;
              // sometimes we might not want to deduplicate a request, for example when we want to force fetch it.
              if (operation.getContext().forceFetch) {
                  return forward(operation);
              }
              var key = operation.toKey();
              var cleanup = function (key) {
                  _this.inFlightRequestObservables.delete(key);
                  var prev = _this.subscribers.get(key);
                  return prev;
              };
              if (!this.inFlightRequestObservables.get(key)) {
                  // this is a new request, i.e. we haven't deduplicated it yet
                  // call the next link
                  var singleObserver_1 = forward(operation);
                  var subscription_1;
                  var sharedObserver = new Observable(function (observer) {
                      // this will still be called by each subscriber regardless of
                      // deduplication status
                      var prev = _this.subscribers.get(key);
                      if (!prev)
                          prev = { next: [], error: [], complete: [] };
                      _this.subscribers.set(key, {
                          next: prev.next.concat([observer.next.bind(observer)]),
                          error: prev.error.concat([observer.error.bind(observer)]),
                          complete: prev.complete.concat([observer.complete.bind(observer)]),
                      });
                      if (!subscription_1) {
                          subscription_1 = singleObserver_1.subscribe({
                              next: function (result) {
                                  var prev = cleanup(key);
                                  _this.subscribers.delete(key);
                                  if (prev) {
                                      prev.next.forEach(function (next) { return next(result); });
                                      prev.complete.forEach(function (complete) { return complete(); });
                                  }
                              },
                              error: function (error) {
                                  var prev = cleanup(key);
                                  _this.subscribers.delete(key);
                                  if (prev)
                                      prev.error.forEach(function (err) { return err(error); });
                              },
                          });
                      }
                      return function () {
                          if (subscription_1)
                              subscription_1.unsubscribe();
                          _this.inFlightRequestObservables.delete(key);
                      };
                  });
                  this.inFlightRequestObservables.set(key, sharedObserver);
              }
              // return shared Observable
              return this.inFlightRequestObservables.get(key);
          };
          return DedupLink;
      }(ApolloLink));
  
      var __assign$2 = (undefined && undefined.__assign) || function () {
          __assign$2 = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$2.apply(this, arguments);
      };
      var QueryScheduler = (function () {
          function QueryScheduler(_a) {
              var queryManager = _a.queryManager, ssrMode = _a.ssrMode;
              this.inFlightQueries = {};
              this.registeredQueries = {};
              this.intervalQueries = {};
              this.pollingTimers = {};
              this.ssrMode = false;
              this.queryManager = queryManager;
              this.ssrMode = ssrMode || false;
          }
          QueryScheduler.prototype.checkInFlight = function (queryId) {
              var query = this.queryManager.queryStore.get(queryId);
              return (query &&
                  query.networkStatus !== exports.NetworkStatus.ready &&
                  query.networkStatus !== exports.NetworkStatus.error);
          };
          QueryScheduler.prototype.fetchQuery = function (queryId, options, fetchType) {
              var _this = this;
              return new Promise(function (resolve, reject) {
                  _this.queryManager
                      .fetchQuery(queryId, options, fetchType)
                      .then(function (result) {
                      resolve(result);
                  })
                      .catch(function (error) {
                      reject(error);
                  });
              });
          };
          QueryScheduler.prototype.startPollingQuery = function (options, queryId, listener) {
              if (!options.pollInterval) {
                  throw new Error('Attempted to start a polling query without a polling interval.');
              }
              if (this.ssrMode)
                  return queryId;
              this.registeredQueries[queryId] = options;
              if (listener) {
                  this.queryManager.addQueryListener(queryId, listener);
              }
              this.addQueryOnInterval(queryId, options);
              return queryId;
          };
          QueryScheduler.prototype.stopPollingQuery = function (queryId) {
              delete this.registeredQueries[queryId];
          };
          QueryScheduler.prototype.fetchQueriesOnInterval = function (interval) {
              var _this = this;
              this.intervalQueries[interval] = this.intervalQueries[interval].filter(function (queryId) {
                  if (!(_this.registeredQueries.hasOwnProperty(queryId) &&
                      _this.registeredQueries[queryId].pollInterval === interval)) {
                      return false;
                  }
                  if (_this.checkInFlight(queryId)) {
                      return true;
                  }
                  var queryOptions = _this.registeredQueries[queryId];
                  var pollingOptions = __assign$2({}, queryOptions);
                  pollingOptions.fetchPolicy = 'network-only';
                  _this.fetchQuery(queryId, pollingOptions, exports.FetchType.poll).catch(function () { });
                  return true;
              });
              if (this.intervalQueries[interval].length === 0) {
                  clearInterval(this.pollingTimers[interval]);
                  delete this.intervalQueries[interval];
              }
          };
          QueryScheduler.prototype.addQueryOnInterval = function (queryId, queryOptions) {
              var _this = this;
              var interval = queryOptions.pollInterval;
              if (!interval) {
                  throw new Error("A poll interval is required to start polling query with id '" + queryId + "'.");
              }
              if (this.intervalQueries.hasOwnProperty(interval.toString()) &&
                  this.intervalQueries[interval].length > 0) {
                  this.intervalQueries[interval].push(queryId);
              }
              else {
                  this.intervalQueries[interval] = [queryId];
                  this.pollingTimers[interval] = setInterval(function () {
                      _this.fetchQueriesOnInterval(interval);
                  }, interval);
              }
          };
          QueryScheduler.prototype.registerPollingQuery = function (queryOptions) {
              if (!queryOptions.pollInterval) {
                  throw new Error('Attempted to register a non-polling query with the scheduler.');
              }
              return new ObservableQuery({
                  scheduler: this,
                  options: queryOptions,
              });
          };
          return QueryScheduler;
      }());
  
      var MutationStore = (function () {
          function MutationStore() {
              this.store = {};
          }
          MutationStore.prototype.getStore = function () {
              return this.store;
          };
          MutationStore.prototype.get = function (mutationId) {
              return this.store[mutationId];
          };
          MutationStore.prototype.initMutation = function (mutationId, mutationString, variables) {
              this.store[mutationId] = {
                  mutationString: mutationString,
                  variables: variables || {},
                  loading: true,
                  error: null,
              };
          };
          MutationStore.prototype.markMutationError = function (mutationId, error) {
              var mutation = this.store[mutationId];
              if (!mutation) {
                  return;
              }
              mutation.loading = false;
              mutation.error = error;
          };
          MutationStore.prototype.markMutationResult = function (mutationId) {
              var mutation = this.store[mutationId];
              if (!mutation) {
                  return;
              }
              mutation.loading = false;
              mutation.error = null;
          };
          MutationStore.prototype.reset = function () {
              this.store = {};
          };
          return MutationStore;
      }());
  
      var __assign$3 = (undefined && undefined.__assign) || function () {
          __assign$3 = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$3.apply(this, arguments);
      };
      var QueryStore = (function () {
          function QueryStore() {
              this.store = {};
          }
          QueryStore.prototype.getStore = function () {
              return this.store;
          };
          QueryStore.prototype.get = function (queryId) {
              return this.store[queryId];
          };
          QueryStore.prototype.initQuery = function (query) {
              var previousQuery = this.store[query.queryId];
              if (previousQuery &&
                  previousQuery.document !== query.document &&
                  printer.print(previousQuery.document) !== printer.print(query.document)) {
                  throw new Error('Internal Error: may not update existing query string in store');
              }
              var isSetVariables = false;
              var previousVariables = null;
              if (query.storePreviousVariables &&
                  previousQuery &&
                  previousQuery.networkStatus !== exports.NetworkStatus.loading) {
                  if (!apolloUtilities.isEqual(previousQuery.variables, query.variables)) {
                      isSetVariables = true;
                      previousVariables = previousQuery.variables;
                  }
              }
              var networkStatus;
              if (isSetVariables) {
                  networkStatus = exports.NetworkStatus.setVariables;
              }
              else if (query.isPoll) {
                  networkStatus = exports.NetworkStatus.poll;
              }
              else if (query.isRefetch) {
                  networkStatus = exports.NetworkStatus.refetch;
              }
              else {
                  networkStatus = exports.NetworkStatus.loading;
              }
              var graphQLErrors = [];
              if (previousQuery && previousQuery.graphQLErrors) {
                  graphQLErrors = previousQuery.graphQLErrors;
              }
              this.store[query.queryId] = {
                  document: query.document,
                  variables: query.variables,
                  previousVariables: previousVariables,
                  networkError: null,
                  graphQLErrors: graphQLErrors,
                  networkStatus: networkStatus,
                  metadata: query.metadata,
              };
              if (typeof query.fetchMoreForQueryId === 'string' &&
                  this.store[query.fetchMoreForQueryId]) {
                  this.store[query.fetchMoreForQueryId].networkStatus =
                      exports.NetworkStatus.fetchMore;
              }
          };
          QueryStore.prototype.markQueryResult = function (queryId, result, fetchMoreForQueryId) {
              if (!this.store[queryId])
                  return;
              this.store[queryId].networkError = null;
              this.store[queryId].graphQLErrors =
                  result.errors && result.errors.length ? result.errors : [];
              this.store[queryId].previousVariables = null;
              this.store[queryId].networkStatus = exports.NetworkStatus.ready;
              if (typeof fetchMoreForQueryId === 'string' &&
                  this.store[fetchMoreForQueryId]) {
                  this.store[fetchMoreForQueryId].networkStatus = exports.NetworkStatus.ready;
              }
          };
          QueryStore.prototype.markQueryError = function (queryId, error, fetchMoreForQueryId) {
              if (!this.store[queryId])
                  return;
              this.store[queryId].networkError = error;
              this.store[queryId].networkStatus = exports.NetworkStatus.error;
              if (typeof fetchMoreForQueryId === 'string') {
                  this.markQueryResultClient(fetchMoreForQueryId, true);
              }
          };
          QueryStore.prototype.markQueryResultClient = function (queryId, complete) {
              if (!this.store[queryId])
                  return;
              this.store[queryId].networkError = null;
              this.store[queryId].previousVariables = null;
              this.store[queryId].networkStatus = complete
                  ? exports.NetworkStatus.ready
                  : exports.NetworkStatus.loading;
          };
          QueryStore.prototype.stopQuery = function (queryId) {
              delete this.store[queryId];
          };
          QueryStore.prototype.reset = function (observableQueryIds) {
              var _this = this;
              this.store = Object.keys(this.store)
                  .filter(function (queryId) {
                  return observableQueryIds.indexOf(queryId) > -1;
              })
                  .reduce(function (res, key) {
                  res[key] = __assign$3({}, _this.store[key], { networkStatus: exports.NetworkStatus.loading });
                  return res;
              }, {});
          };
          return QueryStore;
      }());
  
      var __assign$4 = (undefined && undefined.__assign) || function () {
          __assign$4 = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$4.apply(this, arguments);
      };
      var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
          return new (P || (P = Promise))(function (resolve, reject) {
              function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
              function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
              function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
              step((generator = generator.apply(thisArg, _arguments || [])).next());
          });
      };
      var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
          var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
          return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
          function verb(n) { return function (v) { return step([n, v]); }; }
          function step(op) {
              if (f) throw new TypeError("Generator is already executing.");
              while (_) try {
                  if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                  if (y = 0, t) op = [op[0] & 2, t.value];
                  switch (op[0]) {
                      case 0: case 1: t = op; break;
                      case 4: _.label++; return { value: op[1], done: false };
                      case 5: _.label++; y = op[1]; op = [0]; continue;
                      case 7: op = _.ops.pop(); _.trys.pop(); continue;
                      default:
                          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                          if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                          if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                          if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                          if (t[2]) _.ops.pop();
                          _.trys.pop(); continue;
                  }
                  op = body.call(thisArg, _);
              } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
              if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
          }
      };
      var defaultQueryInfo = {
          listeners: [],
          invalidated: false,
          document: null,
          newData: null,
          lastRequestId: null,
          observableQuery: null,
          subscriptions: [],
      };
      var QueryManager = (function () {
          function QueryManager(_a) {
              var link = _a.link, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, store = _a.store, _c = _a.onBroadcast, onBroadcast = _c === void 0 ? function () { return undefined; } : _c, _d = _a.ssrMode, ssrMode = _d === void 0 ? false : _d;
              this.mutationStore = new MutationStore();
              this.queryStore = new QueryStore();
              this.idCounter = 1;
              this.queries = new Map();
              this.fetchQueryPromises = new Map();
              this.queryIdsByName = {};
              this.link = link;
              this.deduplicator = ApolloLink.from([new DedupLink(), link]);
              this.queryDeduplication = queryDeduplication;
              this.dataStore = store;
              this.onBroadcast = onBroadcast;
              this.scheduler = new QueryScheduler({ queryManager: this, ssrMode: ssrMode });
          }
          QueryManager.prototype.mutate = function (_a) {
              var _this = this;
              var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueriesByName = _a.updateQueries, _b = _a.refetchQueries, refetchQueries = _b === void 0 ? [] : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, updateWithProxyFn = _a.update, _d = _a.errorPolicy, errorPolicy = _d === void 0 ? 'none' : _d, fetchPolicy = _a.fetchPolicy, _e = _a.context, context = _e === void 0 ? {} : _e;
              if (!mutation) {
                  throw new Error('mutation option is required. You must specify your GraphQL document in the mutation option.');
              }
              if (fetchPolicy && fetchPolicy !== 'no-cache') {
                  throw new Error("fetchPolicy for mutations currently only supports the 'no-cache' policy");
              }
              var mutationId = this.generateQueryId();
              var cache = this.dataStore.getCache();
              (mutation = cache.transformDocument(mutation)),
                  (variables = apolloUtilities.assign({}, apolloUtilities.getDefaultValues(apolloUtilities.getMutationDefinition(mutation)), variables));
              var mutationString = printer.print(mutation);
              this.setQuery(mutationId, function () { return ({ document: mutation }); });
              var generateUpdateQueriesInfo = function () {
                  var ret = {};
                  if (updateQueriesByName) {
                      Object.keys(updateQueriesByName).forEach(function (queryName) {
                          return (_this.queryIdsByName[queryName] || []).forEach(function (queryId) {
                              ret[queryId] = {
                                  updater: updateQueriesByName[queryName],
                                  query: _this.queryStore.get(queryId),
                              };
                          });
                      });
                  }
                  return ret;
              };
              this.mutationStore.initMutation(mutationId, mutationString, variables);
              this.dataStore.markMutationInit({
                  mutationId: mutationId,
                  document: mutation,
                  variables: variables || {},
                  updateQueries: generateUpdateQueriesInfo(),
                  update: updateWithProxyFn,
                  optimisticResponse: optimisticResponse,
              });
              this.broadcastQueries();
              return new Promise(function (resolve, reject) {
                  var storeResult;
                  var error;
                  var operation = _this.buildOperationForLink(mutation, variables, __assign$4({}, context, { optimisticResponse: optimisticResponse }));
                  var completeMutation = function () { return __awaiter(_this, void 0, void 0, function () {
                      var refetchQueryPromises, _i, refetchQueries_1, refetchQuery, promise, queryOptions;
                      return __generator(this, function (_a) {
                          switch (_a.label) {
                              case 0:
                                  if (error) {
                                      this.mutationStore.markMutationError(mutationId, error);
                                  }
                                  this.dataStore.markMutationComplete({
                                      mutationId: mutationId,
                                      optimisticResponse: optimisticResponse,
                                  });
                                  this.broadcastQueries();
                                  if (error) {
                                      throw error;
                                  }
                                  if (typeof refetchQueries === 'function') {
                                      refetchQueries = refetchQueries(storeResult);
                                  }
                                  refetchQueryPromises = [];
                                  for (_i = 0, refetchQueries_1 = refetchQueries; _i < refetchQueries_1.length; _i++) {
                                      refetchQuery = refetchQueries_1[_i];
                                      if (typeof refetchQuery === 'string') {
                                          promise = this.refetchQueryByName(refetchQuery);
                                          if (promise) {
                                              refetchQueryPromises.push(promise);
                                          }
                                          continue;
                                      }
                                      queryOptions = {
                                          query: refetchQuery.query,
                                          variables: refetchQuery.variables,
                                          fetchPolicy: 'network-only',
                                      };
                                      if (refetchQuery.context) {
                                          queryOptions.context = refetchQuery.context;
                                      }
                                      refetchQueryPromises.push(this.query(queryOptions));
                                  }
                                  if (!awaitRefetchQueries) return [3, 2];
                                  return [4, Promise.all(refetchQueryPromises)];
                              case 1:
                                  _a.sent();
                                  _a.label = 2;
                              case 2:
                                  this.setQuery(mutationId, function () { return ({ document: undefined }); });
                                  if (errorPolicy === 'ignore' &&
                                      storeResult &&
                                      apolloUtilities.graphQLResultHasError(storeResult)) {
                                      delete storeResult.errors;
                                  }
                                  return [2, storeResult];
                          }
                      });
                  }); };
                  execute(_this.link, operation).subscribe({
                      next: function (result) {
                          if (apolloUtilities.graphQLResultHasError(result) && errorPolicy === 'none') {
                              error = new ApolloError({
                                  graphQLErrors: result.errors,
                              });
                              return;
                          }
                          _this.mutationStore.markMutationResult(mutationId);
                          if (fetchPolicy !== 'no-cache') {
                              _this.dataStore.markMutationResult({
                                  mutationId: mutationId,
                                  result: result,
                                  document: mutation,
                                  variables: variables || {},
                                  updateQueries: generateUpdateQueriesInfo(),
                                  update: updateWithProxyFn,
                              });
                          }
                          storeResult = result;
                      },
                      error: function (err) {
                          _this.mutationStore.markMutationError(mutationId, err);
                          _this.dataStore.markMutationComplete({
                              mutationId: mutationId,
                              optimisticResponse: optimisticResponse,
                          });
                          _this.broadcastQueries();
                          _this.setQuery(mutationId, function () { return ({ document: undefined }); });
                          reject(new ApolloError({
                              networkError: err,
                          }));
                      },
                      complete: function () { return completeMutation().then(resolve, reject); },
                  });
              });
          };
          QueryManager.prototype.fetchQuery = function (queryId, options, fetchType, fetchMoreForQueryId) {
              var _this = this;
              var _a = options.variables, variables = _a === void 0 ? {} : _a, _b = options.metadata, metadata = _b === void 0 ? null : _b, _c = options.fetchPolicy, fetchPolicy = _c === void 0 ? 'cache-first' : _c;
              var cache = this.dataStore.getCache();
              var query = cache.transformDocument(options.query);
              var storeResult;
              var needToFetch = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache';
              if (fetchType !== exports.FetchType.refetch &&
                  fetchPolicy !== 'network-only' &&
                  fetchPolicy !== 'no-cache') {
                  var _d = this.dataStore.getCache().diff({
                      query: query,
                      variables: variables,
                      returnPartialData: true,
                      optimistic: false,
                  }), complete = _d.complete, result = _d.result;
                  needToFetch = !complete || fetchPolicy === 'cache-and-network';
                  storeResult = result;
              }
              var shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby';
              if (apolloUtilities.hasDirectives(['live'], query))
                  shouldFetch = true;
              var requestId = this.generateRequestId();
              var cancel = this.updateQueryWatch(queryId, query, options);
              this.setQuery(queryId, function () { return ({
                  document: query,
                  lastRequestId: requestId,
                  invalidated: true,
                  cancel: cancel,
              }); });
              this.invalidate(true, fetchMoreForQueryId);
              this.queryStore.initQuery({
                  queryId: queryId,
                  document: query,
                  storePreviousVariables: shouldFetch,
                  variables: variables,
                  isPoll: fetchType === exports.FetchType.poll,
                  isRefetch: fetchType === exports.FetchType.refetch,
                  metadata: metadata,
                  fetchMoreForQueryId: fetchMoreForQueryId,
              });
              this.broadcastQueries();
              var shouldDispatchClientResult = !shouldFetch || fetchPolicy === 'cache-and-network';
              if (shouldDispatchClientResult) {
                  this.queryStore.markQueryResultClient(queryId, !shouldFetch);
                  this.invalidate(true, queryId, fetchMoreForQueryId);
                  this.broadcastQueries();
              }
              if (shouldFetch) {
                  var networkResult = this.fetchRequest({
                      requestId: requestId,
                      queryId: queryId,
                      document: query,
                      options: options,
                      fetchMoreForQueryId: fetchMoreForQueryId,
                  }).catch(function (error) {
                      if (isApolloError(error)) {
                          throw error;
                      }
                      else {
                          var lastRequestId = _this.getQuery(queryId).lastRequestId;
                          if (requestId >= (lastRequestId || 1)) {
                              _this.queryStore.markQueryError(queryId, error, fetchMoreForQueryId);
                              _this.invalidate(true, queryId, fetchMoreForQueryId);
                              _this.broadcastQueries();
                          }
                          _this.removeFetchQueryPromise(requestId);
                          throw new ApolloError({ networkError: error });
                      }
                  });
                  if (fetchPolicy !== 'cache-and-network') {
                      return networkResult;
                  }
                  else {
                      networkResult.catch(function () { });
                  }
              }
              return Promise.resolve({ data: storeResult });
          };
          QueryManager.prototype.queryListenerForObserver = function (queryId, options, observer) {
              var _this = this;
              var previouslyHadError = false;
              return function (queryStoreValue, newData) {
                  _this.invalidate(false, queryId);
                  if (!queryStoreValue)
                      return;
                  var observableQuery = _this.getQuery(queryId).observableQuery;
                  var fetchPolicy = observableQuery
                      ? observableQuery.options.fetchPolicy
                      : options.fetchPolicy;
                  if (fetchPolicy === 'standby')
                      return;
                  var errorPolicy = observableQuery
                      ? observableQuery.options.errorPolicy
                      : options.errorPolicy;
                  var lastResult = observableQuery
                      ? observableQuery.getLastResult()
                      : null;
                  var lastError = observableQuery ? observableQuery.getLastError() : null;
                  var shouldNotifyIfLoading = (!newData && queryStoreValue.previousVariables != null) ||
                      fetchPolicy === 'cache-only' ||
                      fetchPolicy === 'cache-and-network';
                  var networkStatusChanged = Boolean(lastResult &&
                      queryStoreValue.networkStatus !== lastResult.networkStatus);
                  var errorStatusChanged = errorPolicy &&
                      (lastError && lastError.graphQLErrors) !==
                          queryStoreValue.graphQLErrors &&
                      errorPolicy !== 'none';
                  if (!isNetworkRequestInFlight(queryStoreValue.networkStatus) ||
                      (networkStatusChanged && options.notifyOnNetworkStatusChange) ||
                      shouldNotifyIfLoading) {
                      if (((!errorPolicy || errorPolicy === 'none') &&
                          queryStoreValue.graphQLErrors &&
                          queryStoreValue.graphQLErrors.length > 0) ||
                          queryStoreValue.networkError) {
                          var apolloError_1 = new ApolloError({
                              graphQLErrors: queryStoreValue.graphQLErrors,
                              networkError: queryStoreValue.networkError,
                          });
                          previouslyHadError = true;
                          if (observer.error) {
                              try {
                                  observer.error(apolloError_1);
                              }
                              catch (e) {
                                  setTimeout(function () {
                                      throw e;
                                  }, 0);
                              }
                          }
                          else {
                              setTimeout(function () {
                                  throw apolloError_1;
                              }, 0);
                              if (!apolloUtilities.isProduction()) {
                                  console.info('An unhandled error was thrown because no error handler is registered ' +
                                      'for the query ' +
                                      printer.print(queryStoreValue.document));
                              }
                          }
                          return;
                      }
                      try {
                          var data = void 0;
                          var isMissing = void 0;
                          if (newData) {
                              if (fetchPolicy !== 'no-cache') {
                                  _this.setQuery(queryId, function () { return ({ newData: null }); });
                              }
                              data = newData.result;
                              isMissing = !newData.complete || false;
                          }
                          else {
                              if (lastResult && lastResult.data && !errorStatusChanged) {
                                  data = lastResult.data;
                                  isMissing = false;
                              }
                              else {
                                  var document_1 = _this.getQuery(queryId).document;
                                  var readResult = _this.dataStore.getCache().diff({
                                      query: document_1,
                                      variables: queryStoreValue.previousVariables ||
                                          queryStoreValue.variables,
                                      optimistic: true,
                                  });
                                  data = readResult.result;
                                  isMissing = !readResult.complete;
                              }
                          }
                          var resultFromStore = void 0;
                          if (isMissing && fetchPolicy !== 'cache-only') {
                              resultFromStore = {
                                  data: lastResult && lastResult.data,
                                  loading: isNetworkRequestInFlight(queryStoreValue.networkStatus),
                                  networkStatus: queryStoreValue.networkStatus,
                                  stale: true,
                              };
                          }
                          else {
                              resultFromStore = {
                                  data: data,
                                  loading: isNetworkRequestInFlight(queryStoreValue.networkStatus),
                                  networkStatus: queryStoreValue.networkStatus,
                                  stale: false,
                              };
                          }
                          if (errorPolicy === 'all' &&
                              queryStoreValue.graphQLErrors &&
                              queryStoreValue.graphQLErrors.length > 0) {
                              resultFromStore.errors = queryStoreValue.graphQLErrors;
                          }
                          if (observer.next) {
                              var isDifferentResult = !(lastResult &&
                                  resultFromStore &&
                                  lastResult.networkStatus === resultFromStore.networkStatus &&
                                  lastResult.stale === resultFromStore.stale &&
                                  lastResult.data === resultFromStore.data);
                              if (isDifferentResult || previouslyHadError) {
                                  try {
                                      observer.next(resultFromStore);
                                  }
                                  catch (e) {
                                      setTimeout(function () {
                                          throw e;
                                      }, 0);
                                  }
                              }
                          }
                          previouslyHadError = false;
                      }
                      catch (error) {
                          previouslyHadError = true;
                          if (observer.error)
                              observer.error(new ApolloError({ networkError: error }));
                          return;
                      }
                  }
              };
          };
          QueryManager.prototype.watchQuery = function (options, shouldSubscribe) {
              if (shouldSubscribe === void 0) { shouldSubscribe = true; }
              if (options.fetchPolicy === 'standby') {
                  throw new Error('client.watchQuery cannot be called with fetchPolicy set to "standby"');
              }
              var queryDefinition = apolloUtilities.getQueryDefinition(options.query);
              if (queryDefinition.variableDefinitions &&
                  queryDefinition.variableDefinitions.length) {
                  var defaultValues = apolloUtilities.getDefaultValues(queryDefinition);
                  options.variables = apolloUtilities.assign({}, defaultValues, options.variables);
              }
              if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
                  options.notifyOnNetworkStatusChange = false;
              }
              var transformedOptions = __assign$4({}, options);
              return new ObservableQuery({
                  scheduler: this.scheduler,
                  options: transformedOptions,
                  shouldSubscribe: shouldSubscribe,
              });
          };
          QueryManager.prototype.query = function (options) {
              var _this = this;
              if (!options.query) {
                  throw new Error('query option is required. You must specify your GraphQL document ' +
                      'in the query option.');
              }
              if (options.query.kind !== 'Document') {
                  throw new Error('You must wrap the query string in a "gql" tag.');
              }
              if (options.returnPartialData) {
                  throw new Error('returnPartialData option only supported on watchQuery.');
              }
              if (options.pollInterval) {
                  throw new Error('pollInterval option only supported on watchQuery.');
              }
              var requestId = this.idCounter;
              return new Promise(function (resolve, reject) {
                  _this.addFetchQueryPromise(requestId, resolve, reject);
                  return _this.watchQuery(options, false)
                      .result()
                      .then(function (result) {
                      _this.removeFetchQueryPromise(requestId);
                      resolve(result);
                  })
                      .catch(function (error) {
                      _this.removeFetchQueryPromise(requestId);
                      reject(error);
                  });
              });
          };
          QueryManager.prototype.generateQueryId = function () {
              var queryId = this.idCounter.toString();
              this.idCounter++;
              return queryId;
          };
          QueryManager.prototype.stopQueryInStore = function (queryId) {
              this.queryStore.stopQuery(queryId);
              this.invalidate(true, queryId);
              this.broadcastQueries();
          };
          QueryManager.prototype.addQueryListener = function (queryId, listener) {
              this.setQuery(queryId, function (_a) {
                  var _b = _a.listeners, listeners = _b === void 0 ? [] : _b;
                  return ({
                      listeners: listeners.concat([listener]),
                      invalidate: false,
                  });
              });
          };
          QueryManager.prototype.updateQueryWatch = function (queryId, document, options) {
              var _this = this;
              var cancel = this.getQuery(queryId).cancel;
              if (cancel)
                  cancel();
              var previousResult = function () {
                  var previousResult = null;
                  var observableQuery = _this.getQuery(queryId).observableQuery;
                  if (observableQuery) {
                      var lastResult = observableQuery.getLastResult();
                      if (lastResult) {
                          previousResult = lastResult.data;
                      }
                  }
                  return previousResult;
              };
              return this.dataStore.getCache().watch({
                  query: document,
                  variables: options.variables,
                  optimistic: true,
                  previousResult: previousResult,
                  callback: function (newData) {
                      _this.setQuery(queryId, function () { return ({ invalidated: true, newData: newData }); });
                  },
              });
          };
          QueryManager.prototype.addFetchQueryPromise = function (requestId, resolve, reject) {
              this.fetchQueryPromises.set(requestId.toString(), {
                  resolve: resolve,
                  reject: reject,
              });
          };
          QueryManager.prototype.removeFetchQueryPromise = function (requestId) {
              this.fetchQueryPromises.delete(requestId.toString());
          };
          QueryManager.prototype.addObservableQuery = function (queryId, observableQuery) {
              this.setQuery(queryId, function () { return ({ observableQuery: observableQuery }); });
              var queryDef = apolloUtilities.getQueryDefinition(observableQuery.options.query);
              if (queryDef.name && queryDef.name.value) {
                  var queryName = queryDef.name.value;
                  this.queryIdsByName[queryName] = this.queryIdsByName[queryName] || [];
                  this.queryIdsByName[queryName].push(observableQuery.queryId);
              }
          };
          QueryManager.prototype.removeObservableQuery = function (queryId) {
              var _a = this.getQuery(queryId), observableQuery = _a.observableQuery, cancel = _a.cancel;
              if (cancel)
                  cancel();
              if (!observableQuery)
                  return;
              var definition = apolloUtilities.getQueryDefinition(observableQuery.options.query);
              var queryName = definition.name ? definition.name.value : null;
              this.setQuery(queryId, function () { return ({ observableQuery: null }); });
              if (queryName) {
                  this.queryIdsByName[queryName] = this.queryIdsByName[queryName].filter(function (val) {
                      return !(observableQuery.queryId === val);
                  });
              }
          };
          QueryManager.prototype.clearStore = function () {
              this.fetchQueryPromises.forEach(function (_a) {
                  var reject = _a.reject;
                  reject(new Error('Store reset while query was in flight(not completed in link chain)'));
              });
              var resetIds = [];
              this.queries.forEach(function (_a, queryId) {
                  var observableQuery = _a.observableQuery;
                  if (observableQuery)
                      resetIds.push(queryId);
              });
              this.queryStore.reset(resetIds);
              this.mutationStore.reset();
              var reset = this.dataStore.reset();
              return reset;
          };
          QueryManager.prototype.resetStore = function () {
              var _this = this;
              return this.clearStore().then(function () {
                  return _this.reFetchObservableQueries();
              });
          };
          QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
              var observableQueryPromises = this.getObservableQueryPromises(includeStandby);
              this.broadcastQueries();
              return Promise.all(observableQueryPromises);
          };
          QueryManager.prototype.startQuery = function (queryId, options, listener) {
              this.addQueryListener(queryId, listener);
              this.fetchQuery(queryId, options)
                  .catch(function () { return undefined; });
              return queryId;
          };
          QueryManager.prototype.startGraphQLSubscription = function (options) {
              var _this = this;
              var query = options.query;
              var isCacheEnabled = !(options.fetchPolicy && options.fetchPolicy === 'no-cache');
              var cache = this.dataStore.getCache();
              var transformedDoc = cache.transformDocument(query);
              var variables = apolloUtilities.assign({}, apolloUtilities.getDefaultValues(apolloUtilities.getOperationDefinition(query)), options.variables);
              var sub;
              var observers = [];
              return new Observable$1(function (observer) {
                  observers.push(observer);
                  if (observers.length === 1) {
                      var handler = {
                          next: function (result) {
                              if (isCacheEnabled) {
                                  _this.dataStore.markSubscriptionResult(result, transformedDoc, variables);
                                  _this.broadcastQueries();
                              }
                              observers.forEach(function (obs) {
                                  if (apolloUtilities.graphQLResultHasError(result) && obs.error) {
                                      obs.error(new ApolloError({
                                          graphQLErrors: result.errors,
                                      }));
                                  }
                                  else if (obs.next) {
                                      obs.next(result);
                                  }
                              });
                          },
                          error: function (error) {
                              observers.forEach(function (obs) {
                                  if (obs.error) {
                                      obs.error(error);
                                  }
                              });
                          },
                      };
                      var operation = _this.buildOperationForLink(transformedDoc, variables);
                      sub = execute(_this.link, operation).subscribe(handler);
                  }
                  return function () {
                      observers = observers.filter(function (obs) { return obs !== observer; });
                      if (observers.length === 0 && sub) {
                          sub.unsubscribe();
                      }
                  };
              });
          };
          QueryManager.prototype.stopQuery = function (queryId) {
              this.stopQueryInStore(queryId);
              this.removeQuery(queryId);
          };
          QueryManager.prototype.removeQuery = function (queryId) {
              var subscriptions = this.getQuery(queryId).subscriptions;
              subscriptions.forEach(function (x) { return x.unsubscribe(); });
              this.queries.delete(queryId);
          };
          QueryManager.prototype.getCurrentQueryResult = function (observableQuery, optimistic) {
              if (optimistic === void 0) { optimistic = true; }
              var _a = observableQuery.options, variables = _a.variables, query = _a.query;
              var lastResult = observableQuery.getLastResult();
              var newData = this.getQuery(observableQuery.queryId).newData;
              if (newData) {
                  return { data: newData.result, partial: false };
              }
              else {
                  try {
                      var data = this.dataStore.getCache().read({
                          query: query,
                          variables: variables,
                          previousResult: lastResult ? lastResult.data : undefined,
                          optimistic: optimistic,
                      });
                      return { data: data, partial: false };
                  }
                  catch (e) {
                      return { data: {}, partial: true };
                  }
              }
          };
          QueryManager.prototype.getQueryWithPreviousResult = function (queryIdOrObservable) {
              var observableQuery;
              if (typeof queryIdOrObservable === 'string') {
                  var foundObserveableQuery = this.getQuery(queryIdOrObservable).observableQuery;
                  if (!foundObserveableQuery) {
                      throw new Error("ObservableQuery with this id doesn't exist: " + queryIdOrObservable);
                  }
                  observableQuery = foundObserveableQuery;
              }
              else {
                  observableQuery = queryIdOrObservable;
              }
              var _a = observableQuery.options, variables = _a.variables, query = _a.query;
              var data = this.getCurrentQueryResult(observableQuery, false).data;
              return {
                  previousResult: data,
                  variables: variables,
                  document: query,
              };
          };
          QueryManager.prototype.broadcastQueries = function () {
              var _this = this;
              this.onBroadcast();
              this.queries.forEach(function (info, id) {
                  if (!info.invalidated || !info.listeners)
                      return;
                  info.listeners
                      .filter(function (x) { return !!x; })
                      .forEach(function (listener) {
                      listener(_this.queryStore.get(id), info.newData);
                  });
              });
          };
          QueryManager.prototype.getObservableQueryPromises = function (includeStandby) {
              var _this = this;
              var observableQueryPromises = [];
              this.queries.forEach(function (_a, queryId) {
                  var observableQuery = _a.observableQuery;
                  if (!observableQuery)
                      return;
                  var fetchPolicy = observableQuery.options.fetchPolicy;
                  observableQuery.resetLastResults();
                  if (fetchPolicy !== 'cache-only' &&
                      (includeStandby || fetchPolicy !== 'standby')) {
                      observableQueryPromises.push(observableQuery.refetch());
                  }
                  _this.setQuery(queryId, function () { return ({ newData: null }); });
                  _this.invalidate(true, queryId);
              });
              return observableQueryPromises;
          };
          QueryManager.prototype.fetchRequest = function (_a) {
              var _this = this;
              var requestId = _a.requestId, queryId = _a.queryId, document = _a.document, options = _a.options, fetchMoreForQueryId = _a.fetchMoreForQueryId;
              var variables = options.variables, context = options.context, _b = options.errorPolicy, errorPolicy = _b === void 0 ? 'none' : _b, fetchPolicy = options.fetchPolicy;
              var operation = this.buildOperationForLink(document, variables, __assign$4({}, context, { forceFetch: !this.queryDeduplication }));
              var resultFromStore;
              var errorsFromStore;
              return new Promise(function (resolve, reject) {
                  _this.addFetchQueryPromise(requestId, resolve, reject);
                  var subscription = execute(_this.deduplicator, operation).subscribe({
                      next: function (result) {
                          var lastRequestId = _this.getQuery(queryId).lastRequestId;
                          if (requestId >= (lastRequestId || 1)) {
                              if (fetchPolicy !== 'no-cache') {
                                  try {
                                      _this.dataStore.markQueryResult(result, document, variables, fetchMoreForQueryId, errorPolicy === 'ignore' || errorPolicy === 'all');
                                  }
                                  catch (e) {
                                      reject(e);
                                      return;
                                  }
                              }
                              else {
                                  _this.setQuery(queryId, function () { return ({
                                      newData: { result: result.data, complete: true },
                                  }); });
                              }
                              _this.queryStore.markQueryResult(queryId, result, fetchMoreForQueryId);
                              _this.invalidate(true, queryId, fetchMoreForQueryId);
                              _this.broadcastQueries();
                          }
                          if (result.errors && errorPolicy === 'none') {
                              reject(new ApolloError({
                                  graphQLErrors: result.errors,
                              }));
                              return;
                          }
                          else if (errorPolicy === 'all') {
                              errorsFromStore = result.errors;
                          }
                          if (fetchMoreForQueryId || fetchPolicy === 'no-cache') {
                              resultFromStore = result.data;
                          }
                          else {
                              try {
                                  resultFromStore = _this.dataStore.getCache().read({
                                      variables: variables,
                                      query: document,
                                      optimistic: false,
                                  });
                              }
                              catch (e) { }
                          }
                      },
                      error: function (error) {
                          _this.removeFetchQueryPromise(requestId);
                          _this.setQuery(queryId, function (_a) {
                              var subscriptions = _a.subscriptions;
                              return ({
                                  subscriptions: subscriptions.filter(function (x) { return x !== subscription; }),
                              });
                          });
                          reject(error);
                      },
                      complete: function () {
                          _this.removeFetchQueryPromise(requestId);
                          _this.setQuery(queryId, function (_a) {
                              var subscriptions = _a.subscriptions;
                              return ({
                                  subscriptions: subscriptions.filter(function (x) { return x !== subscription; }),
                              });
                          });
                          resolve({
                              data: resultFromStore,
                              errors: errorsFromStore,
                              loading: false,
                              networkStatus: exports.NetworkStatus.ready,
                              stale: false,
                          });
                      },
                  });
                  _this.setQuery(queryId, function (_a) {
                      var subscriptions = _a.subscriptions;
                      return ({
                          subscriptions: subscriptions.concat([subscription]),
                      });
                  });
              });
          };
          QueryManager.prototype.refetchQueryByName = function (queryName) {
              var _this = this;
              var refetchedQueries = this.queryIdsByName[queryName];
              if (refetchedQueries === undefined)
                  return;
              return Promise.all(refetchedQueries
                  .map(function (id) { return _this.getQuery(id).observableQuery; })
                  .filter(function (x) { return !!x; })
                  .map(function (x) { return x.refetch(); }));
          };
          QueryManager.prototype.generateRequestId = function () {
              var requestId = this.idCounter;
              this.idCounter++;
              return requestId;
          };
          QueryManager.prototype.getQuery = function (queryId) {
              return this.queries.get(queryId) || __assign$4({}, defaultQueryInfo);
          };
          QueryManager.prototype.setQuery = function (queryId, updater) {
              var prev = this.getQuery(queryId);
              var newInfo = __assign$4({}, prev, updater(prev));
              this.queries.set(queryId, newInfo);
          };
          QueryManager.prototype.invalidate = function (invalidated, queryId, fetchMoreForQueryId) {
              if (queryId)
                  this.setQuery(queryId, function () { return ({ invalidated: invalidated }); });
              if (fetchMoreForQueryId) {
                  this.setQuery(fetchMoreForQueryId, function () { return ({ invalidated: invalidated }); });
              }
          };
          QueryManager.prototype.buildOperationForLink = function (document, variables, extraContext) {
              var cache = this.dataStore.getCache();
              return {
                  query: cache.transformForLink
                      ? cache.transformForLink(document)
                      : document,
                  variables: variables,
                  operationName: apolloUtilities.getOperationName(document) || undefined,
                  context: __assign$4({}, extraContext, { cache: cache, getCacheKey: function (obj) {
                          if (cache.config) {
                              return cache.config.dataIdFromObject(obj);
                          }
                          else {
                              throw new Error('To use context.getCacheKey, you need to use a cache that has a configurable dataIdFromObject, like apollo-cache-inmemory.');
                          }
                      } }),
              };
          };
          return QueryManager;
      }());
  
      var DataStore = (function () {
          function DataStore(initialCache) {
              this.cache = initialCache;
          }
          DataStore.prototype.getCache = function () {
              return this.cache;
          };
          DataStore.prototype.markQueryResult = function (result, document, variables, fetchMoreForQueryId, ignoreErrors) {
              if (ignoreErrors === void 0) { ignoreErrors = false; }
              var writeWithErrors = !apolloUtilities.graphQLResultHasError(result);
              if (ignoreErrors && apolloUtilities.graphQLResultHasError(result) && result.data) {
                  writeWithErrors = true;
              }
              if (!fetchMoreForQueryId && writeWithErrors) {
                  this.cache.write({
                      result: result.data,
                      dataId: 'ROOT_QUERY',
                      query: document,
                      variables: variables,
                  });
              }
          };
          DataStore.prototype.markSubscriptionResult = function (result, document, variables) {
              if (!apolloUtilities.graphQLResultHasError(result)) {
                  this.cache.write({
                      result: result.data,
                      dataId: 'ROOT_SUBSCRIPTION',
                      query: document,
                      variables: variables,
                  });
              }
          };
          DataStore.prototype.markMutationInit = function (mutation) {
              var _this = this;
              if (mutation.optimisticResponse) {
                  var optimistic_1;
                  if (typeof mutation.optimisticResponse === 'function') {
                      optimistic_1 = mutation.optimisticResponse(mutation.variables);
                  }
                  else {
                      optimistic_1 = mutation.optimisticResponse;
                  }
                  var changeFn_1 = function () {
                      _this.markMutationResult({
                          mutationId: mutation.mutationId,
                          result: { data: optimistic_1 },
                          document: mutation.document,
                          variables: mutation.variables,
                          updateQueries: mutation.updateQueries,
                          update: mutation.update,
                      });
                  };
                  this.cache.recordOptimisticTransaction(function (c) {
                      var orig = _this.cache;
                      _this.cache = c;
                      try {
                          changeFn_1();
                      }
                      finally {
                          _this.cache = orig;
                      }
                  }, mutation.mutationId);
              }
          };
          DataStore.prototype.markMutationResult = function (mutation) {
              var _this = this;
              if (!apolloUtilities.graphQLResultHasError(mutation.result)) {
                  var cacheWrites_1 = [];
                  cacheWrites_1.push({
                      result: mutation.result.data,
                      dataId: 'ROOT_MUTATION',
                      query: mutation.document,
                      variables: mutation.variables,
                  });
                  if (mutation.updateQueries) {
                      Object.keys(mutation.updateQueries)
                          .filter(function (id) { return mutation.updateQueries[id]; })
                          .forEach(function (queryId) {
                          var _a = mutation.updateQueries[queryId], query = _a.query, updater = _a.updater;
                          var _b = _this.cache.diff({
                              query: query.document,
                              variables: query.variables,
                              returnPartialData: true,
                              optimistic: false,
                          }), currentQueryResult = _b.result, complete = _b.complete;
                          if (!complete) {
                              return;
                          }
                          var nextQueryResult = apolloUtilities.tryFunctionOrLogError(function () {
                              return updater(currentQueryResult, {
                                  mutationResult: mutation.result,
                                  queryName: apolloUtilities.getOperationName(query.document) || undefined,
                                  queryVariables: query.variables,
                              });
                          });
                          if (nextQueryResult) {
                              cacheWrites_1.push({
                                  result: nextQueryResult,
                                  dataId: 'ROOT_QUERY',
                                  query: query.document,
                                  variables: query.variables,
                              });
                          }
                      });
                  }
                  this.cache.performTransaction(function (c) {
                      cacheWrites_1.forEach(function (write) { return c.write(write); });
                  });
                  var update_1 = mutation.update;
                  if (update_1) {
                      this.cache.performTransaction(function (c) {
                          apolloUtilities.tryFunctionOrLogError(function () { return update_1(c, mutation.result); });
                      });
                  }
              }
          };
          DataStore.prototype.markMutationComplete = function (_a) {
              var mutationId = _a.mutationId, optimisticResponse = _a.optimisticResponse;
              if (!optimisticResponse)
                  return;
              this.cache.removeOptimistic(mutationId);
          };
          DataStore.prototype.markUpdateQueryResult = function (document, variables, newResult) {
              this.cache.write({
                  result: newResult,
                  dataId: 'ROOT_QUERY',
                  variables: variables,
                  query: document,
              });
          };
          DataStore.prototype.reset = function () {
              return this.cache.reset();
          };
          return DataStore;
      }());
  
      var version = 'local';
  
      var __assign$5 = (undefined && undefined.__assign) || function () {
          __assign$5 = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$5.apply(this, arguments);
      };
      var hasSuggestedDevtools = false;
      var supportedDirectives = new ApolloLink(function (operation, forward) {
          operation.query = apolloUtilities.removeConnectionDirectiveFromDocument(operation.query);
          return forward(operation);
      });
      var ApolloClient = (function () {
          function ApolloClient(options) {
              var _this = this;
              this.defaultOptions = {};
              this.resetStoreCallbacks = [];
              var link = options.link, cache = options.cache, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, connectToDevTools = options.connectToDevTools, _c = options.queryDeduplication, queryDeduplication = _c === void 0 ? true : _c, defaultOptions = options.defaultOptions;
              if (!link || !cache) {
                  throw new Error("\n        In order to initialize Apollo Client, you must specify link & cache properties on the config object.\n        This is part of the required upgrade when migrating from Apollo Client 1.0 to Apollo Client 2.0.\n        For more information, please visit:\n          https://www.apollographql.com/docs/react/basics/setup.html\n        to help you get started.\n      ");
              }
              this.link = supportedDirectives.concat(link);
              this.cache = cache;
              this.store = new DataStore(cache);
              this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
              this.queryDeduplication = queryDeduplication;
              this.ssrMode = ssrMode;
              this.defaultOptions = defaultOptions || {};
              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);
              var defaultConnectToDevTools = !apolloUtilities.isProduction() &&
                  typeof window !== 'undefined' &&
                  !window.__APOLLO_CLIENT__;
              if (typeof connectToDevTools === 'undefined'
                  ? defaultConnectToDevTools
                  : connectToDevTools && typeof window !== 'undefined') {
                  window.__APOLLO_CLIENT__ = this;
              }
              if (!hasSuggestedDevtools && !apolloUtilities.isProduction()) {
                  hasSuggestedDevtools = true;
                  if (typeof window !== 'undefined' &&
                      window.document &&
                      window.top === window.self) {
                      if (typeof window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
                          if (window.navigator &&
                              window.navigator.userAgent.indexOf('Chrome') > -1) {
                              console.debug('Download the Apollo DevTools ' +
                                  'for a better development experience: ' +
                                  'https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm');
                          }
                      }
                  }
              }
              this.version = version;
          }
          ApolloClient.prototype.watchQuery = function (options) {
              if (this.defaultOptions.watchQuery) {
                  options = __assign$5({}, this.defaultOptions.watchQuery, options);
              }
              if (this.disableNetworkFetches &&
                  (options.fetchPolicy === 'network-only' ||
                      options.fetchPolicy === 'cache-and-network')) {
                  options = __assign$5({}, options, { fetchPolicy: 'cache-first' });
              }
              return this.initQueryManager().watchQuery(options);
          };
          ApolloClient.prototype.query = function (options) {
              if (this.defaultOptions.query) {
                  options = __assign$5({}, this.defaultOptions.query, options);
              }
              if (options.fetchPolicy === 'cache-and-network') {
                  throw new Error('cache-and-network fetchPolicy can only be used with watchQuery');
              }
              if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
                  options = __assign$5({}, options, { fetchPolicy: 'cache-first' });
              }
              return this.initQueryManager().query(options);
          };
          ApolloClient.prototype.mutate = function (options) {
              if (this.defaultOptions.mutate) {
                  options = __assign$5({}, this.defaultOptions.mutate, options);
              }
              return this.initQueryManager().mutate(options);
          };
          ApolloClient.prototype.subscribe = function (options) {
              return this.initQueryManager().startGraphQLSubscription(options);
          };
          ApolloClient.prototype.readQuery = function (options, optimistic) {
              if (optimistic === void 0) { optimistic = false; }
              return this.initProxy().readQuery(options, optimistic);
          };
          ApolloClient.prototype.readFragment = function (options, optimistic) {
              if (optimistic === void 0) { optimistic = false; }
              return this.initProxy().readFragment(options, optimistic);
          };
          ApolloClient.prototype.writeQuery = function (options) {
              var result = this.initProxy().writeQuery(options);
              this.initQueryManager().broadcastQueries();
              return result;
          };
          ApolloClient.prototype.writeFragment = function (options) {
              var result = this.initProxy().writeFragment(options);
              this.initQueryManager().broadcastQueries();
              return result;
          };
          ApolloClient.prototype.writeData = function (options) {
              var result = this.initProxy().writeData(options);
              this.initQueryManager().broadcastQueries();
              return result;
          };
          ApolloClient.prototype.__actionHookForDevTools = function (cb) {
              this.devToolsHookCb = cb;
          };
          ApolloClient.prototype.__requestRaw = function (payload) {
              return execute(this.link, payload);
          };
          ApolloClient.prototype.initQueryManager = function () {
              var _this = this;
              if (!this.queryManager) {
                  this.queryManager = new QueryManager({
                      link: this.link,
                      store: this.store,
                      queryDeduplication: this.queryDeduplication,
                      ssrMode: this.ssrMode,
                      onBroadcast: function () {
                          if (_this.devToolsHookCb) {
                              _this.devToolsHookCb({
                                  action: {},
                                  state: {
                                      queries: _this.queryManager
                                          ? _this.queryManager.queryStore.getStore()
                                          : {},
                                      mutations: _this.queryManager
                                          ? _this.queryManager.mutationStore.getStore()
                                          : {},
                                  },
                                  dataWithOptimisticResults: _this.cache.extract(true),
                              });
                          }
                      },
                  });
              }
              return this.queryManager;
          };
          ApolloClient.prototype.resetStore = function () {
              var _this = this;
              return Promise.resolve()
                  .then(function () {
                  return _this.queryManager
                      ? _this.queryManager.clearStore()
                      : Promise.resolve(null);
              })
                  .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
                  .then(function () {
                  return _this.queryManager && _this.queryManager.reFetchObservableQueries
                      ? _this.queryManager.reFetchObservableQueries()
                      : Promise.resolve(null);
              });
          };
          ApolloClient.prototype.clearStore = function () {
              var queryManager = this.queryManager;
              return Promise.resolve().then(function () {
                  return queryManager ? queryManager.clearStore() : Promise.resolve(null);
              });
          };
          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.reFetchObservableQueries = function (includeStandby) {
              return this.queryManager
                  ? this.queryManager.reFetchObservableQueries(includeStandby)
                  : Promise.resolve(null);
          };
          ApolloClient.prototype.extract = function (optimistic) {
              return this.initProxy().extract(optimistic);
          };
          ApolloClient.prototype.restore = function (serializedState) {
              return this.initProxy().restore(serializedState);
          };
          ApolloClient.prototype.initProxy = function () {
              if (!this.proxy) {
                  this.initQueryManager();
                  this.proxy = this.cache;
              }
              return this.proxy;
          };
          return ApolloClient;
      }());
  
      var Observable$2 = zenObservable;
  
      var __extends$5 = (undefined && undefined.__extends) || (function () {
          var extendStatics = Object.setPrototypeOf ||
              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
              function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var __assign$6 = (undefined && undefined.__assign) || Object.assign || function(t) {
          for (var s, i = 1, n = arguments.length; i < n; i++) {
              s = arguments[i];
              for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                  t[p] = s[p];
          }
          return t;
      };
      function validateOperation$1(operation) {
          var OPERATION_FIELDS = [
              'query',
              'operationName',
              'variables',
              'extensions',
              'context',
          ];
          for (var _i = 0, _a = Object.keys(operation); _i < _a.length; _i++) {
              var key = _a[_i];
              if (OPERATION_FIELDS.indexOf(key) < 0) {
                  throw new Error("illegal argument: " + key);
              }
          }
          return operation;
      }
      var LinkError$1 = /** @class */ (function (_super) {
          __extends$5(LinkError, _super);
          function LinkError(message, link) {
              var _this = _super.call(this, message) || this;
              _this.link = link;
              return _this;
          }
          return LinkError;
      }(Error));
      function isTerminating$1(link) {
          return link.request.length <= 1;
      }
      function toPromise$1(observable) {
          var completed = false;
          return new Promise(function (resolve, reject) {
              observable.subscribe({
                  next: function (data) {
                      if (completed) {
                          console.warn("Promise Wrapper does not support multiple results from Observable");
                      }
                      else {
                          completed = true;
                          resolve(data);
                      }
                  },
                  error: reject,
              });
          });
      }
      // backwards compat
      var makePromise$1 = toPromise$1;
      function fromPromise$1(promise) {
          return new Observable$2(function (observer) {
              promise
                  .then(function (value) {
                  observer.next(value);
                  observer.complete();
              })
                  .catch(observer.error.bind(observer));
          });
      }
      function fromError$1(errorValue) {
          return new Observable$2(function (observer) {
              observer.error(errorValue);
          });
      }
      function transformOperation$1(operation) {
          var transformedOperation = {
              variables: operation.variables || {},
              extensions: operation.extensions || {},
              operationName: operation.operationName,
              query: operation.query,
          };
          // best guess at an operation name
          if (!transformedOperation.operationName) {
              transformedOperation.operationName =
                  typeof transformedOperation.query !== 'string'
                      ? apolloUtilities.getOperationName(transformedOperation.query)
                      : '';
          }
          return transformedOperation;
      }
      function createOperation$1(starting, operation) {
          var context = __assign$6({}, starting);
          var setContext = function (next) {
              if (typeof next === 'function') {
                  context = __assign$6({}, context, next(context));
              }
              else {
                  context = __assign$6({}, context, next);
              }
          };
          var getContext = function () { return (__assign$6({}, context)); };
          Object.defineProperty(operation, 'setContext', {
              enumerable: false,
              value: setContext,
          });
          Object.defineProperty(operation, 'getContext', {
              enumerable: false,
              value: getContext,
          });
          Object.defineProperty(operation, 'toKey', {
              enumerable: false,
              value: function () { return getKey$1(operation); },
          });
          return operation;
      }
      function getKey$1(operation) {
          // XXX we're assuming here that variables will be serialized in the same order.
          // that might not always be true
          return printer.print(operation.query) + "|" + JSON.stringify(operation.variables) + "|" + operation.operationName;
      }
  
      var passthrough$1 = function (op, forward) { return (forward ? forward(op) : Observable$2.of()); };
      var toLink$1 = function (handler) {
          return typeof handler === 'function' ? new ApolloLink$1(handler) : handler;
      };
      var empty$1 = function () {
          return new ApolloLink$1(function (op, forward) { return Observable$2.of(); });
      };
      var from$1 = function (links) {
          if (links.length === 0)
              return empty$1();
          return links.map(toLink$1).reduce(function (x, y) { return x.concat(y); });
      };
      var split$1 = function (test, left, right) {
          if (right === void 0) { right = new ApolloLink$1(passthrough$1); }
          var leftLink = toLink$1(left);
          var rightLink = toLink$1(right);
          if (isTerminating$1(leftLink) && isTerminating$1(rightLink)) {
              return new ApolloLink$1(function (operation) {
                  return test(operation)
                      ? leftLink.request(operation) || Observable$2.of()
                      : rightLink.request(operation) || Observable$2.of();
              });
          }
          else {
              return new ApolloLink$1(function (operation, forward) {
                  return test(operation)
                      ? leftLink.request(operation, forward) || Observable$2.of()
                      : rightLink.request(operation, forward) || Observable$2.of();
              });
          }
      };
      // join two Links together
      var concat$1 = function (first, second) {
          var firstLink = toLink$1(first);
          if (isTerminating$1(firstLink)) {
              console.warn(new LinkError$1("You are calling concat on a terminating link, which will have no effect", firstLink));
              return firstLink;
          }
          var nextLink = toLink$1(second);
          if (isTerminating$1(nextLink)) {
              return new ApolloLink$1(function (operation) {
                  return firstLink.request(operation, function (op) { return nextLink.request(op) || Observable$2.of(); }) || Observable$2.of();
              });
          }
          else {
              return new ApolloLink$1(function (operation, forward) {
                  return (firstLink.request(operation, function (op) {
                      return nextLink.request(op, forward) || Observable$2.of();
                  }) || Observable$2.of());
              });
          }
      };
      var ApolloLink$1 = /** @class */ (function () {
          function ApolloLink(request) {
              if (request)
                  this.request = request;
          }
          ApolloLink.prototype.split = function (test, left, right) {
              if (right === void 0) { right = new ApolloLink(passthrough$1); }
              return this.concat(split$1(test, left, right));
          };
          ApolloLink.prototype.concat = function (next) {
              return concat$1(this, next);
          };
          ApolloLink.prototype.request = function (operation, forward) {
              throw new Error('request is not implemented');
          };
          ApolloLink.empty = empty$1;
          ApolloLink.from = from$1;
          ApolloLink.split = split$1;
          ApolloLink.execute = execute$1;
          return ApolloLink;
      }());
      function execute$1(link, operation) {
          return (link.request(createOperation$1(operation.context, transformOperation$1(validateOperation$1(operation)))) || Observable$2.of());
      }
  
      function queryFromPojo(obj) {
          var op = {
              kind: 'OperationDefinition',
              operation: 'query',
              name: {
                  kind: 'Name',
                  value: 'GeneratedClientQuery',
              },
              selectionSet: selectionSetFromObj(obj),
          };
          var out = {
              kind: 'Document',
              definitions: [op],
          };
          return out;
      }
      function fragmentFromPojo(obj, typename) {
          var frag = {
              kind: 'FragmentDefinition',
              typeCondition: {
                  kind: 'NamedType',
                  name: {
                      kind: 'Name',
                      value: typename || '__FakeType',
                  },
              },
              name: {
                  kind: 'Name',
                  value: 'GeneratedClientQuery',
              },
              selectionSet: selectionSetFromObj(obj),
          };
          var out = {
              kind: 'Document',
              definitions: [frag],
          };
          return out;
      }
      function selectionSetFromObj(obj) {
          if (typeof obj === 'number' ||
              typeof obj === 'boolean' ||
              typeof obj === 'string' ||
              typeof obj === 'undefined' ||
              obj === null) {
              return null;
          }
          if (Array.isArray(obj)) {
              return selectionSetFromObj(obj[0]);
          }
          var selections = [];
          Object.keys(obj).forEach(function (key) {
              var field = {
                  kind: 'Field',
                  name: {
                      kind: 'Name',
                      value: key,
                  },
              };
              var nestedSelSet = selectionSetFromObj(obj[key]);
              if (nestedSelSet) {
                  field.selectionSet = nestedSelSet;
              }
              selections.push(field);
          });
          var selectionSet = {
              kind: 'SelectionSet',
              selections: selections,
          };
          return selectionSet;
      }
      var justTypenameQuery = {
          kind: 'Document',
          definitions: [
              {
                  kind: 'OperationDefinition',
                  operation: 'query',
                  name: null,
                  variableDefinitions: null,
                  directives: [],
                  selectionSet: {
                      kind: 'SelectionSet',
                      selections: [
                          {
                              kind: 'Field',
                              alias: null,
                              name: {
                                  kind: 'Name',
                                  value: '__typename',
                              },
                              arguments: [],
                              directives: [],
                              selectionSet: null,
                          },
                      ],
                  },
              },
          ],
      };
  
      var ApolloCache = (function () {
          function ApolloCache() {
          }
          ApolloCache.prototype.transformDocument = function (document) {
              return document;
          };
          ApolloCache.prototype.transformForLink = function (document) {
              return document;
          };
          ApolloCache.prototype.readQuery = function (options, optimistic) {
              if (optimistic === void 0) { optimistic = false; }
              return this.read({
                  query: options.query,
                  variables: options.variables,
                  optimistic: optimistic,
              });
          };
          ApolloCache.prototype.readFragment = function (options, optimistic) {
              if (optimistic === void 0) { optimistic = false; }
              return this.read({
                  query: apolloUtilities.getFragmentQueryDocument(options.fragment, options.fragmentName),
                  variables: options.variables,
                  rootId: options.id,
                  optimistic: optimistic,
              });
          };
          ApolloCache.prototype.writeQuery = function (options) {
              this.write({
                  dataId: 'ROOT_QUERY',
                  result: options.data,
                  query: options.query,
                  variables: options.variables,
              });
          };
          ApolloCache.prototype.writeFragment = function (options) {
              this.write({
                  dataId: options.id,
                  result: options.data,
                  variables: options.variables,
                  query: apolloUtilities.getFragmentQueryDocument(options.fragment, options.fragmentName),
              });
          };
          ApolloCache.prototype.writeData = function (_a) {
              var id = _a.id, data = _a.data;
              if (typeof id !== 'undefined') {
                  var typenameResult = null;
                  try {
                      typenameResult = this.read({
                          rootId: id,
                          optimistic: false,
                          query: justTypenameQuery,
                      });
                  }
                  catch (e) {
                  }
                  var __typename = (typenameResult && typenameResult.__typename) || '__ClientData';
                  var dataToWrite = Object.assign({ __typename: __typename }, data);
                  this.writeFragment({
                      id: id,
                      fragment: fragmentFromPojo(dataToWrite, __typename),
                      data: dataToWrite,
                  });
              }
              else {
                  this.writeQuery({ query: queryFromPojo(data), data: data });
              }
          };
          return ApolloCache;
      }());
  
      var haveWarned = false;
      var HeuristicFragmentMatcher = (function () {
          function HeuristicFragmentMatcher() {
          }
          HeuristicFragmentMatcher.prototype.ensureReady = function () {
              return Promise.resolve();
          };
          HeuristicFragmentMatcher.prototype.canBypassInit = function () {
              return true;
          };
          HeuristicFragmentMatcher.prototype.match = function (idValue, typeCondition, context) {
              var obj = context.store.get(idValue.id);
              if (!obj && idValue.id === 'ROOT_QUERY') {
                  return true;
              }
              if (!obj) {
                  return false;
              }
              if (!obj.__typename) {
                  if (!haveWarned) {
                      console.warn("You're using fragments in your queries, but either don't have the addTypename:\n  true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename.\n   Please turn on the addTypename option and include __typename when writing fragments so that Apollo Client\n   can accurately match fragments.");
                      console.warn('Could not find __typename on Fragment ', typeCondition, obj);
                      console.warn("DEPRECATION WARNING: using fragments without __typename is unsupported behavior " +
                          "and will be removed in future versions of Apollo client. You should fix this and set addTypename to true now.");
                      if (!apolloUtilities.isTest()) {
                          haveWarned = true;
                      }
                  }
                  context.returnPartialData = true;
                  return true;
              }
              if (obj.__typename === typeCondition) {
                  return true;
              }
              apolloUtilities.warnOnceInDevelopment('You are using the simple (heuristic) fragment matcher, but your ' +
                  'queries contain union or interface types. Apollo Client will not be ' +
                  'able to accurately map fragments. To make this error go away, use ' +
                  'the `IntrospectionFragmentMatcher` as described in the docs: ' +
                  'https://www.apollographql.com/docs/react/recipes/fragment-matching.html', 'error');
              context.returnPartialData = true;
              return true;
          };
          return HeuristicFragmentMatcher;
      }());
      var IntrospectionFragmentMatcher = (function () {
          function IntrospectionFragmentMatcher(options) {
              if (options && options.introspectionQueryResultData) {
                  this.possibleTypesMap = this.parseIntrospectionResult(options.introspectionQueryResultData);
                  this.isReady = true;
              }
              else {
                  this.isReady = false;
              }
              this.match = this.match.bind(this);
          }
          IntrospectionFragmentMatcher.prototype.match = function (idValue, typeCondition, context) {
              if (!this.isReady) {
                  throw new Error('FragmentMatcher.match() was called before FragmentMatcher.init()');
              }
              var obj = context.store.get(idValue.id);
              if (!obj) {
                  return false;
              }
              if (!obj.__typename) {
                  throw new Error("Cannot match fragment because __typename property is missing: " + JSON.stringify(obj));
              }
              if (obj.__typename === typeCondition) {
                  return true;
              }
              var implementingTypes = this.possibleTypesMap[typeCondition];
              if (implementingTypes && implementingTypes.indexOf(obj.__typename) > -1) {
                  return true;
              }
              return false;
          };
          IntrospectionFragmentMatcher.prototype.parseIntrospectionResult = function (introspectionResultData) {
              var typeMap = {};
              introspectionResultData.__schema.types.forEach(function (type) {
                  if (type.kind === 'UNION' || type.kind === 'INTERFACE') {
                      typeMap[type.name] = type.possibleTypes.map(function (implementingType) { return implementingType.name; });
                  }
              });
              return typeMap;
          };
          return IntrospectionFragmentMatcher;
      }());
  
      var ObjectCache = (function () {
          function ObjectCache(data) {
              if (data === void 0) { data = Object.create(null); }
              this.data = data;
          }
          ObjectCache.prototype.toObject = function () {
              return this.data;
          };
          ObjectCache.prototype.get = function (dataId) {
              return this.data[dataId];
          };
          ObjectCache.prototype.set = function (dataId, value) {
              this.data[dataId] = value;
          };
          ObjectCache.prototype.delete = function (dataId) {
              this.data[dataId] = undefined;
          };
          ObjectCache.prototype.clear = function () {
              this.data = Object.create(null);
          };
          ObjectCache.prototype.replace = function (newData) {
              this.data = newData || Object.create(null);
          };
          return ObjectCache;
      }());
      function defaultNormalizedCacheFactory(seed) {
          return new ObjectCache(seed);
      }
  
      var __extends$6 = (undefined && undefined.__extends) || (function () {
          var extendStatics = function (d, b) {
              extendStatics = Object.setPrototypeOf ||
                  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                  function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
              return extendStatics(d, b);
          };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var __assign$7 = (undefined && undefined.__assign) || function () {
          __assign$7 = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$7.apply(this, arguments);
      };
      var WriteError = (function (_super) {
          __extends$6(WriteError, _super);
          function WriteError() {
              var _this = _super !== null && _super.apply(this, arguments) || this;
              _this.type = 'WriteError';
              return _this;
          }
          return WriteError;
      }(Error));
      function enhanceErrorWithDocument(error, document) {
          var enhancedError = new WriteError("Error writing result to store for query:\n " + printer.print(document));
          enhancedError.message += '\n' + error.message;
          enhancedError.stack = error.stack;
          return enhancedError;
      }
      function writeQueryToStore(_a) {
          var result = _a.result, query = _a.query, _b = _a.storeFactory, storeFactory = _b === void 0 ? defaultNormalizedCacheFactory : _b, _c = _a.store, store = _c === void 0 ? storeFactory() : _c, variables = _a.variables, dataIdFromObject = _a.dataIdFromObject, _d = _a.fragmentMap, fragmentMap = _d === void 0 ? {} : _d, fragmentMatcherFunction = _a.fragmentMatcherFunction;
          var queryDefinition = apolloUtilities.getQueryDefinition(query);
          variables = apolloUtilities.assign({}, apolloUtilities.getDefaultValues(queryDefinition), variables);
          try {
              return writeSelectionSetToStore({
                  dataId: 'ROOT_QUERY',
                  result: result,
                  selectionSet: queryDefinition.selectionSet,
                  context: {
                      store: store,
                      storeFactory: storeFactory,
                      processedData: {},
                      variables: variables,
                      dataIdFromObject: dataIdFromObject,
                      fragmentMap: fragmentMap,
                      fragmentMatcherFunction: fragmentMatcherFunction,
                  },
              });
          }
          catch (e) {
              throw enhanceErrorWithDocument(e, query);
          }
      }
      function writeResultToStore(_a) {
          var dataId = _a.dataId, result = _a.result, document = _a.document, _b = _a.storeFactory, storeFactory = _b === void 0 ? defaultNormalizedCacheFactory : _b, _c = _a.store, store = _c === void 0 ? storeFactory() : _c, variables = _a.variables, dataIdFromObject = _a.dataIdFromObject, fragmentMatcherFunction = _a.fragmentMatcherFunction;
          var operationDefinition = apolloUtilities.getOperationDefinition(document);
          var selectionSet = operationDefinition.selectionSet;
          var fragmentMap = apolloUtilities.createFragmentMap(apolloUtilities.getFragmentDefinitions(document));
          variables = apolloUtilities.assign({}, apolloUtilities.getDefaultValues(operationDefinition), variables);
          try {
              return writeSelectionSetToStore({
                  result: result,
                  dataId: dataId,
                  selectionSet: selectionSet,
                  context: {
                      store: store,
                      storeFactory: storeFactory,
                      processedData: {},
                      variables: variables,
                      dataIdFromObject: dataIdFromObject,
                      fragmentMap: fragmentMap,
                      fragmentMatcherFunction: fragmentMatcherFunction,
                  },
              });
          }
          catch (e) {
              throw enhanceErrorWithDocument(e, document);
          }
      }
      function writeSelectionSetToStore(_a) {
          var result = _a.result, dataId = _a.dataId, selectionSet = _a.selectionSet, context = _a.context;
          var variables = context.variables, store = context.store, fragmentMap = context.fragmentMap;
          selectionSet.selections.forEach(function (selection) {
              var included = apolloUtilities.shouldInclude(selection, variables);
              if (apolloUtilities.isField(selection)) {
                  var resultFieldKey = apolloUtilities.resultKeyNameFromField(selection);
                  var value = result[resultFieldKey];
                  if (included) {
                      if (typeof value !== 'undefined') {
                          writeFieldToStore({
                              dataId: dataId,
                              value: value,
                              field: selection,
                              context: context,
                          });
                      }
                      else {
                          var isDefered = selection.directives &&
                              selection.directives.length &&
                              selection.directives.some(function (directive) { return directive.name && directive.name.value === 'defer'; });
                          if (!isDefered && context.fragmentMatcherFunction) {
                              if (!apolloUtilities.isProduction()) {
                                  console.warn("Missing field " + resultFieldKey + " in " + JSON.stringify(result, null, 2).substring(0, 100));
                              }
                          }
                      }
                  }
              }
              else {
                  var fragment = void 0;
                  if (apolloUtilities.isInlineFragment(selection)) {
                      fragment = selection;
                  }
                  else {
                      fragment = (fragmentMap || {})[selection.name.value];
                      if (!fragment) {
                          throw new Error("No fragment named " + selection.name.value + ".");
                      }
                  }
                  var matches = true;
                  if (context.fragmentMatcherFunction && fragment.typeCondition) {
                      var idValue = apolloUtilities.toIdValue({ id: 'self', typename: undefined });
                      var fakeContext = {
                          store: new ObjectCache({ self: result }),
                          returnPartialData: false,
                          hasMissingField: false,
                          cacheRedirects: {},
                      };
                      matches = context.fragmentMatcherFunction(idValue, fragment.typeCondition.name.value, fakeContext);
                      if (!apolloUtilities.isProduction() && fakeContext.returnPartialData) {
                          console.error('WARNING: heuristic fragment matching going on!');
                      }
                  }
                  if (included && matches) {
                      writeSelectionSetToStore({
                          result: result,
                          selectionSet: fragment.selectionSet,
                          dataId: dataId,
                          context: context,
                      });
                  }
              }
          });
          return store;
      }
      function isGeneratedId(id) {
          return id[0] === '$';
      }
      function mergeWithGenerated(generatedKey, realKey, cache) {
          var generated = cache.get(generatedKey);
          var real = cache.get(realKey);
          Object.keys(generated).forEach(function (key) {
              var value = generated[key];
              var realValue = real[key];
              if (apolloUtilities.isIdValue(value) && isGeneratedId(value.id) && apolloUtilities.isIdValue(realValue)) {
                  mergeWithGenerated(value.id, realValue.id, cache);
              }
              cache.delete(generatedKey);
              cache.set(realKey, __assign$7({}, generated, real));
          });
      }
      function isDataProcessed(dataId, field, processedData) {
          if (!processedData) {
              return false;
          }
          if (processedData[dataId]) {
              if (processedData[dataId].indexOf(field) >= 0) {
                  return true;
              }
              else {
                  processedData[dataId].push(field);
              }
          }
          else {
              processedData[dataId] = [field];
          }
          return false;
      }
      function writeFieldToStore(_a) {
          var field = _a.field, value = _a.value, dataId = _a.dataId, context = _a.context;
          var _b;
          var variables = context.variables, dataIdFromObject = context.dataIdFromObject, store = context.store;
          var storeValue;
          var storeObject;
          var storeFieldName = apolloUtilities.storeKeyNameFromField(field, variables);
          var shouldMerge = false;
          var generatedKey = '';
          if (!field.selectionSet || value === null) {
              storeValue =
                  value != null && typeof value === 'object'
                      ?
                          { type: 'json', json: value }
                      :
                          value;
          }
          else if (Array.isArray(value)) {
              var generatedId = dataId + "." + storeFieldName;
              storeValue = processArrayValue(value, generatedId, field.selectionSet, context);
          }
          else {
              var valueDataId = dataId + "." + storeFieldName;
              var generated = true;
              if (!isGeneratedId(valueDataId)) {
                  valueDataId = '$' + valueDataId;
              }
              if (dataIdFromObject) {
                  var semanticId = dataIdFromObject(value);
                  if (semanticId && isGeneratedId(semanticId)) {
                      throw new Error('IDs returned by dataIdFromObject cannot begin with the "$" character.');
                  }
                  if (semanticId || (typeof semanticId === 'number' && semanticId === 0)) {
                      valueDataId = semanticId;
                      generated = false;
                  }
              }
              if (!isDataProcessed(valueDataId, field, context.processedData)) {
                  writeSelectionSetToStore({
                      dataId: valueDataId,
                      result: value,
                      selectionSet: field.selectionSet,
                      context: context,
                  });
              }
              var typename = value.__typename;
              storeValue = apolloUtilities.toIdValue({ id: valueDataId, typename: typename }, generated);
              storeObject = store.get(dataId);
              var escapedId = storeObject && storeObject[storeFieldName];
              if (escapedId !== storeValue && apolloUtilities.isIdValue(escapedId)) {
                  var hadTypename = escapedId.typename !== undefined;
                  var hasTypename = typename !== undefined;
                  var typenameChanged = hadTypename && hasTypename && escapedId.typename !== typename;
                  if (generated && !escapedId.generated && !typenameChanged) {
                      throw new Error("Store error: the application attempted to write an object with no provided id" +
                          (" but the store already contains an id of " + escapedId.id + " for this object. The selectionSet") +
                          " that was trying to be written is:\n" +
                          printer.print(field));
                  }
                  if (hadTypename && !hasTypename) {
                      throw new Error("Store error: the application attempted to write an object with no provided typename" +
                          (" but the store already contains an object with typename of " + escapedId.typename + " for the object of id " + escapedId.id + ". The selectionSet") +
                          " that was trying to be written is:\n" +
                          printer.print(field));
                  }
                  if (escapedId.generated) {
                      generatedKey = escapedId.id;
                      if (typenameChanged) {
                          if (!generated) {
                              store.delete(generatedKey);
                          }
                      }
                      else {
                          shouldMerge = true;
                      }
                  }
              }
          }
          var newStoreObj = __assign$7({}, store.get(dataId), (_b = {}, _b[storeFieldName] = storeValue, _b));
          if (shouldMerge) {
              mergeWithGenerated(generatedKey, storeValue.id, store);
          }
          storeObject = store.get(dataId);
          if (!storeObject || storeValue !== storeObject[storeFieldName]) {
              store.set(dataId, newStoreObj);
          }
      }
      function processArrayValue(value, generatedId, selectionSet, context) {
          return value.map(function (item, index) {
              if (item === null) {
                  return null;
              }
              var itemDataId = generatedId + "." + index;
              if (Array.isArray(item)) {
                  return processArrayValue(item, itemDataId, selectionSet, context);
              }
              var generated = true;
              if (context.dataIdFromObject) {
                  var semanticId = context.dataIdFromObject(item);
                  if (semanticId) {
                      itemDataId = semanticId;
                      generated = false;
                  }
              }
              if (!isDataProcessed(itemDataId, selectionSet, context.processedData)) {
                  writeSelectionSetToStore({
                      dataId: itemDataId,
                      result: item,
                      selectionSet: selectionSet,
                      context: context,
                  });
              }
              return apolloUtilities.toIdValue({ id: itemDataId, typename: item.__typename }, generated);
          });
      }
  
      function graphql(resolver, document, rootValue, contextValue, variableValues, execOptions) {
          if (execOptions === void 0) { execOptions = {}; }
          var mainDefinition = apolloUtilities.getMainDefinition(document);
          var fragments = apolloUtilities.getFragmentDefinitions(document);
          var fragmentMap = apolloUtilities.createFragmentMap(fragments);
          var resultMapper = execOptions.resultMapper;
          var fragmentMatcher = execOptions.fragmentMatcher || (function () { return true; });
          var execContext = {
              fragmentMap: fragmentMap,
              contextValue: contextValue,
              variableValues: variableValues,
              resultMapper: resultMapper,
              resolver: resolver,
              fragmentMatcher: fragmentMatcher,
          };
          return executeSelectionSet(mainDefinition.selectionSet, rootValue, execContext);
      }
      function executeSelectionSet(selectionSet, rootValue, execContext) {
          var fragmentMap = execContext.fragmentMap, contextValue = execContext.contextValue, variables = execContext.variableValues;
          var result = {};
          selectionSet.selections.forEach(function (selection) {
              if (!apolloUtilities.shouldInclude(selection, variables)) {
                  return;
              }
              if (apolloUtilities.isField(selection)) {
                  var fieldResult = executeField(selection, rootValue, execContext);
                  var resultFieldKey = apolloUtilities.resultKeyNameFromField(selection);
                  if (fieldResult !== undefined) {
                      if (result[resultFieldKey] === undefined) {
                          result[resultFieldKey] = fieldResult;
                      }
                      else {
                          merge(result[resultFieldKey], fieldResult);
                      }
                  }
              }
              else {
                  var fragment = void 0;
                  if (apolloUtilities.isInlineFragment(selection)) {
                      fragment = selection;
                  }
                  else {
                      fragment = fragmentMap[selection.name.value];
                      if (!fragment) {
                          throw new Error("No fragment named " + selection.name.value);
                      }
                  }
                  var typeCondition = fragment.typeCondition.name.value;
                  if (execContext.fragmentMatcher(rootValue, typeCondition, contextValue)) {
                      var fragmentResult = executeSelectionSet(fragment.selectionSet, rootValue, execContext);
                      merge(result, fragmentResult);
                  }
              }
          });
          if (execContext.resultMapper) {
              return execContext.resultMapper(result, rootValue);
          }
          return result;
      }
      function executeField(field, rootValue, execContext) {
          var variables = execContext.variableValues, contextValue = execContext.contextValue, resolver = execContext.resolver;
          var fieldName = field.name.value;
          var args = apolloUtilities.argumentsObjectFromField(field, variables);
          var info = {
              isLeaf: !field.selectionSet,
              resultKey: apolloUtilities.resultKeyNameFromField(field),
              directives: apolloUtilities.getDirectiveInfoFromField(field, variables),
          };
          var result = resolver(fieldName, rootValue, args, contextValue, info);
          if (!field.selectionSet) {
              return result;
          }
          if (result == null) {
              return result;
          }
          if (Array.isArray(result)) {
              return executeSubSelectedArray(field, result, execContext);
          }
          return executeSelectionSet(field.selectionSet, result, execContext);
      }
      function executeSubSelectedArray(field, result, execContext) {
          return result.map(function (item) {
              if (item === null) {
                  return null;
              }
              if (Array.isArray(item)) {
                  return executeSubSelectedArray(field, item, execContext);
              }
              return executeSelectionSet(field.selectionSet, item, execContext);
          });
      }
      var hasOwn = Object.prototype.hasOwnProperty;
      function merge(dest, src) {
          if (src !== null && typeof src === 'object') {
              Object.keys(src).forEach(function (key) {
                  var srcVal = src[key];
                  if (!hasOwn.call(dest, key)) {
                      dest[key] = srcVal;
                  }
                  else {
                      merge(dest[key], srcVal);
                  }
              });
          }
      }
  
      var __assign$8 = (undefined && undefined.__assign) || function () {
          __assign$8 = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$8.apply(this, arguments);
      };
      var ID_KEY = typeof Symbol !== 'undefined' ? Symbol('id') : '@@id';
      function readQueryFromStore(options) {
          var optsPatch = { returnPartialData: false };
          return diffQueryAgainstStore(__assign$8({}, options, optsPatch)).result;
      }
      var readStoreResolver = function (fieldName, idValue, args, context, _a) {
          var resultKey = _a.resultKey, directives = _a.directives;
          assertIdValue(idValue);
          var objId = idValue.id;
          var obj = context.store.get(objId);
          var storeKeyName = fieldName;
          if (args || directives) {
              storeKeyName = apolloUtilities.getStoreKeyName(storeKeyName, args, directives);
          }
          var fieldValue = void 0;
          if (obj) {
              fieldValue = obj[storeKeyName];
              if (typeof fieldValue === 'undefined' &&
                  context.cacheRedirects &&
                  (obj.__typename || objId === 'ROOT_QUERY')) {
                  var typename = obj.__typename || 'Query';
                  var type = context.cacheRedirects[typename];
                  if (type) {
                      var resolver = type[fieldName];
                      if (resolver) {
                          fieldValue = resolver(obj, args, {
                              getCacheKey: function (storeObj) {
                                  return apolloUtilities.toIdValue({
                                      id: context.dataIdFromObject(storeObj),
                                      typename: storeObj.__typename,
                                  });
                              },
                          });
                      }
                  }
              }
          }
          if (typeof fieldValue === 'undefined') {
              if (!context.returnPartialData) {
                  throw new Error("Can't find field " + storeKeyName + " on object (" + objId + ") " + JSON.stringify(obj, null, 2) + ".");
              }
              context.hasMissingField = true;
              return fieldValue;
          }
          if (apolloUtilities.isJsonValue(fieldValue)) {
              if (idValue.previousResult &&
                  apolloUtilities.isEqual(idValue.previousResult[resultKey], fieldValue.json)) {
                  return idValue.previousResult[resultKey];
              }
              return fieldValue.json;
          }
          if (idValue.previousResult) {
              fieldValue = addPreviousResultToIdValues(fieldValue, idValue.previousResult[resultKey]);
          }
          return fieldValue;
      };
      function diffQueryAgainstStore(_a) {
          var store = _a.store, query = _a.query, variables = _a.variables, previousResult = _a.previousResult, _b = _a.returnPartialData, returnPartialData = _b === void 0 ? true : _b, _c = _a.rootId, rootId = _c === void 0 ? 'ROOT_QUERY' : _c, fragmentMatcherFunction = _a.fragmentMatcherFunction, config = _a.config;
          var queryDefinition = apolloUtilities.getQueryDefinition(query);
          variables = apolloUtilities.assign({}, apolloUtilities.getDefaultValues(queryDefinition), variables);
          var context = {
              store: store,
              returnPartialData: returnPartialData,
              dataIdFromObject: (config && config.dataIdFromObject) || null,
              cacheRedirects: (config && config.cacheRedirects) || {},
              hasMissingField: false,
          };
          var rootIdValue = {
              type: 'id',
              id: rootId,
              previousResult: previousResult,
          };
          var result = graphql(readStoreResolver, query, rootIdValue, context, variables, {
              fragmentMatcher: fragmentMatcherFunction,
              resultMapper: resultMapper,
          });
          return {
              result: result,
              complete: !context.hasMissingField,
          };
      }
      function assertIdValue(idValue) {
          if (!apolloUtilities.isIdValue(idValue)) {
              throw new Error("Encountered a sub-selection on the query, but the store doesn't have an object reference. This should never happen during normal use unless you have custom code that is directly manipulating the store; please file an issue.");
          }
      }
      function addPreviousResultToIdValues(value, previousResult) {
          if (apolloUtilities.isIdValue(value)) {
              return __assign$8({}, value, { previousResult: previousResult });
          }
          else if (Array.isArray(value)) {
              var idToPreviousResult_1 = new Map();
              if (Array.isArray(previousResult)) {
                  previousResult.forEach(function (item) {
                      if (item && item[ID_KEY]) {
                          idToPreviousResult_1.set(item[ID_KEY], item);
                      }
                  });
              }
              return value.map(function (item, i) {
                  var itemPreviousResult = previousResult && previousResult[i];
                  if (apolloUtilities.isIdValue(item)) {
                      itemPreviousResult =
                          idToPreviousResult_1.get(item.id) || itemPreviousResult;
                  }
                  return addPreviousResultToIdValues(item, itemPreviousResult);
              });
          }
          return value;
      }
      function resultMapper(resultFields, idValue) {
          if (idValue.previousResult) {
              var currentResultKeys_1 = Object.keys(resultFields);
              var sameAsPreviousResult = Object.keys(idValue.previousResult).every(function (key) { return currentResultKeys_1.indexOf(key) > -1; }) &&
                  currentResultKeys_1.every(function (key) {
                      return areNestedArrayItemsStrictlyEqual(resultFields[key], idValue.previousResult[key]);
                  });
              if (sameAsPreviousResult) {
                  return idValue.previousResult;
              }
          }
          Object.defineProperty(resultFields, ID_KEY, {
              enumerable: false,
              configurable: true,
              writable: false,
              value: idValue.id,
          });
          return resultFields;
      }
      function areNestedArrayItemsStrictlyEqual(a, b) {
          if (a === b) {
              return true;
          }
          if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {
              return false;
          }
          return a.every(function (item, i) { return areNestedArrayItemsStrictlyEqual(item, b[i]); });
      }
  
      var __assign$9 = (undefined && undefined.__assign) || function () {
          __assign$9 = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$9.apply(this, arguments);
      };
      var RecordingCache = (function () {
          function RecordingCache(data) {
              if (data === void 0) { data = {}; }
              this.data = data;
              this.recordedData = {};
          }
          RecordingCache.prototype.record = function (transaction) {
              transaction(this);
              var recordedData = this.recordedData;
              this.recordedData = {};
              return recordedData;
          };
          RecordingCache.prototype.toObject = function () {
              return __assign$9({}, this.data, this.recordedData);
          };
          RecordingCache.prototype.get = function (dataId) {
              if (this.recordedData.hasOwnProperty(dataId)) {
                  return this.recordedData[dataId];
              }
              return this.data[dataId];
          };
          RecordingCache.prototype.set = function (dataId, value) {
              if (this.get(dataId) !== value) {
                  this.recordedData[dataId] = value;
              }
          };
          RecordingCache.prototype.delete = function (dataId) {
              this.recordedData[dataId] = undefined;
          };
          RecordingCache.prototype.clear = function () {
              var _this = this;
              Object.keys(this.data).forEach(function (dataId) { return _this.delete(dataId); });
              this.recordedData = {};
          };
          RecordingCache.prototype.replace = function (newData) {
              this.clear();
              this.recordedData = __assign$9({}, newData);
          };
          return RecordingCache;
      }());
      function record(startingState, transaction) {
          var recordingCache = new RecordingCache(startingState);
          return recordingCache.record(transaction);
      }
  
      var __extends$7 = (undefined && undefined.__extends) || (function () {
          var extendStatics = function (d, b) {
              extendStatics = Object.setPrototypeOf ||
                  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                  function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
              return extendStatics(d, b);
          };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var __assign$a = (undefined && undefined.__assign) || function () {
          __assign$a = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$a.apply(this, arguments);
      };
      var defaultConfig = {
          fragmentMatcher: new HeuristicFragmentMatcher(),
          dataIdFromObject: defaultDataIdFromObject,
          addTypename: true,
          storeFactory: defaultNormalizedCacheFactory,
      };
      function defaultDataIdFromObject(result) {
          if (result.__typename) {
              if (result.id !== undefined) {
                  return result.__typename + ":" + result.id;
              }
              if (result._id !== undefined) {
                  return result.__typename + ":" + result._id;
              }
          }
          return null;
      }
      var InMemoryCache = (function (_super) {
          __extends$7(InMemoryCache, _super);
          function InMemoryCache(config) {
              if (config === void 0) { config = {}; }
              var _this = _super.call(this) || this;
              _this.optimistic = [];
              _this.watches = [];
              _this.typenameDocumentCache = new WeakMap();
              _this.silenceBroadcast = false;
              _this.config = __assign$a({}, defaultConfig, config);
              if (_this.config.customResolvers) {
                  console.warn('customResolvers have been renamed to cacheRedirects. Please update your config as we will be deprecating customResolvers in the next major version.');
                  _this.config.cacheRedirects = _this.config.customResolvers;
              }
              if (_this.config.cacheResolvers) {
                  console.warn('cacheResolvers have been renamed to cacheRedirects. Please update your config as we will be deprecating cacheResolvers in the next major version.');
                  _this.config.cacheRedirects = _this.config.cacheResolvers;
              }
              _this.addTypename = _this.config.addTypename;
              _this.data = _this.config.storeFactory();
              return _this;
          }
          InMemoryCache.prototype.restore = function (data) {
              if (data)
                  this.data.replace(data);
              return this;
          };
          InMemoryCache.prototype.extract = function (optimistic) {
              if (optimistic === void 0) { optimistic = false; }
              if (optimistic && this.optimistic.length > 0) {
                  var patches = this.optimistic.map(function (opt) { return opt.data; });
                  return Object.assign.apply(Object, [{}, this.data.toObject()].concat(patches));
              }
              return this.data.toObject();
          };
          InMemoryCache.prototype.read = function (query) {
              if (query.rootId && this.data.get(query.rootId) === undefined) {
                  return null;
              }
              return readQueryFromStore({
                  store: this.config.storeFactory(this.extract(query.optimistic)),
                  query: this.transformDocument(query.query),
                  variables: query.variables,
                  rootId: query.rootId,
                  fragmentMatcherFunction: this.config.fragmentMatcher.match,
                  previousResult: query.previousResult,
                  config: this.config,
              });
          };
          InMemoryCache.prototype.write = function (write) {
              writeResultToStore({
                  dataId: write.dataId,
                  result: write.result,
                  variables: write.variables,
                  document: this.transformDocument(write.query),
                  store: this.data,
                  dataIdFromObject: this.config.dataIdFromObject,
                  fragmentMatcherFunction: this.config.fragmentMatcher.match,
              });
              this.broadcastWatches();
          };
          InMemoryCache.prototype.diff = function (query) {
              return diffQueryAgainstStore({
                  store: this.config.storeFactory(this.extract(query.optimistic)),
                  query: this.transformDocument(query.query),
                  variables: query.variables,
                  returnPartialData: query.returnPartialData,
                  previousResult: query.previousResult,
                  fragmentMatcherFunction: this.config.fragmentMatcher.match,
                  config: this.config,
              });
          };
          InMemoryCache.prototype.watch = function (watch) {
              var _this = this;
              this.watches.push(watch);
              return function () {
                  _this.watches = _this.watches.filter(function (c) { return c !== watch; });
              };
          };
          InMemoryCache.prototype.evict = function (query) {
              throw new Error("eviction is not implemented on InMemory Cache");
          };
          InMemoryCache.prototype.reset = function () {
              this.data.clear();
              this.broadcastWatches();
              return Promise.resolve();
          };
          InMemoryCache.prototype.removeOptimistic = function (id) {
              var _this = this;
              var toPerform = this.optimistic.filter(function (item) { return item.id !== id; });
              this.optimistic = [];
              toPerform.forEach(function (change) {
                  _this.recordOptimisticTransaction(change.transaction, change.id);
              });
              this.broadcastWatches();
          };
          InMemoryCache.prototype.performTransaction = function (transaction) {
              var alreadySilenced = this.silenceBroadcast;
              this.silenceBroadcast = true;
              transaction(this);
              if (!alreadySilenced) {
                  this.silenceBroadcast = false;
              }
              this.broadcastWatches();
          };
          InMemoryCache.prototype.recordOptimisticTransaction = function (transaction, id) {
              var _this = this;
              this.silenceBroadcast = true;
              var patch = record(this.extract(true), function (recordingCache) {
                  var dataCache = _this.data;
                  _this.data = recordingCache;
                  _this.performTransaction(transaction);
                  _this.data = dataCache;
              });
              this.optimistic.push({
                  id: id,
                  transaction: transaction,
                  data: patch,
              });
              this.silenceBroadcast = false;
              this.broadcastWatches();
          };
          InMemoryCache.prototype.transformDocument = function (document) {
              if (this.addTypename) {
                  var result = this.typenameDocumentCache.get(document);
                  if (!result) {
                      this.typenameDocumentCache.set(document, (result = apolloUtilities.addTypenameToDocument(document)));
                  }
                  return result;
              }
              return document;
          };
          InMemoryCache.prototype.readQuery = function (options, optimistic) {
              if (optimistic === void 0) { optimistic = false; }
              return this.read({
                  query: options.query,
                  variables: options.variables,
                  optimistic: optimistic,
              });
          };
          InMemoryCache.prototype.readFragment = function (options, optimistic) {
              if (optimistic === void 0) { optimistic = false; }
              return this.read({
                  query: this.transformDocument(apolloUtilities.getFragmentQueryDocument(options.fragment, options.fragmentName)),
                  variables: options.variables,
                  rootId: options.id,
                  optimistic: optimistic,
              });
          };
          InMemoryCache.prototype.writeQuery = function (options) {
              this.write({
                  dataId: 'ROOT_QUERY',
                  result: options.data,
                  query: this.transformDocument(options.query),
                  variables: options.variables,
              });
          };
          InMemoryCache.prototype.writeFragment = function (options) {
              this.write({
                  dataId: options.id,
                  result: options.data,
                  query: this.transformDocument(apolloUtilities.getFragmentQueryDocument(options.fragment, options.fragmentName)),
                  variables: options.variables,
              });
          };
          InMemoryCache.prototype.broadcastWatches = function () {
              var _this = this;
              if (this.silenceBroadcast)
                  return;
              this.watches.forEach(function (c) {
                  var newData = _this.diff({
                      query: c.query,
                      variables: c.variables,
                      previousResult: c.previousResult && c.previousResult(),
                      optimistic: c.optimistic,
                  });
                  c.callback(newData);
              });
          };
          return InMemoryCache;
      }(ApolloCache));
  
      var __assign$b = (undefined && undefined.__assign) || Object.assign || function(t) {
          for (var s, i = 1, n = arguments.length; i < n; i++) {
              s = arguments[i];
              for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                  t[p] = s[p];
          }
          return t;
      };
      var defaultHttpOptions = {
          includeQuery: true,
          includeExtensions: false,
      };
      var defaultHeaders = {
          // headers are case insensitive (https://stackoverflow.com/a/5259004)
          accept: '*/*',
          'content-type': 'application/json',
      };
      var defaultOptions = {
          method: 'POST',
      };
      var fallbackHttpConfig = {
          http: defaultHttpOptions,
          headers: defaultHeaders,
          options: defaultOptions,
      };
      var throwServerError = function (response, result, message) {
          var error = new Error(message);
          error.response = response;
          error.statusCode = response.status;
          error.result = result;
          throw error;
      };
      //TODO: when conditional types come in ts 2.8, operations should be a generic type that extends Operation | Array<Operation>
      var parseAndCheckHttpResponse = function (operations) { return function (response) {
          return (response
              .text()
              .then(function (bodyText) {
              try {
                  return JSON.parse(bodyText);
              }
              catch (err) {
                  var parseError = err;
                  parseError.response = response;
                  parseError.statusCode = response.status;
                  parseError.bodyText = bodyText;
                  return Promise.reject(parseError);
              }
          })
              .then(function (result) {
              if (response.status >= 300) {
                  //Network error
                  throwServerError(response, result, "Response not successful: Received status code " + response.status);
              }
              //TODO should really error per response in a Batch based on properties
              //    - could be done in a validation link
              if (!Array.isArray(result) &&
                  !result.hasOwnProperty('data') &&
                  !result.hasOwnProperty('errors')) {
                  //Data error
                  throwServerError(response, result, "Server response was missing for query '" + (Array.isArray(operations)
                      ? operations.map(function (op) { return op.operationName; })
                      : operations.operationName) + "'.");
              }
              return result;
          }));
      }; };
      var checkFetcher = function (fetcher) {
          if (!fetcher && typeof fetch === 'undefined') {
              var library = 'unfetch';
              if (typeof window === 'undefined')
                  library = 'node-fetch';
              throw new Error("\nfetch is not found globally and no fetcher passed, to fix pass a fetch for\nyour environment like https://www.npmjs.com/package/" + library + ".\n\nFor example:\nimport fetch from '" + library + "';\nimport { createHttpLink } from 'apollo-link-http';\n\nconst link = createHttpLink({ uri: '/graphql', fetch: fetch });");
          }
      };
      var createSignalIfSupported = function () {
          if (typeof AbortController === 'undefined')
              return { controller: false, signal: false };
          var controller = new AbortController();
          var signal = controller.signal;
          return { controller: controller, signal: signal };
      };
      var selectHttpOptionsAndBody = function (operation, fallbackConfig) {
          var configs = [];
          for (var _i = 2; _i < arguments.length; _i++) {
              configs[_i - 2] = arguments[_i];
          }
          var options = __assign$b({}, fallbackConfig.options, { headers: fallbackConfig.headers, credentials: fallbackConfig.credentials });
          var http = fallbackConfig.http;
          /*
           * use the rest of the configs to populate the options
           * configs later in the list will overwrite earlier fields
           */
          configs.forEach(function (config) {
              options = __assign$b({}, options, config.options, { headers: __assign$b({}, options.headers, config.headers) });
              if (config.credentials)
                  options.credentials = config.credentials;
              http = __assign$b({}, http, config.http);
          });
          //The body depends on the http options
          var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;
          var body = { operationName: operationName, variables: variables };
          if (http.includeExtensions)
              body.extensions = extensions;
          // not sending the query (i.e persisted queries)
          if (http.includeQuery)
              body.query = printer.print(query);
          return {
              options: options,
              body: body,
          };
      };
      var serializeFetchParameter = function (p, label) {
          var serialized;
          try {
              serialized = JSON.stringify(p);
          }
          catch (e) {
              var parseError = new Error("Network request failed. " + label + " is not serializable: " + e.message);
              parseError.parseError = e;
              throw parseError;
          }
          return serialized;
      };
      //selects "/graphql" by default
      var selectURI = function (operation, fallbackURI) {
          var context = operation.getContext();
          var contextURI = context.uri;
          if (contextURI) {
              return contextURI;
          }
          else if (typeof fallbackURI === 'function') {
              return fallbackURI(operation);
          }
          else {
              return fallbackURI || '/graphql';
          }
      };
  
      var __extends$8 = (undefined && undefined.__extends) || (function () {
          var extendStatics = Object.setPrototypeOf ||
              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
              function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var __rest = (undefined && undefined.__rest) || function (s, e) {
          var t = {};
          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
              t[p] = s[p];
          if (s != null && typeof Object.getOwnPropertySymbols === "function")
              for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
                  t[p[i]] = s[p[i]];
          return t;
      };
      var createHttpLink = function (linkOptions) {
          if (linkOptions === void 0) { linkOptions = {}; }
          var _a = linkOptions.uri, uri = _a === void 0 ? '/graphql' : _a, 
          // use default global fetch is nothing passed in
          fetcher = linkOptions.fetch, includeExtensions = linkOptions.includeExtensions, useGETForQueries = linkOptions.useGETForQueries, requestOptions = __rest(linkOptions, ["uri", "fetch", "includeExtensions", "useGETForQueries"]);
          // dev warnings to ensure fetch is present
          checkFetcher(fetcher);
          //fetcher is set here rather than the destructuring to ensure fetch is
          //declared before referencing it. Reference in the destructuring would cause
          //a ReferenceError
          if (!fetcher) {
              fetcher = fetch;
          }
          var linkConfig = {
              http: { includeExtensions: includeExtensions },
              options: requestOptions.fetchOptions,
              credentials: requestOptions.credentials,
              headers: requestOptions.headers,
          };
          return new ApolloLink$1(function (operation) {
              var chosenURI = selectURI(operation, uri);
              var context = operation.getContext();
              var contextConfig = {
                  http: context.http,
                  options: context.fetchOptions,
                  credentials: context.credentials,
                  headers: context.headers,
              };
              //uses fallback, link, and then context to build options
              var _a = selectHttpOptionsAndBody(operation, fallbackHttpConfig, linkConfig, contextConfig), options = _a.options, body = _a.body;
              var controller;
              if (!options.signal) {
                  var _b = createSignalIfSupported(), _controller = _b.controller, signal = _b.signal;
                  controller = _controller;
                  if (controller)
                      options.signal = signal;
              }
              // If requested, set method to GET if there are no mutations.
              var definitionIsMutation = function (d) {
                  return d.kind === 'OperationDefinition' && d.operation === 'mutation';
              };
              if (useGETForQueries &&
                  !operation.query.definitions.some(definitionIsMutation)) {
                  options.method = 'GET';
              }
              if (options.method === 'GET') {
                  var _c = rewriteURIForGET(chosenURI, body), newURI = _c.newURI, parseError = _c.parseError;
                  if (parseError) {
                      return fromError$1(parseError);
                  }
                  chosenURI = newURI;
              }
              else {
                  try {
                      options.body = serializeFetchParameter(body, 'Payload');
                  }
                  catch (parseError) {
                      return fromError$1(parseError);
                  }
              }
              return new Observable$2(function (observer) {
                  fetcher(chosenURI, options)
                      .then(function (response) {
                      operation.setContext({ response: response });
                      return response;
                  })
                      .then(parseAndCheckHttpResponse(operation))
                      .then(function (result) {
                      // we have data and can send it to back up the link chain
                      observer.next(result);
                      observer.complete();
                      return result;
                  })
                      .catch(function (err) {
                      // fetch was cancelled so its already been cleaned up in the unsubscribe
                      if (err.name === 'AbortError')
                          return;
                      // if it is a network error, BUT there is graphql result info
                      // fire the next observer before calling error
                      // this gives apollo-client (and react-apollo) the `graphqlErrors` and `networErrors`
                      // to pass to UI
                      // this should only happen if we *also* have data as part of the response key per
                      // the spec
                      if (err.result && err.result.errors && err.result.data) {
                          // if we dont' call next, the UI can only show networkError because AC didn't
                          // get andy graphqlErrors
                          // this is graphql execution result info (i.e errors and possibly data)
                          // this is because there is no formal spec how errors should translate to
                          // http status codes. So an auth error (401) could have both data
                          // from a public field, errors from a private field, and a status of 401
                          // {
                          //  user { // this will have errors
                          //    firstName
                          //  }
                          //  products { // this is public so will have data
                          //    cost
                          //  }
                          // }
                          //
                          // the result of above *could* look like this:
                          // {
                          //   data: { products: [{ cost: "$10" }] },
                          //   errors: [{
                          //      message: 'your session has timed out',
                          //      path: []
                          //   }]
                          // }
                          // status code of above would be a 401
                          // in the UI you want to show data where you can, errors as data where you can
                          // and use correct http status codes
                          observer.next(err.result);
                      }
                      observer.error(err);
                  });
                  return function () {
                      // XXX support canceling this request
                      // https://developers.google.com/web/updates/2017/09/abortable-fetch
                      if (controller)
                          controller.abort();
                  };
              });
          });
      };
      // For GET operations, returns the given URI rewritten with parameters, or a
      // parse error.
      function rewriteURIForGET(chosenURI, body) {
          // Implement the standard HTTP GET serialization, plus 'extensions'. Note
          // the extra level of JSON serialization!
          var queryParams = [];
          var addQueryParam = function (key, value) {
              queryParams.push(key + "=" + encodeURIComponent(value));
          };
          if ('query' in body) {
              addQueryParam('query', body.query);
          }
          if (body.operationName) {
              addQueryParam('operationName', body.operationName);
          }
          if (body.variables) {
              var serializedVariables = void 0;
              try {
                  serializedVariables = serializeFetchParameter(body.variables, 'Variables map');
              }
              catch (parseError) {
                  return { parseError: parseError };
              }
              addQueryParam('variables', serializedVariables);
          }
          if (body.extensions) {
              var serializedExtensions = void 0;
              try {
                  serializedExtensions = serializeFetchParameter(body.extensions, 'Extensions map');
              }
              catch (parseError) {
                  return { parseError: parseError };
              }
              addQueryParam('extensions', serializedExtensions);
          }
          // Reconstruct the URI with added query params.
          // XXX This assumes that the URI is well-formed and that it doesn't
          //     already contain any of these query params. We could instead use the
          //     URL API and take a polyfill (whatwg-url@6) for older browsers that
          //     don't support URLSearchParams. Note that some browsers (and
          //     versions of whatwg-url) support URL but not URLSearchParams!
          var fragment = '', preFragment = chosenURI;
          var fragmentStart = chosenURI.indexOf('#');
          if (fragmentStart !== -1) {
              fragment = chosenURI.substr(fragmentStart);
              preFragment = chosenURI.substr(0, fragmentStart);
          }
          var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';
          var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;
          return { newURI: newURI };
      }
      var HttpLink = /** @class */ (function (_super) {
          __extends$8(HttpLink, _super);
          function HttpLink(opts) {
              return _super.call(this, createHttpLink(opts).request) || this;
          }
          return HttpLink;
      }(ApolloLink$1));
  
      var connectionRemoveConfig = {
          test: function (directive) { return directive.name.value === 'client'; },
          remove: true,
      };
      var removed = new Map();
      function removeClientSetsFromDocument(query) {
          var cached = removed.get(query);
          if (cached)
              return cached;
          apolloUtilities.checkDocument(query);
          var docClone = apolloUtilities.removeDirectivesFromDocument([connectionRemoveConfig], query);
          removed.set(query, docClone);
          return docClone;
      }
  
      var __extends$9 = (undefined && undefined.__extends) || (function () {
          var extendStatics = Object.setPrototypeOf ||
              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
              function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var capitalizeFirstLetter = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); };
      var withClientState = function (clientStateConfig) {
          if (clientStateConfig === void 0) { clientStateConfig = { resolvers: {}, defaults: {} }; }
          var resolvers = clientStateConfig.resolvers, defaults = clientStateConfig.defaults, cache = clientStateConfig.cache, typeDefs = clientStateConfig.typeDefs;
          if (cache && defaults) {
              cache.writeData({ data: defaults });
          }
          return new (function (_super) {
              __extends$9(StateLink, _super);
              function StateLink() {
                  return _super !== null && _super.apply(this, arguments) || this;
              }
              StateLink.prototype.writeDefaults = function () {
                  if (cache && defaults) {
                      cache.writeData({ data: defaults });
                  }
              };
              StateLink.prototype.request = function (operation, forward) {
                  if (forward === void 0) { forward = function () { return Observable$2.of({ data: {} }); }; }
                  if (typeDefs) {
                      var directives_1 = 'directive @client on FIELD';
                      var definition_1 = typeof typeDefs === 'string'
                          ? typeDefs
                          : typeDefs.map(function (typeDef) { return typeDef.trim(); }).join('\n');
                      operation.setContext(function (_a) {
                          var _b = _a.schemas, schemas = _b === void 0 ? [] : _b;
                          return ({
                              schemas: schemas.concat([{ definition: definition_1, directives: directives_1 }]),
                          });
                      });
                  }
                  var isClient = apolloUtilities.hasDirectives(['client'], operation.query);
                  if (!isClient)
                      return forward(operation);
                  var server = removeClientSetsFromDocument(operation.query);
                  var query = operation.query;
                  var type = capitalizeFirstLetter((apolloUtilities.getMainDefinition(query) || {}).operation) || 'Query';
                  var resolver = function (fieldName, rootValue, args, context, info) {
                      if (rootValue === void 0) { rootValue = {}; }
                      var fieldValue = rootValue[info.resultKey];
                      if (fieldValue !== undefined)
                          return fieldValue;
                      var resolverMap = resolvers[rootValue.__typename || type];
                      if (resolverMap) {
                          var resolve = resolverMap[fieldName];
                          if (resolve)
                              return resolve(rootValue, args, context, info);
                      }
                      return defaults[fieldName];
                  };
                  return new Observable$2(function (observer) {
                      if (server)
                          operation.query = server;
                      var obs = server && forward
                          ? forward(operation)
                          : Observable$2.of({
                              data: {},
                          });
                      var observerErrorHandler = observer.error.bind(observer);
                      var sub = obs.subscribe({
                          next: function (_a) {
                              var data = _a.data, errors = _a.errors;
                              var context = operation.getContext();
                              async.graphql(resolver, query, data, context, operation.variables)
                                  .then(function (nextData) {
                                  observer.next({
                                      data: nextData,
                                      errors: errors,
                                  });
                                  observer.complete();
                              })
                                  .catch(observerErrorHandler);
                          },
                          error: observerErrorHandler,
                      });
                      return function () {
                          if (sub)
                              sub.unsubscribe();
                      };
                  });
              };
              return StateLink;
          }(ApolloLink$1))();
      };
  
      var __extends$a = (undefined && undefined.__extends) || (function () {
          var extendStatics = Object.setPrototypeOf ||
              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
              function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var onError = function (errorHandler) {
          return new ApolloLink$1(function (operation, forward) {
              return new Observable$2(function (observer) {
                  var sub;
                  var retriedSub;
                  var retriedResult;
                  try {
                      sub = forward(operation).subscribe({
                          next: function (result) {
                              if (result.errors) {
                                  retriedResult = errorHandler({
                                      graphQLErrors: result.errors,
                                      response: result,
                                      operation: operation,
                                      forward: forward,
                                  });
                                  if (retriedResult) {
                                      retriedSub = retriedResult.subscribe({
                                          next: observer.next.bind(observer),
                                          error: observer.error.bind(observer),
                                          complete: observer.complete.bind(observer),
                                      });
                                      return;
                                  }
                              }
                              observer.next(result);
                          },
                          error: function (networkError) {
                              retriedResult = errorHandler({
                                  operation: operation,
                                  networkError: networkError,
                                  //Network errors can return GraphQL errors on for example a 403
                                  graphQLErrors: networkError.result && networkError.result.errors,
                                  forward: forward,
                              });
                              if (retriedResult) {
                                  retriedSub = retriedResult.subscribe({
                                      next: observer.next.bind(observer),
                                      error: observer.error.bind(observer),
                                      complete: observer.complete.bind(observer),
                                  });
                                  return;
                              }
                              observer.error(networkError);
                          },
                          complete: function () {
                              // disable the previous sub from calling complete on observable
                              // if retry is in flight.
                              if (!retriedResult) {
                                  observer.complete.bind(observer)();
                              }
                          },
                      });
                  }
                  catch (e) {
                      errorHandler({ networkError: e, operation: operation, forward: forward });
                      observer.error(e);
                  }
                  return function () {
                      if (sub)
                          sub.unsubscribe();
                      if (retriedSub)
                          sub.unsubscribe();
                  };
              });
          });
      };
      var ErrorLink = /** @class */ (function (_super) {
          __extends$a(ErrorLink, _super);
          function ErrorLink(errorHandler) {
              var _this = _super.call(this) || this;
              _this.link = onError(errorHandler);
              return _this;
          }
          ErrorLink.prototype.request = function (operation, forward) {
              return this.link.request(operation, forward);
          };
          return ErrorLink;
      }(ApolloLink$1));
  
      var __extends$b = (undefined && undefined.__extends) || (function () {
          var extendStatics = function (d, b) {
              extendStatics = Object.setPrototypeOf ||
                  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                  function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
              return extendStatics(d, b);
          };
          return function (d, b) {
              extendStatics(d, b);
              function __() { this.constructor = d; }
              d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
      })();
      var __assign$c = (undefined && undefined.__assign) || function () {
          __assign$c = Object.assign || function(t) {
              for (var s, i = 1, n = arguments.length; i < n; i++) {
                  s = arguments[i];
                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                      t[p] = s[p];
              }
              return t;
          };
          return __assign$c.apply(this, arguments);
      };
      var PRESET_CONFIG_KEYS = [
          'request',
          'uri',
          'credentials',
          'headers',
          'fetch',
          'fetchOptions',
          'clientState',
          'onError',
          'cacheRedirects',
          'cache',
      ];
      var DefaultClient = (function (_super) {
          __extends$b(DefaultClient, _super);
          function DefaultClient(config) {
              if (config === void 0) { config = {}; }
              var _this = this;
              if (config) {
                  var diff = Object.keys(config).filter(function (key) { return PRESET_CONFIG_KEYS.indexOf(key) === -1; });
                  if (diff.length > 0) {
                      console.warn('ApolloBoost was initialized with unsupported options: ' +
                          ("" + diff.join(' ')));
                  }
              }
              var request = config.request, uri = config.uri, credentials = config.credentials, headers = config.headers, fetch = config.fetch, fetchOptions = config.fetchOptions, clientState = config.clientState, cacheRedirects = config.cacheRedirects, errorCallback = config.onError;
              var cache = config.cache;
              if (cache && cacheRedirects) {
                  throw new Error('Incompatible cache configuration. If providing `cache` then ' +
                      'configure the provided instance with `cacheRedirects` instead.');
              }
              if (!cache) {
                  cache = cacheRedirects
                      ? new InMemoryCache({ cacheRedirects: cacheRedirects })
                      : new InMemoryCache();
              }
              var stateLink = clientState
                  ? withClientState(__assign$c({}, clientState, { cache: cache }))
                  : false;
              var errorLink = errorCallback
                  ? onError(errorCallback)
                  : onError(function (_a) {
                      var graphQLErrors = _a.graphQLErrors, networkError = _a.networkError;
                      if (graphQLErrors) {
                          graphQLErrors.map(function (_a) {
                              var message = _a.message, locations = _a.locations, path = _a.path;
                              return console.log("[GraphQL error]: Message: " + message + ", Location: " +
                                  (locations + ", Path: " + path));
                          });
                      }
                      if (networkError) {
                          console.log("[Network error]: " + networkError);
                      }
                  });
              var requestHandler = request
                  ? new ApolloLink$1(function (operation, forward) {
                      return new Observable$2(function (observer) {
                          var handle;
                          Promise.resolve(operation)
                              .then(function (oper) { return request(oper); })
                              .then(function () {
                              handle = forward(operation).subscribe({
                                  next: observer.next.bind(observer),
                                  error: observer.error.bind(observer),
                                  complete: observer.complete.bind(observer),
                              });
                          })
                              .catch(observer.error.bind(observer));
                          return function () {
                              if (handle) {
                                  handle.unsubscribe();
                              }
                          };
                      });
                  })
                  : false;
              var httpLink = new HttpLink({
                  uri: uri || '/graphql',
                  fetch: fetch,
                  fetchOptions: fetchOptions || {},
                  credentials: credentials || 'same-origin',
                  headers: headers || {},
              });
              var link = ApolloLink$1.from([
                  errorLink,
                  requestHandler,
                  stateLink,
                  httpLink,
              ].filter(function (x) { return !!x; }));
              _this = _super.call(this, { cache: cache, link: link }) || this;
              return _this;
          }
          return DefaultClient;
      }(ApolloClient));
  
      exports.printAST = printer.print;
      exports.gql = graphqlTag;
      exports.InMemoryCache = InMemoryCache;
      exports.HttpLink = HttpLink;
      exports.default = DefaultClient;
      exports.ApolloClient = ApolloClient;
      exports.ObservableQuery = ObservableQuery;
      exports.ApolloError = ApolloError;
      exports.Observable = Observable$2;
      exports.createOperation = createOperation$1;
      exports.makePromise = makePromise$1;
      exports.toPromise = toPromise$1;
      exports.fromPromise = fromPromise$1;
      exports.fromError = fromError$1;
      exports.empty = empty$1;
      exports.from = from$1;
      exports.split = split$1;
      exports.concat = concat$1;
      exports.ApolloLink = ApolloLink$1;
      exports.execute = execute$1;
      exports.defaultDataIdFromObject = defaultDataIdFromObject;
      exports.ID_KEY = ID_KEY;
      exports.readQueryFromStore = readQueryFromStore;
      exports.diffQueryAgainstStore = diffQueryAgainstStore;
      exports.assertIdValue = assertIdValue;
      exports.WriteError = WriteError;
      exports.enhanceErrorWithDocument = enhanceErrorWithDocument;
      exports.writeQueryToStore = writeQueryToStore;
      exports.writeResultToStore = writeResultToStore;
      exports.writeSelectionSetToStore = writeSelectionSetToStore;
      exports.HeuristicFragmentMatcher = HeuristicFragmentMatcher;
      exports.IntrospectionFragmentMatcher = IntrospectionFragmentMatcher;
      exports.ObjectCache = ObjectCache;
      exports.defaultNormalizedCacheFactory = defaultNormalizedCacheFactory;
      exports.RecordingCache = RecordingCache;
      exports.record = record;
  
      Object.defineProperty(exports, '__esModule', { value: true });
  
  })));
  //# sourceMappingURL=bundle.umd.js.map
  