@expertbridge-ui/switchboard
Version:
Switchboard is a library to make it easier to communicate across browser windows using the MessageChannel API
56 lines • 2.31 kB
TypeScript
export declare type Params = {
port: MessagePort;
name?: string;
debug?: boolean;
};
/**
* A utility for communications between an iframe and its parent, used by the Expertbridge embedded SDK.
* This builds useful patterns on top of the basic functionality offered by MessageChannel.
*
* Both windows instantiate a Switchboard, passing in their MessagePorts.
* Calling methods on the switchboard causes messages to be sent through the channel.
*/
export declare class Switchboard {
port: MessagePort;
name: string;
methods: Record<string, Method<any, unknown>>;
incrementor: number;
debugMode: boolean;
constructor({ port, name, debug }: Params);
private getMethodResult;
/**
* Defines a method that can be "called" from the other side by sending an event.
*/
defineMethod<A = any, R = any>(methodName: string, executor: Method<A, R>): void;
/**
* Calls a method registered on the other side, and returns the result.
*
* How this is accomplished:
* This switchboard sends a "get" message over the channel describing which method to call with which arguments.
* The other side's switchboard finds a method with that name, and calls it with the arguments.
* It then packages up the returned value into a "reply" message, sending it back to us across the channel.
* This switchboard has attached a listener on the channel, which will resolve with the result when a reply is detected.
*
* Instead of an arguments list, arguments are supplied as a map.
*
* @param method the name of the method to call
* @param args arguments that will be supplied. Must be serializable, no functions or other nonense.
* @returns whatever is returned from the method
*/
get<T = unknown>(method: string, args?: unknown): Promise<T>;
/**
* Emit calls a method on the other side just like get does.
* But emit doesn't wait for a response, it just sends and forgets.
*
* @param method
* @param args
*/
emit(method: string, args?: unknown): void;
start(): void;
private log;
private logError;
private getNewMessageId;
}
declare type Method<A extends {}, R> = (args: A) => R | Promise<R>;
export {};
//# sourceMappingURL=switchboard.d.ts.map