"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/createPersister.ts
var createPersister_exports = {};
__export(createPersister_exports, {
  PERSISTER_KEY_PREFIX: () => PERSISTER_KEY_PREFIX,
  experimental_createQueryPersister: () => experimental_createQueryPersister
});
module.exports = __toCommonJS(createPersister_exports);
var import_query_core = require("@tanstack/query-core");
var PERSISTER_KEY_PREFIX = "tanstack-query";
function experimental_createQueryPersister({
  storage,
  buster = "",
  maxAge = 1e3 * 60 * 60 * 24,
  serialize = JSON.stringify,
  deserialize = JSON.parse,
  prefix = PERSISTER_KEY_PREFIX,
  filters
}) {
  function isExpiredOrBusted(persistedQuery) {
    if (persistedQuery.state.dataUpdatedAt) {
      const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt;
      const expired = queryAge > maxAge;
      const busted = persistedQuery.buster !== buster;
      if (expired || busted) {
        return true;
      }
      return false;
    }
    return true;
  }
  async function retrieveQuery(queryHash, afterRestoreMacroTask) {
    if (storage != null) {
      const storageKey = `${prefix}-${queryHash}`;
      try {
        const storedData = await storage.getItem(storageKey);
        if (storedData) {
          const persistedQuery = await deserialize(storedData);
          if (isExpiredOrBusted(persistedQuery)) {
            await storage.removeItem(storageKey);
          } else {
            if (afterRestoreMacroTask) {
              setTimeout(() => afterRestoreMacroTask(persistedQuery), 0);
            }
            return persistedQuery.state.data;
          }
        }
      } catch (err) {
        if (process.env.NODE_ENV === "development") {
          console.error(err);
          console.warn(
            "Encountered an error attempting to restore query cache from persisted location."
          );
        }
        await storage.removeItem(storageKey);
      }
    }
    return;
  }
  async function persistQueryByKey(queryKey, queryClient) {
    if (storage != null) {
      const query = queryClient.getQueryCache().find({ queryKey });
      if (query) {
        await persistQuery(query);
      } else {
        if (process.env.NODE_ENV === "development") {
          console.warn(
            "Could not find query to be persisted. QueryKey:",
            JSON.stringify(queryKey)
          );
        }
      }
    }
  }
  async function persistQuery(query) {
    if (storage != null) {
      const storageKey = `${prefix}-${query.queryHash}`;
      storage.setItem(
        storageKey,
        await serialize({
          state: query.state,
          queryKey: query.queryKey,
          queryHash: query.queryHash,
          buster
        })
      );
    }
  }
  async function persisterFn(queryFn, ctx, query) {
    const matchesFilter = filters ? (0, import_query_core.matchQuery)(filters, query) : true;
    if (matchesFilter && query.state.data === void 0 && storage != null) {
      const restoredData = await retrieveQuery(
        query.queryHash,
        (persistedQuery) => {
          query.setState({
            dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
            errorUpdatedAt: persistedQuery.state.errorUpdatedAt
          });
          if (query.isStale()) {
            query.fetch();
          }
        }
      );
      if (restoredData != null) {
        return Promise.resolve(restoredData);
      }
    }
    const queryFnResult = await queryFn(ctx);
    if (matchesFilter && storage != null) {
      setTimeout(() => {
        persistQuery(query);
      }, 0);
    }
    return Promise.resolve(queryFnResult);
  }
  async function persisterGc() {
    if (storage?.entries) {
      const entries = await storage.entries();
      for (const [key, value] of entries) {
        if (key.startsWith(prefix)) {
          const persistedQuery = await deserialize(value);
          if (isExpiredOrBusted(persistedQuery)) {
            await storage.removeItem(key);
          }
        }
      }
    } else if (process.env.NODE_ENV === "development") {
      throw new Error(
        "Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items."
      );
    }
  }
  async function persisterRestoreAll(queryClient) {
    if (storage?.entries) {
      const entries = await storage.entries();
      for (const [key, value] of entries) {
        if (key.startsWith(prefix)) {
          const persistedQuery = await deserialize(value);
          if (isExpiredOrBusted(persistedQuery)) {
            await storage.removeItem(key);
          } else {
            queryClient.setQueryData(
              persistedQuery.queryKey,
              persistedQuery.state.data,
              {
                updatedAt: persistedQuery.state.dataUpdatedAt
              }
            );
          }
        }
      }
    } else if (process.env.NODE_ENV === "development") {
      throw new Error(
        "Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items."
      );
    }
  }
  return {
    persisterFn,
    persistQuery,
    persistQueryByKey,
    retrieveQuery,
    persisterGc,
    persisterRestoreAll
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PERSISTER_KEY_PREFIX,
  experimental_createQueryPersister
});
//# sourceMappingURL=createPersister.cjs.map