"use strict";
/* Socket Lib - Built with esbuild */
"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);
var memoize_exports = {};
__export(memoize_exports, {
  memoize: () => memoize
});
module.exports = __toCommonJS(memoize_exports);
var import_output = require("../debug/output");
var import_date = require("../primordials/date");
var import_error = require("../primordials/error");
var import_map_set = require("../primordials/map-set");
var import_internal = require("./_internal");
function memoize(fn, options = {}) {
  const {
    keyGen = (...args) => (0, import_internal.defaultKeyGen)(args),
    maxSize = Number.POSITIVE_INFINITY,
    name = fn.name || "anonymous",
    ttl = Number.POSITIVE_INFINITY
  } = options;
  if (ttl < 0) {
    throw new import_error.TypeErrorCtor("TTL must be non-negative");
  }
  const cache = new import_map_set.MapCtor();
  import_internal.cacheRegistry.push(() => {
    cache.clear();
  });
  function evictLRU() {
    if (cache.size >= maxSize) {
      const oldest = cache.keys().next().value;
      if (oldest !== void 0) {
        cache.delete(oldest);
        (0, import_output.debugLog)(`[memoize:${name}] clear`, {
          key: oldest,
          reason: "LRU"
        });
      }
    }
  }
  function isExpired(entry) {
    if (ttl === Number.POSITIVE_INFINITY) {
      return false;
    }
    return (0, import_date.DateNow)() - entry.timestamp > ttl;
  }
  return function memoized(...args) {
    const key = keyGen(...args);
    const cached = cache.get(key);
    if (cached) {
      if (!isExpired(cached)) {
        cached.hits++;
        cache.delete(key);
        cache.set(key, cached);
        (0, import_output.debugLog)(`[memoize:${name}] hit`, { key, hits: cached.hits });
        return cached.value;
      }
      cache.delete(key);
    }
    (0, import_output.debugLog)(`[memoize:${name}] miss`, { key });
    const value = fn(...args);
    evictLRU();
    cache.set(key, {
      value,
      timestamp: Date.now(),
      hits: 0
    });
    (0, import_output.debugLog)(`[memoize:${name}] set`, { key, cacheSize: cache.size });
    return value;
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  memoize
});
