"use strict";
/**
 * Copyright 2023 Google LLC.
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScriptProcessor = void 0;
const protocol_1 = require("../../../protocol/protocol");
const PreloadScript_1 = require("./PreloadScript");
class ScriptProcessor {
    #browsingContextStorage;
    #realmStorage;
    #preloadScriptStorage;
    #logger;
    constructor(browsingContextStorage, realmStorage, preloadScriptStorage, logger) {
        this.#browsingContextStorage = browsingContextStorage;
        this.#realmStorage = realmStorage;
        this.#preloadScriptStorage = preloadScriptStorage;
        this.#logger = logger;
    }
    async addPreloadScript(params) {
        const contexts = new Set();
        if (params.contexts) {
            // XXX: Remove once https://github.com/google/cddlconv/issues/16 is implemented
            if (params.contexts.length === 0) {
                throw new protocol_1.InvalidArgumentException('Contexts list is empty.');
            }
            for (const contextId of params.contexts) {
                const context = this.#browsingContextStorage.getContext(contextId);
                if (context.isTopLevelContext()) {
                    contexts.add(context);
                }
                else {
                    throw new protocol_1.InvalidArgumentException(`Non top-level context '${contextId}' given.`);
                }
            }
        }
        const preloadScript = new PreloadScript_1.PreloadScript(params, this.#logger);
        this.#preloadScriptStorage.add(preloadScript);
        const cdpTargets = contexts.size === 0
            ? new Set(this.#browsingContextStorage
                .getTopLevelContexts()
                .map((context) => context.cdpTarget))
            : new Set([...contexts.values()].map((context) => context.cdpTarget));
        await preloadScript.initInTargets(cdpTargets, false);
        return {
            script: preloadScript.id,
        };
    }
    async removePreloadScript(params) {
        const bidiId = params.script;
        const scripts = this.#preloadScriptStorage.find({
            id: bidiId,
        });
        if (scripts.length === 0) {
            throw new protocol_1.NoSuchScriptException(`No preload script with BiDi ID '${bidiId}'`);
        }
        await Promise.all(scripts.map((script) => script.remove()));
        this.#preloadScriptStorage.remove({
            id: bidiId,
        });
        return {};
    }
    async callFunction(params) {
        const realm = await this.#getRealm(params.target);
        return await realm.callFunction(params.functionDeclaration, params.this ?? {
            type: 'undefined',
        }, // `this` is `undefined` by default.
        params.arguments ?? [], // `arguments` is `[]` by default.
        params.awaitPromise, params.resultOwnership ?? "none" /* Script.ResultOwnership.None */, params.serializationOptions ?? {}, params.userActivation ?? false);
    }
    async evaluate(params) {
        const realm = await this.#getRealm(params.target);
        return await realm.evaluate(params.expression, params.awaitPromise, params.resultOwnership ?? "none" /* Script.ResultOwnership.None */, params.serializationOptions ?? {}, params.userActivation ?? false);
    }
    async disown(params) {
        const realm = await this.#getRealm(params.target);
        await Promise.all(params.handles.map(async (handle) => await realm.disown(handle)));
        return {};
    }
    getRealms(params) {
        if (params.context !== undefined) {
            // Make sure the context is known.
            this.#browsingContextStorage.getContext(params.context);
        }
        const realms = this.#realmStorage
            .findRealms({
            browsingContextId: params.context,
            type: params.type,
        })
            .map((realm) => realm.realmInfo);
        return { realms };
    }
    async #getRealm(target) {
        if ('realm' in target) {
            return this.#realmStorage.getRealm({
                realmId: target.realm,
            });
        }
        const context = this.#browsingContextStorage.getContext(target.context);
        return await context.getOrCreateSandbox(target.sandbox);
    }
}
exports.ScriptProcessor = ScriptProcessor;
//# sourceMappingURL=ScriptProcessor.js.map