"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.patchCompilerGlobalLocation = exports.unpatchGlobalLocation = exports.patchGlobalLocation = void 0;
const path_1 = __importDefault(require("path"));
const url_1 = require("url");
const GLOBAL_PATCHED_SYMBOL = Symbol('GLOBAL_PATCHED_SYMBOL');
/** fix issue about dart2js: https://github.com/dart-lang/sdk/issues/27979 */
function patchGlobalLocation() {
    if (!global.location) {
        const href = (0, url_1.pathToFileURL)(process.cwd()).href + path_1.default.sep;
        const location = Object.freeze({ [GLOBAL_PATCHED_SYMBOL]: true, href });
        global.location = location;
    }
}
exports.patchGlobalLocation = patchGlobalLocation;
function unpatchGlobalLocation() {
    var _a;
    if ((_a = global.location) === null || _a === void 0 ? void 0 : _a[GLOBAL_PATCHED_SYMBOL]) {
        // @ts-expect-error
        delete global.location;
    }
}
exports.unpatchGlobalLocation = unpatchGlobalLocation;
function patchCompilerGlobalLocation(compiler) {
    // https://github.com/webpack/webpack/blob/136b723023f8f26d71eabdd16badf04c1c8554e4/lib/MultiCompiler.js#L64
    compiler.hooks.run.tap('PatchGlobalLocation', patchGlobalLocation);
    compiler.hooks.watchRun.tap('PatchGlobalLocation', patchGlobalLocation);
    compiler.hooks.watchClose.tap('PatchGlobalLocation', unpatchGlobalLocation);
    compiler.hooks.done.tap('PatchGlobalLocation', unpatchGlobalLocation);
}
exports.patchCompilerGlobalLocation = patchCompilerGlobalLocation;
