"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.preferBrowserFilesPlugin = preferBrowserFilesPlugin;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
/**
 * Prefer sibling `.browser.*` implementation when it exists.
 *
 * Example:
 * - resolved: `/abs/path/to/streams.ts`
 * - if `/abs/path/to/streams.browser.ts` exists => use it
 */
function preferBrowserFilesPlugin() {
    return {
        name: "excelts-prefer-browser-files",
        enforce: "pre",
        async resolveId(source, importer) {
            if (source.startsWith("\0") || source.startsWith("virtual:") || source.startsWith("node:")) {
                return null;
            }
            const resolved = await this.resolve(source, importer, {
                skipSelf: true
            });
            if (!resolved) {
                return null;
            }
            if (typeof resolved === "object" && resolved.external) {
                return resolved;
            }
            const resolvedId = typeof resolved === "string" ? resolved : resolved.id;
            if (typeof resolvedId !== "string") {
                return resolved;
            }
            const cleanId = resolvedId.split("?")[0].split("#")[0];
            if (!node_path_1.default.isAbsolute(cleanId)) {
                return resolved;
            }
            if (cleanId.includes(".browser.")) {
                return resolved;
            }
            const ext = node_path_1.default.extname(cleanId);
            if (!ext || cleanId.endsWith(".d.ts")) {
                return resolved;
            }
            const candidate = cleanId.slice(0, -ext.length) + ".browser" + ext;
            if (node_fs_1.default.existsSync(candidate)) {
                return candidate;
            }
            return resolved;
        }
    };
}
