"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CallbacksRegistry = void 0;
class CallbacksRegistry {
    constructor() {
        this.nextId = 0;
        this.callbacks = {};
        this.callbackIds = new WeakMap();
        this.locationInfo = new WeakMap();
    }
    add(callback) {
        // The callback is already added.
        let id = this.callbackIds.get(callback);
        if (id != null)
            return id;
        id = this.nextId += 1;
        // Capture the location of the function and put it in the ID string,
        // so that release errors can be tracked down easily.
        const regexp = /at (.*)/gi;
        const stackString = (new Error()).stack;
        if (!stackString)
            return;
        let filenameAndLine;
        let match;
        while ((match = regexp.exec(stackString)) !== null) {
            const location = match[1];
            if (location.includes('(native)'))
                continue;
            if (location.includes('(<anonymous>)'))
                continue;
            if (location.includes('callbacks-registry.js'))
                continue;
            if (location.includes('remote.js'))
                continue;
            if (location.includes('@electron/remote/dist'))
                continue;
            const ref = /([^/^)]*)\)?$/gi.exec(location);
            if (ref)
                filenameAndLine = ref[1];
            break;
        }
        this.callbacks[id] = callback;
        this.callbackIds.set(callback, id);
        this.locationInfo.set(callback, filenameAndLine);
        return id;
    }
    get(id) {
        return this.callbacks[id] || function () { };
    }
    getLocation(callback) {
        return this.locationInfo.get(callback);
    }
    apply(id, ...args) {
        return this.get(id).apply(global, ...args);
    }
    remove(id) {
        const callback = this.callbacks[id];
        if (callback) {
            this.callbackIds.delete(callback);
            delete this.callbacks[id];
        }
    }
}
exports.CallbacksRegistry = CallbacksRegistry;
