export function createEventCollector() {
    const events = [];
    const waiters = [];
    const onEvent = (event) => {
        events.push(event);
        for (const waiter of [...waiters]) {
            if (!waiter.predicate(event)) {
                continue;
            }
            settleWaiter(waiters, waiter);
            waiter.resolve(event);
        }
    };
    return {
        onEvent,
        events,
        waitFor(predicate, options) {
            const existing = events.find(predicate);
            if (existing !== undefined) {
                return Promise.resolve(existing);
            }
            return new Promise((resolve, reject) => {
                const waiter = {
                    predicate,
                    resolve,
                    reject,
                    timeout: setTimeout(() => {
                        settleWaiter(waiters, waiter);
                        reject(new Error(`Timed out waiting for maestro event after ${options.timeoutMs}ms.`));
                    }, options.timeoutMs)
                };
                waiters.push(waiter);
            });
        },
        snapshot() {
            return Object.freeze([...events]);
        }
    };
}
function settleWaiter(waiters, waiter) {
    clearTimeout(waiter.timeout);
    const index = waiters.indexOf(waiter);
    if (index >= 0) {
        waiters.splice(index, 1);
    }
}
