"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PendingEvents = void 0;
class PendingEvents {
    pending = new Map();
    timeoutMs;
    constructor({ timeoutMs }) {
        this.timeoutMs = timeoutMs;
    }
    wait(key) {
        const completer = Promise.withResolvers();
        const existing = this.pending.get(key);
        if (existing) {
            existing.completers.push(completer);
            return completer.promise;
        }
        const timeout = setTimeout(() => this.complete(key, { error: 'Request timed out' }), this.timeoutMs);
        this.pending.set(key, { completers: [completer], timeout });
        return completer.promise;
    }
    complete(key, value) {
        const pending = this.pending.get(key);
        if (!pending) {
            return;
        }
        clearTimeout(pending.timeout);
        this.pending.delete(key);
        if ('error' in value) {
            const error = new Error(value.error);
            for (const completer of pending.completers) {
                completer.reject(error);
            }
        }
        else {
            for (const completer of pending.completers) {
                completer.resolve(value);
            }
        }
    }
    rejectByPrefix(prefix, error) {
        for (const key of this.pending.keys()) {
            if (key.startsWith(prefix)) {
                this.complete(key, { error });
            }
        }
    }
}
exports.PendingEvents = PendingEvents;
//# sourceMappingURL=event.js.map