"use strict";
/* Socket Lib - Built with esbuild */
"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(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var binary_cache_exports = {};
__export(binary_cache_exports, {
  cleanDlxCache: () => cleanDlxCache,
  getBinaryCacheMetadataPath: () => getBinaryCacheMetadataPath,
  getDlxCachePath: () => getDlxCachePath,
  isBinaryCacheValid: () => isBinaryCacheValid,
  listDlxCache: () => listDlxCache,
  readBinaryCacheMetadata: () => readBinaryCacheMetadata,
  writeBinaryCacheMetadata: () => writeBinaryCacheMetadata
});
module.exports = __toCommonJS(binary_cache_exports);
var import_node_process = __toESM(require("node:process"));
var import_node_fs = require("node:fs");
var import_time = require("../constants/time");
var import_read_json = require("../fs/read-json");
var import_safe = require("../fs/safe");
var import_predicates = require("../objects/predicates");
var import_socket = require("../paths/socket");
var import_array = require("../primordials/array");
var import_date = require("../primordials/date");
var import_json = require("../primordials/json");
var import_string = require("../primordials/string");
var import_fs = require("../node/fs");
var import_path = require("../node/path");
async function cleanDlxCache(maxAge = import_time.DLX_BINARY_CACHE_TTL) {
  const cacheDir = getDlxCachePath();
  const fs = (0, import_fs.getNodeFs)();
  if (!fs.existsSync(cacheDir)) {
    return 0;
  }
  let cleaned = 0;
  const now = (0, import_date.DateNow)();
  const path = (0, import_path.getNodePath)();
  const entries = await fs.promises.readdir(cacheDir);
  for (const entry of entries) {
    const entryPath = path.join(cacheDir, entry);
    const metaPath = getBinaryCacheMetadataPath(entryPath);
    try {
      if (!await (0, import_node_fs.existsSync)(entryPath)) {
        continue;
      }
      const metadata = await (0, import_read_json.readJson)(metaPath, { throws: false });
      if (!metadata || typeof metadata !== "object" || (0, import_array.ArrayIsArray)(metadata)) {
        continue;
      }
      const timestamp = metadata["timestamp"];
      const age = typeof timestamp === "number" && timestamp > 0 ? now - timestamp : Number.POSITIVE_INFINITY;
      if (age < 0 || age > maxAge) {
        await (0, import_safe.safeDelete)(entryPath, { force: true, recursive: true });
        cleaned += 1;
      }
    } catch {
      try {
        const contents = await fs.promises.readdir(entryPath);
        if (!contents.length) {
          await (0, import_safe.safeDelete)(entryPath);
          cleaned += 1;
        }
      } catch {
      }
    }
  }
  return cleaned;
}
function getBinaryCacheMetadataPath(cacheEntryPath) {
  return (0, import_path.getNodePath)().join(cacheEntryPath, ".dlx-metadata.json");
}
const getDlxCachePath = import_socket.getSocketDlxDir;
async function isBinaryCacheValid(cacheEntryPath, cacheTtl) {
  const fs = (0, import_fs.getNodeFs)();
  try {
    const metaPath = getBinaryCacheMetadataPath(cacheEntryPath);
    if (!fs.existsSync(metaPath)) {
      return false;
    }
    const metadata = await (0, import_read_json.readJson)(metaPath, { throws: false });
    if (!(0, import_predicates.isPlainObject)(metadata)) {
      return false;
    }
    const now = (0, import_date.DateNow)();
    const timestamp = metadata["timestamp"];
    if (typeof timestamp !== "number" || timestamp <= 0) {
      return false;
    }
    const age = now - timestamp;
    if (age < 0) {
      return false;
    }
    return age < cacheTtl;
  } catch {
    return false;
  }
}
async function listDlxCache() {
  const cacheDir = getDlxCachePath();
  const fs = (0, import_fs.getNodeFs)();
  if (!fs.existsSync(cacheDir)) {
    return [];
  }
  const results = [];
  const now = (0, import_date.DateNow)();
  const path = (0, import_path.getNodePath)();
  const entries = await fs.promises.readdir(cacheDir);
  for (const entry of entries) {
    const entryPath = path.join(cacheDir, entry);
    try {
      if (!await (0, import_node_fs.existsSync)(entryPath)) {
        continue;
      }
      const metaPath = getBinaryCacheMetadataPath(entryPath);
      const metadata = await (0, import_read_json.readJson)(metaPath, { throws: false });
      if (!metadata || typeof metadata !== "object" || (0, import_array.ArrayIsArray)(metadata)) {
        continue;
      }
      const metaObj = metadata;
      const source = metaObj["source"];
      const url = source?.["url"] || metaObj["url"] || "";
      const files = await fs.promises.readdir(entryPath);
      const binaryFile = (0, import_array.ArrayPrototypeFind)(
        files,
        (f) => !(0, import_string.StringPrototypeStartsWith)(f, ".")
      );
      if (binaryFile) {
        const binaryPath = path.join(entryPath, binaryFile);
        const binaryStats = await fs.promises.stat(binaryPath);
        results.push({
          age: now - (metaObj["timestamp"] || 0),
          integrity: metaObj["integrity"] || "",
          name: binaryFile,
          size: binaryStats.size,
          url
        });
      }
    } catch {
    }
  }
  return results;
}
async function readBinaryCacheMetadata(cacheEntryPath) {
  const fs = (0, import_fs.getNodeFs)();
  try {
    const metaPath = getBinaryCacheMetadataPath(cacheEntryPath);
    if (!fs.existsSync(metaPath)) {
      return void 0;
    }
    const metadata = await (0, import_read_json.readJson)(metaPath, { throws: false });
    if (!(0, import_predicates.isPlainObject)(metadata)) {
      return void 0;
    }
    return metadata;
  } catch {
    return void 0;
  }
}
async function writeBinaryCacheMetadata(cacheEntryPath, cacheKey, url, integrity, size) {
  const metaPath = getBinaryCacheMetadataPath(cacheEntryPath);
  const metadata = {
    version: "1.0.0",
    cache_key: cacheKey,
    timestamp: (0, import_date.DateNow)(),
    integrity,
    size,
    source: {
      type: "download",
      url
    }
  };
  const fs = (0, import_fs.getNodeFs)();
  const tmpPath = `${metaPath}.tmp.${import_node_process.default.pid}`;
  await fs.promises.writeFile(tmpPath, (0, import_json.JSONStringify)(metadata, null, 2));
  await fs.promises.rename(tmpPath, metaPath);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  cleanDlxCache,
  getBinaryCacheMetadataPath,
  getDlxCachePath,
  isBinaryCacheValid,
  listDlxCache,
  readBinaryCacheMetadata,
  writeBinaryCacheMetadata
});
