"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 primordials_exports = {};
__export(primordials_exports, {
  checkPrimordials: () => checkPrimordials,
  collectJsFiles: () => collectJsFiles,
  extractPrimordialsNames: () => extractPrimordialsNames,
  extractTsExports: () => extractTsExports,
  readSocketLibPrimordialNames: () => readSocketLibPrimordialNames,
  resolveSocketLibPrimordials: () => resolveSocketLibPrimordials,
  stripComments: () => stripComments
});
module.exports = __toCommonJS(primordials_exports);
var import_node_fs = require("node:fs");
var import_node_path = __toESM(require("node:path"));
var import_join = require("../arrays/join");
var import_error = require("../primordials/error");
const NAME_HEAD_RE = /^([A-Za-z_$][A-Za-z0-9_$]*)/;
function checkPrimordials(config) {
  const repoRoot = config.repoRoot ?? process.cwd();
  const used = /* @__PURE__ */ new Set();
  const usedToFiles = /* @__PURE__ */ new Map();
  for (const dir of config.scanDirs) {
    const fullDir = import_node_path.default.resolve(repoRoot, dir);
    const jsFiles = collectJsFiles(fullDir);
    for (const file of jsFiles) {
      let src;
      try {
        src = (0, import_node_fs.readFileSync)(file, "utf8");
      } catch {
        continue;
      }
      if (!src.includes("primordials")) {
        continue;
      }
      const names = extractPrimordialsNames(src);
      if (names.length === 0) {
        continue;
      }
      const rel = import_node_path.default.relative(repoRoot, file);
      for (const name of names) {
        used.add(name);
        const arr = usedToFiles.get(name) ?? [];
        if (!arr.includes(rel)) {
          arr.push(rel);
        }
        usedToFiles.set(name, arr);
      }
    }
  }
  const socketLibPath = resolveSocketLibPrimordials(config);
  const socketLibNames = readSocketLibPrimordialNames(socketLibPath);
  const findings = [];
  for (const name of [...used].sort()) {
    if (config.nodeInternalOnly.has(name)) {
      continue;
    }
    if (socketLibNames.has(name)) {
      continue;
    }
    const aliased = config.aliasMap.get(name);
    if (aliased) {
      if (socketLibNames.has(aliased)) {
        continue;
      }
      findings.push({
        kind: "missing-from-socket-lib",
        name,
        files: usedToFiles.get(name) ?? [],
        hint: `\`${name}\` is mapped to socket-lib's \`${aliased}\`, but \`${aliased}\` is not exported. Add \`export const ${aliased} = ${name}\` to the appropriate leaf under socket-lib/src/primordials/.`
      });
      continue;
    }
    findings.push({
      kind: "unmapped",
      name,
      files: usedToFiles.get(name) ?? [],
      hint: `\`${name}\` is destructured from \`primordials\` but no socket-lib mapping exists. Pick one: ` + (0, import_join.joinOr)([
        `add \`${name}\` to the appropriate leaf under socket-lib/src/primordials/`,
        `add a \`${name}\` \u2192 \`<libName>\` entry to the alias map`,
        `add \`${name}\` to nodeInternalOnly (if Node-internal only)`
      ]) + "."
    });
  }
  return {
    used,
    usedToFiles,
    socketLibNames,
    findings
  };
}
function collectJsFiles(dir) {
  const out = [];
  if (!(0, import_node_fs.existsSync)(dir)) {
    return out;
  }
  const stack = [dir];
  while (stack.length > 0) {
    const cur = stack.pop();
    let entries;
    try {
      entries = (0, import_node_fs.readdirSync)(cur);
    } catch {
      continue;
    }
    for (const name of entries) {
      const full = import_node_path.default.join(cur, name);
      let stat;
      try {
        stat = (0, import_node_fs.statSync)(full);
      } catch {
        continue;
      }
      if (stat.isDirectory()) {
        stack.push(full);
      } else if (stat.isFile() && full.endsWith(".js")) {
        out.push(full);
      }
    }
  }
  return out;
}
function extractPrimordialsNames(src) {
  const cleaned = stripComments(src);
  const re = /const\s*\{\s*([^}]*?)\}\s*=\s*primordials\b/g;
  const out = [];
  let m;
  while ((m = re.exec(cleaned)) !== null) {
    for (const raw of m[1].split(",")) {
      const trimmed = raw.trim();
      if (!trimmed) {
        continue;
      }
      const nameMatch = NAME_HEAD_RE.exec(trimmed);
      if (nameMatch) {
        out.push(nameMatch[1]);
      }
    }
  }
  return out;
}
function extractTsExports(src) {
  const out = /* @__PURE__ */ new Set();
  for (const m of src.matchAll(
    /^export\s+(?:declare\s+)?const\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm
  )) {
    out.add(m[1]);
  }
  for (const m of src.matchAll(
    /^export\s+(?:declare\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm
  )) {
    out.add(m[1]);
  }
  for (const m of src.matchAll(/^export\s*\{\s*([^}]+)\}/gm)) {
    for (const raw of m[1].split(",")) {
      const trimmed = raw.trim();
      if (!trimmed) {
        continue;
      }
      const nameMatch = NAME_HEAD_RE.exec(trimmed);
      if (nameMatch) {
        out.add(nameMatch[1]);
      }
    }
  }
  return [...out];
}
function readSocketLibPrimordialNames(resolved) {
  const stat = (0, import_node_fs.statSync)(resolved);
  if (stat.isFile()) {
    return new Set(extractTsExports((0, import_node_fs.readFileSync)(resolved, "utf8")));
  }
  const out = /* @__PURE__ */ new Set();
  for (const name of (0, import_node_fs.readdirSync)(resolved)) {
    if (!name.endsWith(".ts") && !name.endsWith(".d.ts")) {
      continue;
    }
    const full = import_node_path.default.join(resolved, name);
    const fileStat = (0, import_node_fs.statSync)(full);
    if (!fileStat.isFile()) {
      continue;
    }
    for (const exp of extractTsExports((0, import_node_fs.readFileSync)(full, "utf8"))) {
      out.add(exp);
    }
  }
  return out;
}
function resolveSocketLibPrimordials(config) {
  if (config.socketLibPrimordialsPath) {
    if (!(0, import_node_fs.existsSync)(config.socketLibPrimordialsPath)) {
      throw new import_error.ErrorCtor(
        `socketLibPrimordialsPath does not exist: ${config.socketLibPrimordialsPath}`
      );
    }
    return config.socketLibPrimordialsPath;
  }
  const repoRoot = config.repoRoot ?? process.cwd();
  const siblingDir = import_node_path.default.resolve(
    repoRoot,
    "..",
    "socket-lib",
    "src",
    "primordials"
  );
  if ((0, import_node_fs.existsSync)(siblingDir)) {
    return siblingDir;
  }
  const siblingLegacy = import_node_path.default.resolve(
    repoRoot,
    "..",
    "socket-lib",
    "src",
    "primordials.ts"
  );
  if ((0, import_node_fs.existsSync)(siblingLegacy)) {
    return siblingLegacy;
  }
  const installedDir = import_node_path.default.resolve(
    repoRoot,
    "node_modules",
    "@socketsecurity",
    "lib",
    "dist",
    "primordials"
  );
  if ((0, import_node_fs.existsSync)(installedDir)) {
    return installedDir;
  }
  const installedLegacy = import_node_path.default.resolve(
    repoRoot,
    "node_modules",
    "@socketsecurity",
    "lib",
    "dist",
    "primordials.d.ts"
  );
  if ((0, import_node_fs.existsSync)(installedLegacy)) {
    return installedLegacy;
  }
  throw new import_error.ErrorCtor(
    `Cannot locate socket-lib primordials source. Looked at:
  ${siblingDir}
  ${siblingLegacy}
  ${installedDir}
  ${installedLegacy}
Either clone socket-lib at ../socket-lib or run \`pnpm install\`.`
  );
}
function stripComments(src) {
  let out = src.replace(/\/\*[\s\S]*?\*\//g, "");
  out = out.replace(/^[\t ]*\/\/.*$/gm, "");
  out = out.replace(/[\t ]+\/\/.*$/gm, "");
  return out;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  checkPrimordials,
  collectJsFiles,
  extractPrimordialsNames,
  extractTsExports,
  readSocketLibPrimordialNames,
  resolveSocketLibPrimordials,
  stripComments
});
