-
Notifications
You must be signed in to change notification settings - Fork 237
/
types.ts
48 lines (40 loc) · 1.13 KB
/
types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
export type RPCMessage<T> = IRPCMethod<T> | IRPCResponse<T>;
export interface IRPCMethod<T> {
type: 'method';
requesterId: string;
id: number;
method: string;
params: T;
}
export interface IRPCResponse<T> {
type: 'response';
requesterId: string;
id: number;
result: T;
error?: {
code: number;
message: string;
};
}
export function isRPCMessage(data: any): data is RPCMessage<any> {
return (data.type === 'method' || data.type === 'response')
&& typeof data.id === 'number'
&& typeof data.requesterId === 'string';
}
export interface IMessageEvent {
data: any;
origin: string;
}
export interface IMessagePoster {
postMessage(data: any, targetOrigin: string): void;
}
export interface IMessageReceiver {
readMessages(callback: (ev: IMessageEvent) => void): () => void;
}
export const windowReceiver: IMessageReceiver = {
readMessages(callback) {
window.addEventListener('message', callback);
// Unsubscribe handler for consumers to call to stop listening
return () => window.removeEventListener('message', callback);
},
};