-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathMessagePortMessaging.ts
77 lines (67 loc) · 2 KB
/
MessagePortMessaging.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { AbstractMessaging, RegisterableListener } from '@finos/fdc3-agent-proxy';
import { AppIdentifier, GetAgentParams, WebDesktopAgentType } from '@finos/fdc3-standard';
import { v4 as uuidv4 } from 'uuid';
import {
AppRequestMessage,
WebConnectionProtocol3Handshake,
WebConnectionProtocol6Goodbye,
} from '@finos/fdc3-schema/dist/generated/api/BrowserTypes';
/**
* Details needed to set up the Messaging instance and Desktop AgentDetails record
*/
export type ConnectionDetails = {
connectionAttemptUuid: string;
handshake: WebConnectionProtocol3Handshake;
messagePort: MessagePort;
actualUrl: string;
options: GetAgentParams;
agentType: WebDesktopAgentType;
agentUrl?: string;
messageExchangeTimeout: number;
appLaunchTimeout: number;
};
export class MessagePortMessaging extends AbstractMessaging {
private readonly cd: ConnectionDetails;
private readonly listeners: Map<string, RegisterableListener> = new Map();
constructor(cd: ConnectionDetails, appIdentifier: AppIdentifier) {
super(appIdentifier);
this.cd = cd;
this.cd.messagePort.addEventListener('message', m => {
this.listeners.forEach(v => {
if (v.filter(m.data)) {
v.action(m.data);
}
});
});
}
createUUID(): string {
return uuidv4();
}
async post(message: AppRequestMessage | WebConnectionProtocol6Goodbye): Promise<void> {
this.cd.messagePort.postMessage(message);
return Promise.resolve();
}
register(l: RegisterableListener): void {
this.listeners.set(l.id!, l);
}
unregister(id: string): void {
this.listeners.delete(id);
}
createMeta(): AppRequestMessage['meta'] {
return {
requestUuid: this.createUUID(),
timestamp: new Date(),
source: super.getAppIdentifier(),
};
}
async disconnect(): Promise<void> {
const bye: WebConnectionProtocol6Goodbye = {
type: 'WCP6Goodbye',
meta: {
timestamp: new Date(),
},
};
await this.post(bye);
this.cd.messagePort.close();
}
}