passerelle
Version:
TypeScript BroadcastChannel wrapper for structured Events and Async/Await.
33 lines (30 loc) • 1.4 kB
TypeScript
interface ChannelEvent<Action extends string, Payload> {
type: 'event';
action: Action;
payload: Payload;
}
interface ChannelRequest<Action extends string, Payload> {
type: 'request';
requestId: string;
action: Action;
payload: Payload;
}
interface ChannelResponse<Result> {
type: 'response';
requestId: string;
result?: Result;
}
type ChannelMessage = ChannelEvent<string, unknown> | ChannelRequest<string, unknown> | ChannelResponse<unknown>;
interface ChannelSchema {
events: Record<string, unknown>;
awaits: Record<string, (...args: any[]) => unknown>;
}
interface ChannelInterface<T extends ChannelSchema> {
onEvent: <K extends keyof T['events'] & string>(action: K, handler: (payload: T['events'][K]) => void) => void;
onAwait: <K extends keyof T['awaits'] & string>(action: K, handler: T['awaits'][K]) => void;
sendEvent: <K extends keyof T['events'] & string>(action: K, payload: T['events'][K]) => void;
sendAwait: <K extends keyof T['awaits'] & string>(action: K, payload: Parameters<T['awaits'][K]>[0]) => Promise<ReturnType<T['awaits'][K]>>;
destroy: () => void;
}
declare const createChannel: <T extends ChannelSchema>(channelName: string) => ChannelInterface<T>;
export { type ChannelEvent, type ChannelInterface, type ChannelMessage, type ChannelRequest, type ChannelResponse, type ChannelSchema, createChannel };