import { InspectorContext } from "./context.mjs";
import * as impl from "./methods.mjs";
const ignoreNamespaces = ['Network'];
const ignoreMethods = [];
export { createConsole, createInternals } from "./utils.mjs";
export class Inspector {
    preference = { preview: false, previewDebug: false };
    #contexts = [];
    attachRealm(realm) {
        this.#contexts.push(new InspectorContext(realm));
        realm.HostDefined.attachingInspector = this;
    }
    onMessage(id, methodArg, params) {
        if (ignoreMethods.includes(methodArg)) {
            return;
        }
        const [namespace, method] = methodArg.split('.');
        if (ignoreNamespaces.includes(namespace)) {
            return;
        }
        if (!(namespace in impl)) {
            // eslint-disable-next-line no-console
            console.error(`Unknown namespace requested: ${namespace}`);
            return;
        }
        const ns = impl[namespace];
        if (!(method in ns)) {
            // eslint-disable-next-line no-console
            console.error(`Unknown method requested: ${namespace}.${method}`);
            return;
        }
        const f = ns[method];
        new Promise((resolve) => {
            resolve(f(params, this.#context));
        }).then((result = {}) => {
            this.send({ id, result });
        });
    }
    sendEvent = Object.create(new Proxy({}, {
        get: (_, key) => {
            const f = (params) => {
                this.send({ method: key, params });
            };
            Object.defineProperty(this.sendEvent, key, { value: f });
            return f;
        },
    }));
    console(realm, type, args) {
        const context = this.#contexts.findIndex((c) => c.realm === realm);
        this.sendEvent['Runtime.consoleAPICalled']({
            type,
            // @ts-expect-error
            args: args.map((x) => this.#contexts[context].toRemoteObject(x, { generatePreview: true })),
            executionContextId: context,
            timestamp: Date.now(),
        });
    }
    #context = {
        sendEvent: this.sendEvent,
        preference: this.preference,
        getContext: (id = 0) => this.#contexts.at(id),
    };
}
//# sourceMappingURL=index.mjs.map