| 2 | import { Cause, Effect } from "effect" |
| 3 | |
| 4 | export function waitGlobalBusEvent(input: { |
| 5 | timeout?: number |
| 6 | message?: string |
| 7 | predicate: (event: GlobalEvent) => boolean |
| 8 | }) { |
| 9 | return Effect.callback<GlobalEvent, unknown>((resume) => { |
| 10 | const cleanup = () => GlobalBus.off("event", handler) |
| 11 | |
| 12 | const handler = (event: GlobalEvent) => { |
| 13 | try { |
| 14 | if (!input.predicate(event)) return |
| 15 | cleanup() |
| 16 | resume(Effect.succeed(event)) |
| 17 | } catch (error) { |
| 18 | cleanup() |
| 19 | resume(Effect.fail(error)) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | GlobalBus.on("event", handler) |
| 24 | return Effect.sync(cleanup) |
| 25 | }).pipe( |
| 26 | Effect.timeout(input.timeout ?? 10_000), |
| 27 | Effect.mapError((error) => |
| 28 | Cause.isTimeoutError(error) ? new Error(input.message ?? "timed out waiting for global bus event") : error, |
| 29 | ), |
| 30 | ) |
| 31 | } |