"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 isolation_exports = {};
__export(isolation_exports, {
  isolatePackage: () => isolatePackage
});
module.exports = __toCommonJS(isolation_exports);
var import_fs = require("fs");
var import_platform = require("../constants/platform");
var import_node_path = __toESM(require("node:path"));
var import_npm_package_arg = __toESM(require("../external/npm-package-arg"));
var import_spawn = require("../spawn");
var import_normalize = require("../paths/normalize");
var import_operations = require("./operations");
var import_socket = require("../paths/socket");
const FS_CP_OPTIONS = {
  dereference: true,
  errorOnExist: false,
  filter: (src) => !src.includes("node_modules") && !src.endsWith(".DS_Store"),
  force: true,
  recursive: true,
  ...import_platform.WIN32 ? { maxRetries: 3, retryDelay: 100 } : {}
};
async function resolveRealPath(pathStr) {
  return await import_fs.promises.realpath(pathStr).catch(() => import_node_path.default.resolve(pathStr));
}
async function mergePackageJson(pkgJsonPath, originalPkgJson) {
  const pkgJson = JSON.parse(await import_fs.promises.readFile(pkgJsonPath, "utf8"));
  const mergedPkgJson = originalPkgJson ? { ...originalPkgJson, ...pkgJson } : pkgJson;
  return mergedPkgJson;
}
async function isolatePackage(packageSpec, options) {
  const opts = { __proto__: null, ...options };
  const { imports, install, onPackageJson, sourcePath: optSourcePath } = opts;
  let sourcePath = optSourcePath;
  let packageName;
  let spec;
  if ((0, import_normalize.isPath)(packageSpec)) {
    const trimmedPath = (0, import_normalize.trimLeadingDotSlash)(packageSpec);
    const pathToResolve = (0, import_normalize.isAbsolute)(trimmedPath) ? trimmedPath : packageSpec;
    sourcePath = import_node_path.default.resolve(pathToResolve);
    if (!(0, import_fs.existsSync)(sourcePath)) {
      throw new Error(`Source path does not exist: ${sourcePath}`);
    }
    const pkgJson = await (0, import_operations.readPackageJson)(sourcePath, { normalize: true });
    if (!pkgJson) {
      throw new Error(`Could not read package.json from: ${sourcePath}`);
    }
    packageName = pkgJson.name;
  } else {
    const parsed = (0, import_npm_package_arg.default)(packageSpec);
    packageName = parsed.name;
    if (parsed.type === "directory" || parsed.type === "file") {
      sourcePath = parsed.fetchSpec;
      if (!sourcePath || !(0, import_fs.existsSync)(sourcePath)) {
        throw new Error(`Source path does not exist: ${sourcePath}`);
      }
      if (!packageName) {
        const pkgJson = await (0, import_operations.readPackageJson)(sourcePath, { normalize: true });
        if (!pkgJson) {
          throw new Error(`Could not read package.json from: ${sourcePath}`);
        }
        packageName = pkgJson.name;
      }
    } else {
      spec = parsed.fetchSpec || parsed.rawSpec;
    }
  }
  if (!packageName) {
    throw new Error(`Could not determine package name from: ${packageSpec}`);
  }
  const sanitizedName = packageName.replace(/[@/]/g, "-");
  const tempDir = await import_fs.promises.mkdtemp(
    import_node_path.default.join((0, import_socket.getOsTmpDir)(), `socket-test-${sanitizedName}-`)
  );
  const packageTempDir = import_node_path.default.join(tempDir, sanitizedName);
  await import_fs.promises.mkdir(packageTempDir, { recursive: true });
  let installedPath;
  let originalPackageJson;
  if (spec) {
    await import_fs.promises.writeFile(
      import_node_path.default.join(packageTempDir, "package.json"),
      JSON.stringify(
        {
          name: "test-temp",
          private: true,
          version: "1.0.0"
        },
        null,
        2
      )
    );
    if (install) {
      await install(packageTempDir);
    } else {
      const packageInstallSpec = spec.startsWith("https://") ? spec : `${packageName}@${spec}`;
      await (0, import_spawn.spawn)("pnpm", ["add", packageInstallSpec], {
        cwd: packageTempDir,
        shell: import_platform.WIN32,
        stdio: "pipe"
      });
    }
    installedPath = import_node_path.default.join(packageTempDir, "node_modules", packageName);
    originalPackageJson = await (0, import_operations.readPackageJson)(installedPath, {
      normalize: true
    });
    if (sourcePath) {
      const realInstalledPath = await resolveRealPath(installedPath);
      const realSourcePath = await resolveRealPath(sourcePath);
      if (realSourcePath !== realInstalledPath) {
        await import_fs.promises.cp(sourcePath, installedPath, FS_CP_OPTIONS);
      }
    }
  } else {
    if (!sourcePath) {
      throw new Error("sourcePath is required when no version spec provided");
    }
    const scopedPath = packageName.startsWith("@") ? import_node_path.default.join(
      packageTempDir,
      "node_modules",
      packageName.split("/")[0] ?? ""
    ) : import_node_path.default.join(packageTempDir, "node_modules");
    await import_fs.promises.mkdir(scopedPath, { recursive: true });
    installedPath = import_node_path.default.join(packageTempDir, "node_modules", packageName);
    await import_fs.promises.cp(sourcePath, installedPath, FS_CP_OPTIONS);
  }
  if (onPackageJson || originalPackageJson) {
    const pkgJsonPath = import_node_path.default.join(installedPath, "package.json");
    const mergedPkgJson = await mergePackageJson(
      pkgJsonPath,
      originalPackageJson
    );
    const finalPkgJson = onPackageJson ? await onPackageJson(mergedPkgJson) : mergedPkgJson;
    await import_fs.promises.writeFile(pkgJsonPath, JSON.stringify(finalPkgJson, null, 2));
  }
  if (install) {
    await install(installedPath);
  } else {
    await (0, import_spawn.spawn)("pnpm", ["install"], {
      cwd: installedPath,
      shell: import_platform.WIN32,
      stdio: "pipe"
    });
  }
  const exports2 = imports ? { __proto__: null } : void 0;
  if (imports) {
    for (const { 0: key, 1: specifier } of Object.entries(imports)) {
      const fullPath = import_node_path.default.join(installedPath, specifier);
      exports2[key] = require(fullPath);
    }
  }
  return {
    exports: exports2,
    tmpdir: installedPath
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  isolatePackage
});
