|
1 | 1 | // @ts-nocheck |
2 | 2 | import * as Comlink from 'comlink'; |
3 | 3 |
|
4 | | -Comlink.transferHandlers.set("FUNCTION", { |
5 | | - canHandle: obj => { |
6 | | - return obj && typeof obj === "object" && Object.values(obj).some(x => typeof x === 'function'); |
7 | | - }, |
8 | | - serialize(obj) { |
9 | | - obj._functionKeys = []; |
10 | | - const ports = []; |
11 | | - Object.entries(obj).forEach(([k,v]) => { |
12 | | - if(typeof v === 'function'){ |
13 | | - const { port1, port2 } = new MessageChannel(); |
14 | | - obj._functionKeys.push(k); |
15 | | - Comlink.expose(obj[k], port1); |
16 | | - obj[k] = port2; |
17 | | - ports.push(port2); |
18 | | - } |
19 | | - }) |
20 | | - return [obj,ports]; |
21 | | - }, |
22 | | - deserialize(obj) { |
23 | | - obj._functionKeys.forEach((x) => { |
24 | | - // under certain conditions deserialize can be called more than once on same object |
25 | | - if (obj[x] instanceof MessagePort) { |
26 | | - obj[x].start(); |
27 | | - obj[x] = Comlink.wrap(obj[x]); |
28 | | - } |
29 | | - }) |
30 | | - return obj; |
| 4 | +const TRANSFER_HANDLER_NAME = 'FUNCTION'; |
| 5 | + |
| 6 | +let isInitialized = false; |
| 7 | + |
| 8 | +export const initTransferNestedFunctions = () => { |
| 9 | + if (isInitialized || Comlink.transferHandlers.has(TRANSFER_HANDLER_NAME)) { |
| 10 | + isInitialized = true; |
| 11 | + return; |
31 | 12 | } |
32 | | -}); |
| 13 | + |
| 14 | + Comlink.transferHandlers.set(TRANSFER_HANDLER_NAME, { |
| 15 | + canHandle: obj => { |
| 16 | + return obj && typeof obj === 'object' && Object.values(obj).some(x => typeof x === 'function'); |
| 17 | + }, |
| 18 | + serialize(obj) { |
| 19 | + obj._functionKeys = []; |
| 20 | + const ports = []; |
| 21 | + Object.entries(obj).forEach(([k, v]) => { |
| 22 | + if (typeof v === 'function') { |
| 23 | + const { port1, port2 } = new MessageChannel(); |
| 24 | + obj._functionKeys.push(k); |
| 25 | + Comlink.expose(obj[k], port1); |
| 26 | + obj[k] = port2; |
| 27 | + ports.push(port2); |
| 28 | + } |
| 29 | + }); |
| 30 | + return [obj, ports]; |
| 31 | + }, |
| 32 | + deserialize(obj) { |
| 33 | + obj._functionKeys.forEach((x) => { |
| 34 | + // under certain conditions deserialize can be called more than once on same object |
| 35 | + if (obj[x] instanceof MessagePort) { |
| 36 | + obj[x].start(); |
| 37 | + obj[x] = Comlink.wrap(obj[x]); |
| 38 | + } |
| 39 | + }); |
| 40 | + return obj; |
| 41 | + } |
| 42 | + }); |
| 43 | + |
| 44 | + isInitialized = true; |
| 45 | +}; |
| 46 | + |
0 commit comments