Update selected item color in Pass menu
[ProtonMail-WebClient.git] / packages / cross-storage / lib / host.ts
blobb59455deb8aab7fefeadfe9cc29bf570e4530db8
1 import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url';
3 import type { CrossStorageMessage, ResponseMessage } from './interface';
4 import { getTestKeyValue, setTestKeyValue } from './support';
6 const createHost = <Message, MessageResponse>(handler: (message: Message) => Promise<MessageResponse>) => {
7     const isEmbedded = window.location !== window.parent.location;
8     const hostSecondLevelDomain = getSecondLevelDomain(window.location.hostname);
10     if (!isEmbedded) {
11         throw new Error('Window not embedded');
12     }
14     const postMessage = (message: CrossStorageMessage, origin: string) => {
15         return window.parent.postMessage(message, origin);
16     };
18     postMessage({ type: 'init', payload: { value: getTestKeyValue(window) } }, '*');
20     const reply = (origin: string, payload: ResponseMessage<MessageResponse>) => {
21         postMessage(payload, origin);
22     };
24     window.addEventListener('message', (event: MessageEvent<CrossStorageMessage>) => {
25         const { source, data, origin } = event;
26         if (
27             source !== window.parent ||
28             getSecondLevelDomain(new URL(origin).hostname) !== hostSecondLevelDomain ||
29             data?.type !== 'message'
30         ) {
31             return;
32         }
33         handler(data.payload)
34             .then((response) => {
35                 reply(origin, { id: data.id, type: 'response', status: 'success', payload: response });
36             })
37             .catch((e) => {
38                 reply(origin, {
39                     id: data.id,
40                     type: 'response',
41                     status: 'error',
42                     payload: e,
43                 });
44             });
45     });
48 export const initMainHost = () => {
49     setTestKeyValue(window);
52 export default createHost;