"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var cache_exports = {};
__export(cache_exports, {
  cachePolicy: () => cachePolicy
});
module.exports = __toCommonJS(cache_exports);
var import_cache = __toESM(require("../../cache"), 1);
var import_cache2 = require("../../cache/cache");
var import_types = require("../../lib/types");
const serverSide = typeof globalThis.window === "undefined";
const cachePolicy = ({
  enabled,
  setFetching,
  cache: localCache = import_cache.default,
  serverSideFallback = true
}) => () => {
  return {
    beforeNetwork(ctx, { initialValue, next, resolve, marshalVariables }) {
      const { policy, artifact } = ctx;
      let useCache = false;
      if (enabled && (artifact.kind === import_types.ArtifactKind.Query || artifact.kind === import_types.ArtifactKind.Fragment) && !ctx.cacheParams?.disableRead) {
        const policyAllowsCache = policy !== import_types.CachePolicy.NetworkOnly && policy !== import_types.CachePolicy.NoCache;
        if (policyAllowsCache) {
          const value = localCache.read({
            selection: artifact.selection,
            variables: marshalVariables(ctx),
            fullCheck: true
          });
          const allowed = !value.partial || artifact.kind === import_types.ArtifactKind.Query && artifact.partial;
          if (policy === import_types.CachePolicy.CacheOnly) {
            return resolve(ctx, {
              fetching: false,
              variables: ctx.variables ?? null,
              data: allowed ? value.data : initialValue.data,
              errors: null,
              source: import_types.DataSource.Cache,
              partial: allowed ? value.partial : false,
              stale: value.stale
            });
          }
          useCache = !!(value.data !== null && allowed);
          if (useCache) {
            resolve(ctx, {
              fetching: false,
              variables: ctx.variables ?? null,
              data: value.data,
              errors: null,
              source: import_types.DataSource.Cache,
              partial: value.partial,
              stale: value.stale
            });
          }
          if (useCache && !value.partial && !value.stale && ctx.policy !== "CacheAndNetwork") {
            return;
          }
        }
      }
      if (enabled) {
        setTimeout(() => {
          localCache._internal_unstable.collectGarbage();
        }, 0);
      }
      if (!ctx.stuff?.silenceLoading) {
        let fetchingState = null;
        if (!useCache && "enableLoadingState" in artifact && artifact.enableLoadingState) {
          fetchingState = localCache.read({
            selection: artifact.selection,
            variables: marshalVariables(ctx),
            loading: true
          }).data;
        }
        setFetching(!useCache, fetchingState);
      }
      return next(ctx);
    },
    afterNetwork(ctx, { resolve, value, marshalVariables }) {
      if (ctx.policy !== import_types.CachePolicy.NoCache && value.source !== import_types.DataSource.Cache && enabled && value.data && !ctx.cacheParams?.disableWrite) {
        if (ctx.cacheParams && "serverSideFallback" in ctx.cacheParams) {
          serverSideFallback = ctx.cacheParams?.serverSideFallback ?? serverSideFallback;
        }
        const targetCache = serverSide && serverSideFallback ? new import_cache2.Cache({ disabled: false }) : localCache;
        let layer;
        if (!serverSide && ctx.cacheParams?.layer) {
          layer = ctx.cacheParams.layer.id;
        }
        targetCache.write({
          ...ctx.cacheParams,
          layer,
          selection: ctx.artifact.selection,
          data: value.data,
          variables: marshalVariables(ctx)
        });
        value = {
          ...value,
          data: targetCache.read({
            selection: ctx.artifact.selection,
            variables: marshalVariables(ctx),
            ignoreMasking: serverSide
          }).data
        };
      }
      resolve(ctx, value);
    }
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  cachePolicy
});
