import { existsSync } from "node:fs";
import path from "node:path";
import { __dirname } from "./plugin-loader.helpers.js";
const SERVER_PACKAGE_ROOT = path.resolve(__dirname, "../..");
const BUNDLED_PLUGIN_PACKAGE_DIRS = new Map([
    ["@rudderhq/plugin-linear", "plugin-linear"],
]);
export function resolvePluginPackageCandidateDirs(localPluginDir, packageName, packagePath, options = {}) {
    const candidates = [];
    if (packagePath && existsSync(packagePath)) {
        candidates.push(path.resolve(packagePath));
    }
    if (packageName.startsWith("@")) {
        candidates.push(path.join(localPluginDir, "node_modules", ...packageName.split("/")));
    }
    else {
        candidates.push(path.join(localPluginDir, "node_modules", packageName));
    }
    candidates.push(path.join(localPluginDir, packageName));
    const bundledPluginDirName = BUNDLED_PLUGIN_PACKAGE_DIRS.get(packageName);
    if (bundledPluginDirName) {
        candidates.push(path.join(options.serverPackageRoot ?? SERVER_PACKAGE_ROOT, "dist", "bundled-plugins", bundledPluginDirName));
    }
    return [...new Set(candidates.map((candidate) => path.resolve(candidate)))];
}
export function resolveWorkerEntrypoint(plugin, localPluginDir, options = {}) {
    const manifest = plugin.manifestJson;
    const workerRelPath = manifest.entrypoints.worker;
    const packageName = plugin.packageName;
    const checkedEntrypoints = [];
    for (const dir of resolvePluginPackageCandidateDirs(localPluginDir, packageName, plugin.packagePath, options)) {
        const entrypoint = path.resolve(dir, workerRelPath);
        checkedEntrypoints.push(entrypoint);
        // Security: ensure entrypoint is actually inside the directory (prevent path traversal)
        if (!isPathInsideDir(entrypoint, dir)) {
            continue;
        }
        if (existsSync(entrypoint)) {
            return entrypoint;
        }
    }
    // Fallback: try the worker path as-is (absolute or relative to cwd)
    // ONLY if it's already an absolute path and we trust the manifest (which we've already validated)
    if (path.isAbsolute(workerRelPath) && existsSync(workerRelPath)) {
        return workerRelPath;
    }
    throw new Error(`Worker entrypoint not found for plugin "${plugin.pluginKey}". ` +
        `Checked: ${checkedEntrypoints.join(", ")}`);
}
export function resolveManagedInstallPackageDir(localPluginDir, packageName) {
    if (packageName.startsWith("@")) {
        return path.join(localPluginDir, "node_modules", ...packageName.split("/"));
    }
    return path.join(localPluginDir, "node_modules", packageName);
}
export function isPathInsideDir(candidatePath, parentDir) {
    const resolvedCandidate = path.resolve(candidatePath);
    const resolvedParent = path.resolve(parentDir);
    const relative = path.relative(resolvedParent, resolvedCandidate);
    return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
//# sourceMappingURL=plugin-loader.worker-paths.js.map