"use strict";
exports.ids = [
    "323"
];
exports.modules = {
    "./webpack/plugin-browsers/run-chromium/chromium-launch/setup-cdp-after-launch.ts" (__unused_rspack_module, __webpack_exports__, __webpack_require__) {
        __webpack_require__.d(__webpack_exports__, {
            setupCdpAfterLaunch: ()=>setupCdpAfterLaunch
        });
        var messages = __webpack_require__("./webpack/plugin-browsers/browsers-lib/messages.ts");
        var shared_utils = __webpack_require__("./webpack/plugin-browsers/browsers-lib/shared-utils.ts");
        var banner = __webpack_require__("./webpack/plugin-browsers/browsers-lib/banner.ts");
        var external_path_ = __webpack_require__("path");
        var external_fs_ = __webpack_require__("fs");
        async function deriveExtensionIdFromTargetsHelper(cdp, outPath, maxRetries = 6, backoffMs = 150, profilePath, extensionPaths) {
            let expectedName;
            let expectedVersion;
            let expectedManifestVersion;
            let expectedNameIsMsg = false;
            try {
                const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(outPath, 'manifest.json'), 'utf-8'));
                expectedName = manifest?.name;
                expectedVersion = manifest?.version;
                expectedManifestVersion = manifest?.manifest_version;
                expectedNameIsMsg = 'string' == typeof expectedName && /__MSG_/i.test(expectedName);
                if (expectedNameIsMsg) {
                    const defaultLocale = String(manifest?.default_locale || '').trim();
                    const msgKeyMatch = String(expectedName || '').match(/__MSG_(.+)__/i);
                    const msgKey = msgKeyMatch ? msgKeyMatch[1] : '';
                    if (defaultLocale && msgKey) {
                        const messagesPath = external_path_.join(outPath, '_locales', defaultLocale, 'messages.json');
                        if (external_fs_.existsSync(messagesPath)) {
                            const messagesJson = JSON.parse(external_fs_.readFileSync(messagesPath, 'utf-8'));
                            const resolved = String(messagesJson?.[msgKey]?.message || '').trim();
                            if (resolved) {
                                expectedName = resolved;
                                expectedNameIsMsg = false;
                            }
                        }
                    }
                }
            } catch  {}
            const trimTrailingSep = (p)=>p.replace(/[\\\/]+$/g, '');
            const normalizePath = (p)=>{
                try {
                    const resolved = external_path_.resolve(p);
                    if (external_fs_.existsSync(resolved)) return trimTrailingSep(external_fs_.realpathSync(resolved));
                    return trimTrailingSep(resolved);
                } catch  {
                    return trimTrailingSep(external_path_.resolve(p));
                }
            };
            const resolvedOutPath = normalizePath(outPath);
            const normalizedCandidates = Array.isArray(extensionPaths) ? extensionPaths.map((p)=>p ? normalizePath(p) : '').filter(Boolean) : [];
            const resolvedCandidates = normalizedCandidates.length ? normalizedCandidates : [
                resolvedOutPath
            ];
            const platformIsCaseInsensitive = 'win32' === process.platform || 'darwin' === process.platform;
            const normalizeForCompare = (p)=>platformIsCaseInsensitive ? p.toLowerCase() : p;
            const matchesAnyCandidate = (p)=>{
                const n = normalizeForCompare(p);
                return resolvedCandidates.some((candidate)=>n === normalizeForCompare(candidate));
            };
            const deriveFromProfile = ()=>{
                if (!profilePath) return null;
                const candidates = [];
                const pushPrefIfExists = (dir)=>{
                    const prefPath = external_path_.join(dir, 'Preferences');
                    if (external_fs_.existsSync(prefPath)) candidates.push(prefPath);
                };
                try {
                    pushPrefIfExists(profilePath);
                    pushPrefIfExists(external_path_.join(profilePath, 'Default'));
                    const entries = external_fs_.readdirSync(profilePath);
                    for (const entry of entries)if (/^Profile\s+\d+$/i.test(entry)) pushPrefIfExists(external_path_.join(profilePath, entry));
                } catch  {}
                for (const prefPath of candidates)try {
                    if (!external_fs_.existsSync(prefPath)) continue;
                    const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
                    const settings = prefs?.extensions?.settings;
                    if (!settings || 'object' != typeof settings) continue;
                    const entries = Object.entries(settings);
                    let fallbackId = null;
                    for (const [id, info] of entries){
                        const storedPath = String(info?.path || '');
                        if (!storedPath) continue;
                        const normalized = normalizePath(storedPath);
                        if (!matchesAnyCandidate(normalized)) continue;
                        const manifestName = String(info?.manifest?.name || '');
                        const manifestVersion = String(info?.manifest?.version || '');
                        if (expectedName && manifestName === expectedName) return id;
                        if (expectedVersion && manifestVersion === expectedVersion) return id;
                        fallbackId = id;
                    }
                    if (fallbackId) return fallbackId;
                } catch  {}
                return null;
            };
            let retries = 0;
            let deferredFirstEvalId = null;
            let deferredUrlDerivedId = null;
            const hasExpectedManifestIdentity = Boolean(expectedName || expectedVersion || expectedManifestVersion);
            while(retries <= maxRetries){
                try {
                    const targets = await cdp.getTargets();
                    const profileCandidateId = deriveFromProfile();
                    let firstEvalId = null;
                    let evalIdCount = 0;
                    let urlDerivedId = null;
                    for (const t of targets || []){
                        const url = String(t?.url || '');
                        const type = String(t?.type || '');
                        const typeOk = [
                            'service_worker',
                            'background_page',
                            'worker'
                        ].includes(type);
                        if (!typeOk) continue;
                        const urlMatch = url.match(/^chrome-extension:\/\/([^\/]+)/);
                        if (!urlDerivedId && urlMatch?.[1]) urlDerivedId = String(urlMatch[1]);
                        if (url && !url.startsWith('chrome-extension://')) continue;
                        const targetId = t?.targetId;
                        if (targetId) try {
                            const sessionId = await cdp.attachToTarget(targetId);
                            if (!sessionId) continue;
                            await cdp.sendCommand('Runtime.enable', {}, sessionId);
                            const info = await cdp.evaluate(sessionId, '(()=>{try{const m=chrome.runtime.getManifest?.();return {id:chrome.runtime?.id||"",name:m?.name||"",version:m?.version||"",manifestVersion:m?.manifest_version||0}}catch(_){return null}})()');
                            const id = String(info?.id || '').trim();
                            if (!id) continue;
                            evalIdCount += 1;
                            if (!firstEvalId) firstEvalId = id;
                            if (profileCandidateId && id === profileCandidateId) return id;
                            const gotName = String(info?.name || '');
                            const gotVersion = String(info?.version || '');
                            const gotManifestVersion = Number(info?.manifestVersion || 0);
                            const nameMatches = expectedName && !expectedNameIsMsg ? gotName === expectedName : false;
                            const versionMatches = expectedVersion ? gotVersion === expectedVersion : false;
                            const manifestVersionMatches = expectedManifestVersion ? gotManifestVersion === expectedManifestVersion : false;
                            if (nameMatches && (!profileCandidateId || id === profileCandidateId)) return id;
                            if (expectedVersion && versionMatches && (expectedManifestVersion ? manifestVersionMatches : true) && (!profileCandidateId || id === profileCandidateId)) return id;
                        } catch  {}
                    }
                    if (1 === evalIdCount && firstEvalId) {
                        if (!hasExpectedManifestIdentity) return firstEvalId;
                        deferredFirstEvalId = deferredFirstEvalId || firstEvalId;
                    }
                    if (profileCandidateId) return profileCandidateId;
                    if (urlDerivedId) {
                        if (!hasExpectedManifestIdentity) return urlDerivedId;
                        deferredUrlDerivedId = deferredUrlDerivedId || urlDerivedId;
                    }
                } catch  {}
                await new Promise((r)=>setTimeout(r, backoffMs));
                retries++;
            }
            return deriveFromProfile() || deferredFirstEvalId || deferredUrlDerivedId;
        }
        var cdp_client = __webpack_require__("./webpack/plugin-browsers/run-chromium/chromium-source-inspection/cdp-client.ts");
        var discovery = __webpack_require__("./webpack/plugin-browsers/run-chromium/chromium-source-inspection/discovery.ts");
        function isRecoverableBootstrapError(error) {
            const msg = String(error?.message || error || '').toLowerCase();
            return msg.includes('econnreset') || msg.includes('websocket is not open') || msg.includes('cdp connection closed') || msg.includes('socket hang up') || msg.includes('timed out') || msg.includes('no cdp websocket url');
        }
        async function connectToChromeCdp(cdpPort) {
            let retries = 0;
            const maxRetries = 60;
            const backoffMs = 250;
            while(retries < maxRetries){
                const ready = await (0, discovery.z)(cdpPort);
                if (ready) break;
                retries++;
                await new Promise((r)=>setTimeout(r, backoffMs));
            }
            const maxBootstrapAttempts = 4;
            let lastError = null;
            for(let attempt = 1; attempt <= maxBootstrapAttempts; attempt++){
                const cdp = new cdp_client.n(cdpPort, '127.0.0.1');
                try {
                    await cdp.connect();
                    await cdp.sendCommand('Target.setDiscoverTargets', {
                        discover: true
                    });
                    await cdp.sendCommand('Target.setAutoAttach', {
                        autoAttach: true,
                        waitForDebuggerOnStart: false,
                        flatten: true
                    });
                    return cdp;
                } catch (error) {
                    lastError = error;
                    cdp.disconnect();
                    const retryable = isRecoverableBootstrapError(error);
                    const hasMoreAttempts = attempt < maxBootstrapAttempts;
                    if ('true' === process.env.EXTENSION_AUTHOR_MODE) {
                        const base = String(error?.message || error);
                        console.warn(`[CDP] bootstrap attempt ${attempt}/${maxBootstrapAttempts} failed: ${base}`);
                    }
                    if (!retryable || !hasMoreAttempts) throw error;
                    const delayMs = 120 * attempt;
                    await new Promise((r)=>setTimeout(r, delayMs));
                }
            }
            throw lastError instanceof Error ? lastError : new Error('Failed to bootstrap CDP connection');
        }
        async function loadUnpackedIfNeeded(cdp, outPath) {
            try {
                const response = await cdp.sendCommand('Extensions.loadUnpacked', {
                    extensionPath: outPath,
                    options: {
                        failOnError: false
                    }
                });
                const id = String(response?.extensionId || '');
                return id || null;
            } catch  {
                return null;
            }
        }
        function readManifestInfo(outPath) {
            try {
                const manifestPath = external_path_.join(outPath, 'manifest.json');
                const manifest = JSON.parse(external_fs_.readFileSync(manifestPath, 'utf-8'));
                return {
                    name: manifest?.name,
                    version: manifest?.version
                };
            } catch  {
                return null;
            }
        }
        function registerAutoEnableLogging(cdp, getExtensionId) {
            cdp.onProtocolEvent((message)=>{
                try {
                    if (!message || !message.method) return;
                    if ('Target.attachedToTarget' === message.method) {
                        const params = message.params || {};
                        const targetInfo = params.targetInfo || {};
                        const sessionId = params.sessionId;
                        const url = String(targetInfo.url || '');
                        const type = String(targetInfo.type || '');
                        const extId = getExtensionId();
                        const matchesExtension = !!(extId && url.includes(`chrome-extension://${extId}/`) || 'service_worker' === type);
                        if (sessionId && matchesExtension) {
                            cdp.sendCommand('Runtime.enable', {}, sessionId).catch(()=>{});
                            cdp.sendCommand('Log.enable', {}, sessionId).catch(()=>{});
                        }
                    } else if ('Runtime.consoleAPICalled' === message.method || 'Log.entryAdded' === message.method) {
                        if ('1' === String(process.env.EXTENSION_VERBOSE || '').trim()) {
                            const ts = new Date().toISOString();
                            console.log(messages.bvI(ts, message.params));
                        }
                    }
                } catch (error) {
                    if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.KK1(String(error?.message || error)));
                }
            });
        }
        function _define_property(obj, key, value) {
            if (key in obj) Object.defineProperty(obj, key, {
                value: value,
                enumerable: true,
                configurable: true,
                writable: true
            });
            else obj[key] = value;
            return obj;
        }
        class CDPExtensionController {
            async connect() {
                if (this.cdp) return;
                await this.connectFreshClient();
            }
            async ensureLoaded() {
                if (!this.cdp) throw new Error('CDP not connected');
                const exists = external_fs_.existsSync(this.outPath);
                if (!exists) throw new Error(`Output path not found: ${this.outPath}`);
                if (!this.extensionId) {
                    const id = await this.deriveExtensionIdFromTargets();
                    if (id) this.extensionId = id;
                }
                if (this.extensionId) {
                    const belongsToOutPath = this.extensionIdBelongsToOutPath(this.extensionId);
                    if (false === belongsToOutPath) this.extensionId = null;
                }
                if (this.extensionId) try {
                    let info = null;
                    try {
                        info = await this.cdp.getExtensionInfo(this.extensionId);
                    } catch  {}
                    if (!info) {
                        const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(this.outPath, 'manifest.json'), 'utf-8'));
                        return {
                            extensionId: this.extensionId,
                            name: manifest.name,
                            version: manifest.version
                        };
                    }
                    return {
                        extensionId: this.extensionId,
                        name: info?.extensionInfo?.name,
                        version: info?.extensionInfo?.version
                    };
                } catch  {}
                try {
                    if (!this.extensionId && this.shouldAttemptLoadUnpacked()) {
                        const id = await loadUnpackedIfNeeded(this.cdp, this.outPath);
                        if (id) this.extensionId = id;
                    }
                    if (!this.extensionId) this.extensionId = await this.deriveExtensionIdFromTargets(10, 150);
                    if (!this.extensionId) throw new Error('Failed to determine extension ID via CDP');
                    await this.enableLogging();
                    let name;
                    let version;
                    try {
                        const info = await this.cdp.getExtensionInfo(this.extensionId);
                        name = info?.extensionInfo?.name;
                        version = info?.extensionInfo?.version;
                    } catch (error) {
                        try {
                            const manifest = readManifestInfo(this.outPath);
                            name = String(manifest?.name || '') || void 0;
                            version = String(manifest?.version || '') || void 0;
                        } catch (e2) {
                            if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn('[CDP] Fallback manifest read failed:', String(e2?.message || e2));
                        }
                    }
                    return {
                        extensionId: this.extensionId,
                        name,
                        version
                    };
                } catch (error) {
                    throw new Error(`Failed to load extension from ${external_path_.resolve(this.outPath)}: ${String(error.message || error)}`);
                }
            }
            async deriveExtensionIdFromTargets(maxRetries = 20, backoffMs = 200) {
                if (!this.cdp) return null;
                return await deriveExtensionIdFromTargetsHelper(this.cdp, this.outPath, maxRetries, backoffMs, this.profilePath, this.extensionPaths);
            }
            shouldAttemptLoadUnpacked() {
                const normalizedOutPath = this.normalizePath(this.outPath);
                const normalizedExtensionPaths = (this.extensionPaths || []).map((candidate)=>String(candidate || '').trim()).filter(Boolean).map((candidate)=>this.normalizePath(candidate));
                if (0 === normalizedExtensionPaths.length) return true;
                return !normalizedExtensionPaths.includes(normalizedOutPath);
            }
            normalizePath(input) {
                try {
                    return external_fs_.realpathSync(external_path_.resolve(input));
                } catch  {
                    return external_path_.resolve(input);
                }
            }
            extensionIdBelongsToOutPath(extensionId) {
                if (!this.profilePath || !extensionId) return null;
                const prefCandidates = [];
                const addPrefCandidate = (dir)=>{
                    const prefPath = external_path_.join(dir, 'Preferences');
                    if (external_fs_.existsSync(prefPath)) prefCandidates.push(prefPath);
                };
                try {
                    addPrefCandidate(this.profilePath);
                    addPrefCandidate(external_path_.join(this.profilePath, 'Default'));
                    for (const entry of external_fs_.readdirSync(this.profilePath))if (/^Profile\s+\d+$/i.test(entry)) addPrefCandidate(external_path_.join(this.profilePath, entry));
                } catch  {}
                if (0 === prefCandidates.length) return null;
                const normalizedOutPath = this.normalizePath(this.outPath);
                for (const prefPath of prefCandidates)try {
                    const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
                    const settings = prefs?.extensions?.settings;
                    const info = settings?.[extensionId];
                    const storedPath = String(info?.path || '');
                    if (!storedPath) continue;
                    return this.normalizePath(storedPath) === normalizedOutPath;
                } catch  {}
                return null;
            }
            getDeveloperModeStatus() {
                if (!this.profilePath) return 'unknown';
                const prefCandidates = [];
                const seen = new Set();
                const addPrefCandidate = (dir)=>{
                    const prefPath = external_path_.join(dir, 'Preferences');
                    if (!external_fs_.existsSync(prefPath)) return;
                    const dedupeKey = external_path_.resolve(prefPath);
                    if (seen.has(dedupeKey)) return;
                    seen.add(dedupeKey);
                    prefCandidates.push(prefPath);
                };
                try {
                    addPrefCandidate(this.profilePath);
                    addPrefCandidate(external_path_.join(this.profilePath, 'Default'));
                    for (const entry of external_fs_.readdirSync(this.profilePath))if (/^Profile\s+\d+$/i.test(entry)) addPrefCandidate(external_path_.join(this.profilePath, entry));
                } catch  {}
                for (const prefPath of prefCandidates)try {
                    const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
                    const uiFlag = prefs?.extensions?.ui?.developer_mode;
                    if ('boolean' == typeof uiFlag) return uiFlag ? 'enabled' : 'disabled';
                    const legacyFlag = prefs?.extensions?.developer_mode;
                    if ('boolean' == typeof legacyFlag) return legacyFlag ? 'enabled' : 'disabled';
                } catch  {}
                return 'unknown';
            }
            async hardReload() {
                if (!this.extensionId) return false;
                try {
                    if (!this.cdp) await this.connectFreshClient();
                    if (this.cdp && await this.cdp.forceReloadExtension(this.extensionId)) return true;
                } catch  {}
                try {
                    await this.reconnectForReload();
                    return Boolean(this.cdp && this.extensionId && await this.cdp.forceReloadExtension(this.extensionId));
                } catch  {
                    return false;
                }
            }
            async connectFreshClient() {
                this.cdp = await connectToChromeCdp(this.cdpPort);
                try {
                    await this.cdp.sendCommand('Target.setDiscoverTargets', {
                        discover: true
                    });
                    await this.cdp.sendCommand('Target.setAutoAttach', {
                        autoAttach: true,
                        waitForDebuggerOnStart: false,
                        flatten: true
                    });
                } catch (error) {
                    if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.wXK(String(error?.message || error)));
                }
                registerAutoEnableLogging(this.cdp, ()=>this.extensionId);
            }
            async reconnectForReload() {
                try {
                    this.cdp?.disconnect?.();
                } catch  {}
                this.cdp = null;
                await this.connectFreshClient();
                try {
                    const derivedExtensionId = await this.deriveExtensionIdFromTargets(10, 150);
                    if (derivedExtensionId) this.extensionId = derivedExtensionId;
                } catch  {}
            }
            onProtocolEvent(cb) {
                if (!this.cdp) throw new Error('CDP not connected');
                this.cdp.onProtocolEvent((raw)=>{
                    const evt = raw;
                    cb(evt);
                });
            }
            clearProtocolEventHandler() {
                if (!this.cdp) return;
                this.cdp.onProtocolEvent(()=>{});
            }
            async enableUnifiedLogging() {
                if (!this.cdp) return;
                try {
                    await this.cdp.enableAutoAttach();
                    await this.cdp.enableRuntimeAndLog();
                    try {
                        const targets = await this.cdp.getTargets();
                        for (const t of targets || []){
                            const type = String(t?.type || '');
                            if ('page' === type || 'service_worker' === type || 'background_page' === type || 'worker' === type) {
                                const targetId = String(t?.targetId || '');
                                if (!targetId) continue;
                                const sessionId = await this.cdp.attachToTarget(targetId);
                                await this.cdp.enableRuntimeAndLog(sessionId);
                            }
                        }
                    } catch  {}
                } catch  {}
            }
            async enableRuntimeForSession(sessionId) {
                if (!this.cdp) return;
                try {
                    await this.cdp.enableRuntimeAndLog(sessionId);
                } catch  {}
            }
            async enableLogging() {
                if (!this.cdp) return;
                try {
                    const extId = this.extensionId;
                    this.onProtocolEvent(async (message)=>{
                        try {
                            if (!message || !message.method) return;
                            if ('Target.attachedToTarget' === message.method) {
                                const params = message.params || {};
                                const targetInfo = params.targetInfo || {
                                    url: '',
                                    type: ''
                                };
                                const sessionId = params.sessionId;
                                const url = String(targetInfo.url || '');
                                const type = String(targetInfo.type || '');
                                const matchesExtension = !!(this.extensionId && url.includes(`chrome-extension://${this.extensionId}/`) || extId && url.includes(`chrome-extension://${extId}/`) || 'service_worker' === type);
                                if (sessionId && matchesExtension) {
                                    await this.cdp.sendCommand('Runtime.enable', {}, sessionId);
                                    await this.cdp.sendCommand('Log.enable', {}, sessionId);
                                }
                            } else if ('Runtime.consoleAPICalled' === message.method || 'Log.entryAdded' === message.method) {
                                const ts = new Date().toISOString();
                                console.log(messages.bvI(ts, message.params));
                            }
                        } catch  {}
                    });
                } catch (e) {
                    if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn('[CDP] enableLogging failed:', String(e));
                }
            }
            async getInfoBestEffort() {
                try {
                    if (!this.cdp) return null;
                    if (!this.extensionId) this.extensionId = await this.deriveExtensionIdFromTargets(6, 150);
                    if (this.extensionId) {
                        const belongsToOutPath = this.extensionIdBelongsToOutPath(this.extensionId);
                        if (false === belongsToOutPath) this.extensionId = await this.deriveExtensionIdFromTargets(10, 150);
                    }
                    if (!this.extensionId) return null;
                    let name;
                    let version;
                    try {
                        const info = await this.cdp.getExtensionInfo(this.extensionId);
                        name = info?.extensionInfo?.name;
                        version = info?.extensionInfo?.version;
                    } catch  {
                        try {
                            const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(this.outPath, 'manifest.json'), 'utf-8'));
                            name = manifest?.name;
                            version = manifest?.version;
                        } catch  {}
                    }
                    return {
                        extensionId: this.extensionId,
                        name,
                        version
                    };
                } catch (error) {
                    return null;
                }
            }
            constructor(args){
                _define_property(this, "outPath", void 0);
                _define_property(this, "browser", void 0);
                _define_property(this, "cdpPort", void 0);
                _define_property(this, "profilePath", void 0);
                _define_property(this, "extensionPaths", void 0);
                _define_property(this, "cdp", null);
                _define_property(this, "extensionId", null);
                this.outPath = args.outPath;
                this.browser = args.browser;
                this.cdpPort = args.cdpPort;
                this.profilePath = args.profilePath;
                this.extensionPaths = args.extensionPaths;
            }
        }
        var extension_output_path = __webpack_require__("./webpack/plugin-browsers/run-chromium/chromium-launch/extension-output-path.ts");
        async function setupCdpAfterLaunch(compilation, plugin, chromiumArgs) {
            const loadExtensionFlag = chromiumArgs.find((flag)=>flag.startsWith('--load-extension='));
            const extensionOutputPath = (0, extension_output_path.W)(compilation, loadExtensionFlag);
            const extensionPaths = loadExtensionFlag ? loadExtensionFlag.replace('--load-extension=', '').split(',').map((s)=>s.trim()).filter(Boolean) : [];
            const selectedExtensionPaths = extensionOutputPath && extensionOutputPath.length > 0 ? [
                extensionOutputPath
            ] : extensionPaths;
            const remoteDebugPortFlag = chromiumArgs.find((flag)=>flag.startsWith('--remote-debugging-port='));
            const chromeRemoteDebugPort = remoteDebugPortFlag ? parseInt(remoteDebugPortFlag.split('=')[1], 10) : (0, shared_utils.jl)(plugin.port, plugin.instanceId);
            const userDataDirFlag = chromiumArgs.find((flag)=>flag.startsWith('--user-data-dir='));
            const userDataDir = userDataDirFlag ? userDataDirFlag.replace('--user-data-dir=', '').replace(/^"|"$/g, '') : '';
            if ('true' === process.env.EXTENSION_AUTHOR_MODE) {
                if (userDataDir) console.log(messages.aIt(userDataDir));
                console.log(messages.CYH(chromeRemoteDebugPort, chromeRemoteDebugPort));
            }
            const cdpExtensionController = new CDPExtensionController({
                outPath: extensionOutputPath,
                browser: 'chromium-based' === plugin.browser ? 'chrome' : plugin.browser,
                cdpPort: chromeRemoteDebugPort,
                profilePath: userDataDir || void 0,
                extensionPaths: selectedExtensionPaths
            });
            await cdpExtensionController.connect();
            if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(messages.M3V('127.0.0.1', chromeRemoteDebugPort));
            const mode = compilation?.options?.mode || 'development';
            let earlyBannerPrinted = false;
            if ('development' === mode) try {
                earlyBannerPrinted = await (0, banner.a)({
                    outPath: extensionOutputPath,
                    browser: plugin.browser,
                    hostPort: {
                        host: '127.0.0.1',
                        port: chromeRemoteDebugPort
                    },
                    getInfo: async ()=>null,
                    browserVersionLine: plugin.browserVersionLine
                });
            } catch  {}
            if ('development' === mode) try {
                earlyBannerPrinted = await (0, banner.a)({
                    outPath: extensionOutputPath,
                    browser: plugin.browser,
                    hostPort: {
                        host: '127.0.0.1',
                        port: chromeRemoteDebugPort
                    },
                    getInfo: async ()=>cdpExtensionController.getInfoBestEffort(),
                    browserVersionLine: plugin.browserVersionLine
                });
            } catch  {}
            let extensionControllerInfo = null;
            try {
                const ensureLoadedTimeoutMs = 10000;
                extensionControllerInfo = await Promise.race([
                    cdpExtensionController.ensureLoaded(),
                    new Promise((_, reject)=>{
                        setTimeout(()=>reject(new Error(`ensureLoaded timeout (${ensureLoadedTimeoutMs}ms)`)), ensureLoadedTimeoutMs);
                    })
                ]);
            } catch (error) {
                if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(`[CDP] ensureLoaded failed: ${String(error?.message || error)}`);
            }
            try {
                if ('development' === mode) {
                    if (!earlyBannerPrinted) {
                        const bannerPrinted = await (0, banner.a)({
                            outPath: extensionOutputPath,
                            browser: plugin.browser,
                            hostPort: {
                                host: '127.0.0.1',
                                port: chromeRemoteDebugPort
                            },
                            getInfo: async ()=>extensionControllerInfo,
                            browserVersionLine: plugin.browserVersionLine
                        });
                        if (!bannerPrinted) await (0, banner.a)({
                            outPath: extensionOutputPath,
                            browser: plugin.browser,
                            hostPort: {
                                host: '127.0.0.1',
                                port: chromeRemoteDebugPort
                            },
                            getInfo: async ()=>cdpExtensionController.getInfoBestEffort(),
                            browserVersionLine: plugin.browserVersionLine
                        });
                    }
                } else if ('production' === mode) {
                    const runtime = extensionControllerInfo ? {
                        extensionId: extensionControllerInfo.extensionId,
                        name: extensionControllerInfo.name,
                        version: extensionControllerInfo.version
                    } : void 0;
                    await (0, banner.M)({
                        browser: plugin.browser,
                        outPath: extensionOutputPath,
                        browserVersionLine: plugin.browserVersionLine,
                        runtime
                    });
                }
            } catch (bannerErr) {
                if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.$wD(String(bannerErr)));
                try {
                    const mode = compilation?.options?.mode || 'development';
                    if ('production' === mode) await (0, banner.M)({
                        browser: plugin.browser,
                        outPath: extensionOutputPath,
                        browserVersionLine: plugin.browserVersionLine
                    });
                } catch  {}
            }
            plugin.cdpController = cdpExtensionController;
        }
    }
};
