"use strict";
/* Socket Lib - Built with esbuild */
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 operations_exports = {};
__export(operations_exports, {
  extractPackage: () => extractPackage,
  findPackageExtensions: () => findPackageExtensions,
  getReleaseTag: () => getReleaseTag,
  packPackage: () => packPackage,
  readPackageJson: () => readPackageJson,
  readPackageJsonSync: () => readPackageJsonSync,
  resolveGitHubTgzUrl: () => resolveGitHubTgzUrl,
  resolvePackageName: () => resolvePackageName,
  resolveRegistryPackageName: () => resolveRegistryPackageName
});
module.exports = __toCommonJS(operations_exports);
var import_packages = require("../constants/packages");
var import_process = require("../constants/process");
var import_socket = require("../constants/socket");
var import_cacache = __toESM(require("../external/cacache"));
var import_libnpmpack = __toESM(require("../external/libnpmpack"));
var import_make_fetch_happen = __toESM(require("../external/make-fetch-happen"));
var import_npm_package_arg = __toESM(require("../external/npm-package-arg"));
var import_packageurl_js = require("../external/@socketregistry/packageurl-js");
var import_pacote = __toESM(require("../external/pacote"));
var semver = __toESM(require("../external/semver"));
var import_fs = require("../fs");
var import_objects = require("../objects");
var import_normalize = require("./normalize");
var import_packages2 = require("../paths/packages");
var import_specs = require("./specs");
var import_editable = require("./editable");
const abortSignal = (0, import_process.getAbortSignal)();
const packageExtensions = (0, import_packages.getPackageExtensions)();
const packumentCache = (0, import_packages.getPackumentCache)();
const pacoteCachePath = (0, import_packages.getPacoteCachePath)();
const fetcher = import_make_fetch_happen.default.defaults({
  cachePath: pacoteCachePath,
  // Prefer-offline: Staleness checks for cached data will be bypassed, but
  // missing data will be requested from the server.
  // https://github.com/npm/make-fetch-happen?tab=readme-ov-file#--optscache
  cache: "force-cache"
});
// @__NO_SIDE_EFFECTS__
async function extractPackage(pkgNameOrId, options, callback) {
  let actualCallback = callback;
  let actualOptions = options;
  if (arguments.length === 2 && typeof options === "function") {
    actualCallback = options;
    actualOptions = void 0;
  }
  const { dest, tmpPrefix, ...extractOptions_ } = {
    __proto__: null,
    ...actualOptions
  };
  const extractOptions = {
    packumentCache,
    preferOffline: true,
    ...extractOptions_
  };
  if (typeof dest === "string") {
    await import_pacote.default.extract(pkgNameOrId, dest, extractOptions);
    if (typeof actualCallback === "function") {
      await actualCallback(dest);
    }
  } else {
    await import_cacache.default.tmp.withTmp(
      pacoteCachePath,
      { tmpPrefix },
      async (tmpDirPath) => {
        await import_pacote.default.extract(pkgNameOrId, tmpDirPath, extractOptions);
        if (typeof actualCallback === "function") {
          await actualCallback(tmpDirPath);
        }
      }
    );
  }
}
// @__NO_SIDE_EFFECTS__
function findPackageExtensions(pkgName, pkgVer) {
  let result;
  for (const entry of packageExtensions) {
    const selector = String(entry[0]);
    const ext = entry[1];
    const lastAtSignIndex = selector.lastIndexOf("@");
    const name = selector.slice(0, lastAtSignIndex);
    if (pkgName === name) {
      const range = selector.slice(lastAtSignIndex + 1);
      if (semver.satisfies(pkgVer, range)) {
        if (result === void 0) {
          result = {};
        }
        if (typeof ext === "object" && ext !== null) {
          (0, import_objects.merge)(result, ext);
        }
      }
    }
  }
  return result;
}
// @__NO_SIDE_EFFECTS__
function getReleaseTag(spec) {
  if (!spec) {
    return "";
  }
  let atIndex = -1;
  if (spec.startsWith("@")) {
    atIndex = spec.indexOf("@", 1);
  } else {
    atIndex = spec.indexOf("@");
  }
  if (atIndex !== -1) {
    return spec.slice(atIndex + 1);
  }
  return "";
}
// @__NO_SIDE_EFFECTS__
async function packPackage(spec, options) {
  return await (0, import_libnpmpack.default)(spec, {
    __proto__: null,
    signal: abortSignal,
    ...options,
    packumentCache,
    preferOffline: true
  });
}
// @__NO_SIDE_EFFECTS__
async function readPackageJson(filepath, options) {
  const { editable, normalize, throws, ...normalizeOptions } = {
    __proto__: null,
    ...options
  };
  const pkgJson = await (0, import_fs.readJson)((0, import_packages2.resolvePackageJsonPath)(filepath), {
    throws
  });
  if (pkgJson) {
    if (editable) {
      return await (0, import_editable.toEditablePackageJson)(pkgJson, {
        path: filepath,
        normalize,
        ...normalizeOptions
      });
    }
    return normalize ? (0, import_normalize.normalizePackageJson)(pkgJson, normalizeOptions) : pkgJson;
  }
  return void 0;
}
// @__NO_SIDE_EFFECTS__
function readPackageJsonSync(filepath, options) {
  const { editable, normalize, throws, ...normalizeOptions } = {
    __proto__: null,
    ...options
  };
  const pkgJson = (0, import_fs.readJsonSync)((0, import_packages2.resolvePackageJsonPath)(filepath), { throws });
  if (pkgJson) {
    if (editable) {
      return (0, import_editable.toEditablePackageJsonSync)(pkgJson, {
        path: filepath,
        normalize,
        ...normalizeOptions
      });
    }
    return normalize ? (0, import_normalize.normalizePackageJson)(pkgJson, normalizeOptions) : pkgJson;
  }
  return void 0;
}
// @__NO_SIDE_EFFECTS__
async function resolveGitHubTgzUrl(pkgNameOrId, where) {
  const whereIsPkgJson = (0, import_objects.isObjectObject)(where);
  const pkgJson = whereIsPkgJson ? where : await /* @__PURE__ */ readPackageJson(where, { normalize: true });
  if (!pkgJson) {
    return "";
  }
  const { version } = pkgJson;
  const parsedSpec = (0, import_npm_package_arg.default)(
    pkgNameOrId,
    whereIsPkgJson ? void 0 : where
  );
  const isTarballUrl = (0, import_specs.isGitHubTgzSpec)(parsedSpec);
  if (isTarballUrl) {
    return parsedSpec.saveSpec || "";
  }
  const isGitHubUrl = (0, import_specs.isGitHubUrlSpec)(parsedSpec);
  const repository = pkgJson.repository;
  const { project, user } = (isGitHubUrl ? parsedSpec.hosted : (0, import_specs.getRepoUrlDetails)(repository?.url)) || { project: "", user: "" };
  if (user && project) {
    let apiUrl = "";
    if (isGitHubUrl) {
      apiUrl = (0, import_specs.gitHubTagRefUrl)(user, project, parsedSpec.gitCommittish || "");
    } else {
      const versionStr = version;
      apiUrl = (0, import_specs.gitHubTagRefUrl)(user, project, `v${versionStr}`);
      if (!(await fetcher(apiUrl, { method: "head" })).ok) {
        apiUrl = (0, import_specs.gitHubTagRefUrl)(user, project, versionStr);
        if (!(await fetcher(apiUrl, { method: "head" })).ok) {
          apiUrl = "";
        }
      }
    }
    if (apiUrl) {
      const resp = await fetcher(apiUrl);
      const json = await resp.json();
      const sha = json?.object?.sha;
      if (sha) {
        return (0, import_specs.gitHubTgzUrl)(user, project, sha);
      }
    }
  }
  return "";
}
// @__NO_SIDE_EFFECTS__
function resolvePackageName(purlObj, delimiter = "/") {
  const { name, namespace } = purlObj;
  return `${namespace ? `${namespace}${delimiter}` : ""}${name}`;
}
// @__NO_SIDE_EFFECTS__
function resolveRegistryPackageName(pkgName) {
  const purlObj = import_packageurl_js.PackageURL.fromString(`pkg:npm/${pkgName}`);
  return purlObj.namespace ? `${purlObj.namespace.slice(1)}${import_socket.REGISTRY_SCOPE_DELIMITER}${purlObj.name}` : pkgName;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  extractPackage,
  findPackageExtensions,
  getReleaseTag,
  packPackage,
  readPackageJson,
  readPackageJsonSync,
  resolveGitHubTgzUrl,
  resolvePackageName,
  resolveRegistryPackageName
});
