"use strict";
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadExtension = loadExtension;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const globalThis = global;
let loadExtensionPromise = Promise.resolve();
async function loadExtension(name, startPage = undefined, allowFileAccess = undefined, devToolsPage, inspectedPage) {
    startPage = startPage || `${inspectedPage.getResourcesPath()}/extensions/empty_extension.html`;
    const extensionInfo = { startPage, name, allowFileAccess };
    // Because the injected script is shared across calls for the target, we cannot run multiple instances concurrently.
    const load = loadExtensionPromise.then(() => doLoad(devToolsPage, extensionInfo));
    loadExtensionPromise = load.catch(() => { });
    return await load;
    async function doLoad(devToolsPage, extensionInfo) {
        const session = devToolsPage.page._client();
        // TODO(chromium:1246836) remove once real extension tests are available
        const injectedAPI = await devToolsPage.evaluate(extensionInfo => globalThis.buildExtensionAPIInjectedScript(extensionInfo, undefined, 'default', []), extensionInfo);
        function declareChrome() {
            window.chrome = window.chrome || {};
        }
        const extensionScriptId = crypto.randomUUID();
        const injectedScriptId = await session.send('Page.addScriptToEvaluateOnNewDocument', { source: `(${declareChrome})();${injectedAPI}('${extensionScriptId}')` });
        try {
            await devToolsPage.evaluate(extensionInfo => {
                globalThis.Extensions.extensionServer.addExtension(extensionInfo);
                const extensionIFrames = document.body.querySelectorAll(`[data-devtools-extension="${extensionInfo.name}"]`);
                if (extensionIFrames.length > 1) {
                    throw new Error(`Duplicate extension ${extensionInfo.name}`);
                }
                if (extensionIFrames.length === 0) {
                    throw new Error('Installing the extension failed.');
                }
                return new Promise(resolve => {
                    extensionIFrames[0].onload = () => resolve();
                });
            }, extensionInfo);
            const iframe = await devToolsPage.waitFor(`[data-devtools-extension="${name}"]`);
            const frame = await iframe.contentFrame();
            if (!frame) {
                throw new Error('Installing the extension failed.');
            }
            return frame;
        }
        finally {
            await session.send('Page.removeScriptToEvaluateOnNewDocument', injectedScriptId);
        }
    }
}
//# sourceMappingURL=extension-helpers.js.map