import { captureSelf, Expression, teardown, watch, type Falsy } from "../core/index.js"; export type WatchGuardCondition = (value: T) => value is R; export type WatchCondition = (value: T) => boolean; export class WatchForTimeoutError extends Error {} /** * Utility to watch an expression until its output satisfies a condition. * * @param expr The expression to watch. * @param condition The condition to test. By default, all truthy values are matched. * @param timeout An optional timeout. Default is no timeout. * @returns A promise that resolves with the first matched output or rejects with a {@link WatchForTimeoutError}. */ export function watchFor(expr: Expression, timeout?: number): Promise; export function watchFor(expr: Expression, condition?: WatchGuardCondition, R>, timeout?: number): Promise; export function watchFor(expr: Expression, condition?: WatchCondition>, timeout?: number): Promise; export function watchFor(expr: Expression, condition?: WatchCondition> | number, timeout?: number): Promise { if (typeof condition === "number") { timeout = condition; condition = Boolean as unknown as WatchCondition; } else if (condition === undefined) { condition = Boolean as unknown as WatchCondition; } return new Promise((resolve, reject) => { captureSelf(dispose => { watch(expr, value => { if ((condition as WatchCondition)(value)) { dispose(); resolve(value); } }); if (timeout !== undefined) { const handle = setTimeout(() => { dispose(); reject(new WatchForTimeoutError()); }, timeout); teardown(() => clearTimeout(handle)); } }); }); }