var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Provider = void 0;

var React = _interopRequireWildcard(require("react"));

var _reactApollo = require("react-apollo");

var _apolloClient = require("apollo-client");

var _apolloLink = require("apollo-link");

var _apolloLinkHttp = require("apollo-link-http");

var _apolloLinkContext = require("apollo-link-context");

var _apolloCacheInmemory = require("apollo-cache-inmemory");

var _apolloLinkError = require("apollo-link-error");

var Auth = _interopRequireWildcard(require("../helpers/auth"));

const Provider = ({
  children,
  shop,
  token,
  version,
  onNavigate
}) => {
  if (typeof window !== "undefined") {
    const httpLink = (0, _apolloLinkHttp.createHttpLink)({
      uri: `/api/graphql`
    });
    const middlewareLink = (0, _apolloLinkContext.setContext)(() => ({
      headers: {
        "X-Shopify-Access-Token": token,
        "X-Shopify-Shop-Domain": shop,
        "X-Shopify-API-Version": version
      }
    }));
    const errorLink = (0, _apolloLinkError.onError)(({
      graphQLErrors,
      networkError
    }) => {
      if (graphQLErrors) graphQLErrors.map(({
        message,
        locations,
        path
      }) => console.log(`[Reactify] GraphQL Error: Message: ${message}, Location: ${locations}, Path: ${path}`));

      if (networkError) {
        const networkErrorString = `${networkError}`;

        if (networkErrorString.includes("401")) {
          console.warn(`[Reactify] Network Error: ${networkError}`);
          Auth.removeCookies();
          onNavigate(`/reauth`, {
            replace: true
          });
        }
      }
    });
    const client = new _apolloClient.ApolloClient({
      link: _apolloLink.ApolloLink.from([errorLink, middlewareLink, httpLink]),
      cache: new _apolloCacheInmemory.InMemoryCache()
    });
    return /*#__PURE__*/React.createElement(_reactApollo.ApolloProvider, {
      client: client
    }, children);
  } else {
    return /*#__PURE__*/React.createElement(React.Fragment, null, children);
  }
};

exports.Provider = Provider;
//# sourceMappingURL=shopify.js.map