"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 parse_lockfile_exports = {};
__export(parse_lockfile_exports, {
  addToIndex: () => addToIndex,
  buildPackageRef: () => buildPackageRef,
  jsParsePackageLock: () => jsParsePackageLock,
  parsePackageLock: () => parsePackageLock,
  parseV1: () => parseV1,
  parseV2V3: () => parseV2V3,
  resolveDepType: () => resolveDepType
});
module.exports = __toCommonJS(parse_lockfile_exports);
var import_manifest_error = require("../../manifest/manifest-error");
var import_message = require("../../../errors/message");
var import_array = require("../../../primordials/array");
var import_error = require("../../../primordials/error");
var import_json = require("../../../primordials/json");
var import_map_set = require("../../../primordials/map-set");
var import_object = require("../../../primordials/object");
var import_manifest = require("../../../smol/manifest");
var import_extract_package_name_from_path = require("./extract-package-name-from-path");
var import_parse_git_url = require("./parse-git-url");
var import_string = require("../../../primordials/string");
const MAX_LOCKFILE_DEPTH = 64;
function addToIndex(packageIndex, name, idx) {
  const existing = packageIndex[name];
  if (existing === void 0) {
    packageIndex[name] = idx;
  } else if (typeof existing === "number") {
    packageIndex[name] = [existing, idx];
  } else {
    (0, import_array.ArrayPrototypePush)(existing, idx);
  }
}
function buildPackageRef(name, pkg) {
  let vcsUrl;
  let vcsCommit;
  if (typeof pkg.resolved === "string") {
    const gitMatch = (0, import_parse_git_url.parseGitUrl)(pkg.resolved);
    if (gitMatch) {
      vcsUrl = gitMatch.url;
      vcsCommit = gitMatch.commit;
    }
  }
  const depsKey = pkg.dependencies ?? pkg.requires;
  const dependencies = depsKey && typeof depsKey === "object" ? (0, import_object.ObjectKeys)(depsKey) : [];
  let effectiveName = name;
  let version = typeof pkg.version === "string" ? pkg.version : "0.0.0";
  if ((0, import_string.StringPrototypeStartsWith)(version, "npm:")) {
    const rest = (0, import_string.StringPrototypeSlice)(version, "npm:".length);
    const atIdx = (0, import_string.StringPrototypeLastIndexOf)(rest, "@");
    if (atIdx > 0) {
      effectiveName = (0, import_string.StringPrototypeSlice)(rest, 0, atIdx);
      version = (0, import_string.StringPrototypeSlice)(rest, atIdx + 1);
    }
  }
  return (0, import_object.ObjectFreeze)({
    __proto__: null,
    name: effectiveName,
    version,
    resolved: typeof pkg.resolved === "string" ? pkg.resolved : void 0,
    integrity: typeof pkg.integrity === "string" ? pkg.integrity : void 0,
    ecosystem: "npm",
    depType: resolveDepType(pkg),
    isDev: !!pkg.dev,
    isOptional: !!pkg.optional,
    isPeer: !!pkg.peer,
    isBundled: !!pkg.inBundle,
    license: typeof pkg.license === "string" ? pkg.license : void 0,
    vcsUrl,
    vcsCommit,
    dependencies
  });
}
function jsParsePackageLock(content) {
  let data;
  try {
    data = (0, import_json.JSONParse)(content);
  } catch (e) {
    throw new import_manifest_error.ManifestError(
      `Invalid JSON: ${(0, import_message.errorMessage)(e)}`,
      "ERR_INVALID_JSON"
    );
  }
  if (data.packages) {
    return parseV2V3(data, data.packages);
  }
  if (data.dependencies) {
    return parseV1(data, data.dependencies);
  }
  return (0, import_object.ObjectFreeze)({
    __proto__: null,
    type: "lockfile",
    lockVersion: String(data.lockfileVersion ?? 1),
    ecosystem: "npm",
    packages: (0, import_object.ObjectFreeze)([]),
    _index: { __proto__: null }
  });
}
function parseV1(data, rootDeps) {
  const packageIndex = {
    __proto__: null
  };
  const packages = [];
  const visited = new import_map_set.SetCtor();
  const flatten = (deps, parentPath, depth) => {
    if (depth > MAX_LOCKFILE_DEPTH) {
      throw new import_error.RangeErrorCtor(
        `Lockfile dependency nesting exceeds ${MAX_LOCKFILE_DEPTH} levels at ${parentPath}`
      );
    }
    const depKeys = (0, import_object.ObjectKeys)(deps);
    for (let di = 0, { length } = depKeys; di < length; di++) {
      const name = depKeys[di];
      const pkg = deps[name];
      const version = typeof pkg.version === "string" ? pkg.version : "0.0.0";
      const key = `${name}@${version}`;
      if (visited.has(key)) {
        continue;
      }
      if (packageIndex[name] === void 0) {
        const ref = buildPackageRef(name, pkg);
        (0, import_array.ArrayPrototypePush)(packages, ref);
        packageIndex[name] = packages.length - 1;
      }
      if (pkg.dependencies && typeof pkg.dependencies === "object") {
        visited.add(key);
        flatten(
          pkg.dependencies,
          `${parentPath}/${name}`,
          depth + 1
        );
        visited.delete(key);
      }
    }
  };
  flatten(rootDeps, "", 0);
  return (0, import_object.ObjectFreeze)({
    __proto__: null,
    type: "lockfile",
    lockVersion: String(data.lockfileVersion ?? 1),
    ecosystem: "npm",
    packages: (0, import_object.ObjectFreeze)(packages),
    _index: packageIndex
  });
}
function parseV2V3(data, rawPackages) {
  const packageIndex = {
    __proto__: null
  };
  const pkgKeys = (0, import_object.ObjectKeys)(rawPackages);
  const packages = (0, import_array.ArrayFrom)({
    length: rawPackages[""] !== void 0 ? pkgKeys.length - 1 : pkgKeys.length
  });
  let pkgCount = 0;
  for (let ki = 0, { length } = pkgKeys; ki < length; ki++) {
    const pkgPath = pkgKeys[ki];
    if (pkgPath === "") {
      continue;
    }
    const pkg = rawPackages[pkgPath];
    const nameFromPath = (0, import_extract_package_name_from_path.extractPackageNameFromPath)(pkgPath);
    const name = typeof pkg.name === "string" && pkg.name.length > 0 ? pkg.name : nameFromPath;
    const ref = buildPackageRef(name, pkg);
    packages[pkgCount] = ref;
    addToIndex(packageIndex, name, pkgCount);
    pkgCount++;
  }
  packages.length = pkgCount;
  return (0, import_object.ObjectFreeze)({
    __proto__: null,
    type: "lockfile",
    lockVersion: String(data.lockfileVersion ?? 1),
    ecosystem: "npm",
    packages: (0, import_object.ObjectFreeze)(packages),
    _index: packageIndex
  });
}
function resolveDepType(pkg) {
  if (pkg.dev) {
    return "dev";
  }
  if (pkg.optional) {
    return "optional";
  }
  if (pkg.peer) {
    return "peer";
  }
  return "prod";
}
const _smol = (0, import_manifest.getSmolManifest)();
const parsePackageLock = _smol ? (
  /* c8 ignore next 2 - smol Node binary only. */
  (content) => _smol.parseLockfile(content, "npm", "npm")
) : jsParsePackageLock;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  addToIndex,
  buildPackageRef,
  jsParsePackageLock,
  parsePackageLock,
  parseV1,
  parseV2V3,
  resolveDepType
});
