@dxos/rpc-tunnel 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,205 @@
1
+ import UAParser from "ua-parser-js";
2
+ import { log } from "@dxos/log";
3
+ //#region src/ports/iframe.ts
4
+ var __dxlog_file$2 = "/__w/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/iframe.ts";
5
+ var browser;
6
+ var os;
7
+ if (typeof navigator !== "undefined") {
8
+ const parser = new UAParser(navigator.userAgent);
9
+ browser = parser.getBrowser().name;
10
+ os = parser.getOS().name;
11
+ }
12
+ var sendToIFrame = (iframe, origin, message) => {
13
+ if (!iframe.contentWindow) {
14
+ log("IFrame content window missing", { origin }, {
15
+ "~LogMeta": "~LogMeta",
16
+ F: __dxlog_file$2,
17
+ L: 24,
18
+ S: void 0
19
+ });
20
+ return;
21
+ }
22
+ if (browser === "Chrome" && os === "iOS") iframe.contentWindow.postMessage(message, origin);
23
+ else iframe.contentWindow.postMessage(message, origin, [message.payload]);
24
+ };
25
+ var sendToParentWindow = (origin, message) => {
26
+ if (browser === "Chrome" && os === "iOS") window.parent.postMessage(message, origin);
27
+ else window.parent.postMessage(message, origin, [message.payload]);
28
+ };
29
+ /**
30
+ * Create a RPC port with an iframe over window messaging.
31
+ * @param options.channel Identifier for sent/recieved messages.
32
+ * @param options.iframe Instance of the iframe if sending to child.
33
+ * @param options.origin Origin of the destination window.
34
+ * @param options.onOrigin Callback triggered when origin of destination window is verified.
35
+ * @returns RPC port for messaging.
36
+ */
37
+ var createIFramePort = ({ channel, iframe, origin, onOrigin }) => {
38
+ return {
39
+ send: async (data) => {
40
+ if (!origin) {
41
+ log("no origin set", { channel }, {
42
+ "~LogMeta": "~LogMeta",
43
+ F: __dxlog_file$2,
44
+ L: 62,
45
+ S: void 0
46
+ });
47
+ return;
48
+ }
49
+ log("sending", {
50
+ channel,
51
+ data: data.length
52
+ }, {
53
+ "~LogMeta": "~LogMeta",
54
+ F: __dxlog_file$2,
55
+ L: 66,
56
+ S: void 0
57
+ });
58
+ const message = {
59
+ channel,
60
+ payload: data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
61
+ };
62
+ if (iframe) sendToIFrame(iframe, origin, message);
63
+ else sendToParentWindow(origin, message);
64
+ },
65
+ subscribe: (callback) => {
66
+ const handler = (event) => {
67
+ if (!iframe && event.source !== window.parent) return;
68
+ else if (iframe && event.source !== iframe.contentWindow) return;
69
+ const message = event.data && typeof event.data === "object" && "channel" in event.data && "payload" in event.data ? event.data : void 0;
70
+ if (message?.channel !== channel) return;
71
+ if (!origin) {
72
+ origin = event.origin;
73
+ onOrigin?.(origin);
74
+ }
75
+ log("received", message, {
76
+ "~LogMeta": "~LogMeta",
77
+ F: __dxlog_file$2,
78
+ L: 98,
79
+ S: void 0
80
+ });
81
+ callback(new Uint8Array(message.payload));
82
+ };
83
+ window.addEventListener("message", handler);
84
+ return () => window.removeEventListener("message", handler);
85
+ }
86
+ };
87
+ };
88
+ /**
89
+ * Create a hidden iframe and insert it into the DOM.
90
+ * If an element with the same id already exists it will be returned instead.
91
+ * @param source Source of the iframe.
92
+ * @param id DOM id of the iframe.
93
+ * @returns The created iframe.
94
+ */
95
+ var createIFrame = (source, id, { hidden = true, allow } = {}) => {
96
+ const create = () => {
97
+ const iframe = document.createElement("iframe");
98
+ iframe.id = id;
99
+ iframe.src = source;
100
+ hidden && iframe.setAttribute("style", "display: none;");
101
+ allow && iframe.setAttribute("allow", allow);
102
+ document.body.appendChild(iframe);
103
+ return iframe;
104
+ };
105
+ return document.getElementById(id) ?? create();
106
+ };
107
+ //#endregion
108
+ //#region src/ports/worker.ts
109
+ var __dxlog_file$1 = "/__w/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/worker.ts";
110
+ /**
111
+ * Create a RPC port for a worker.
112
+ * @param options.port Message port to send message on.
113
+ * @param options.channel Identifier for sent/recieved messages.
114
+ * @param options.subscribe
115
+ * @returns RPC port for messaging.
116
+ */
117
+ var createWorkerPort = ({ port, channel, subscribe }) => ({
118
+ send: async (message) => {
119
+ const payload = message.buffer.slice(message.byteOffset, message.byteOffset + message.byteLength);
120
+ port.postMessage({
121
+ channel,
122
+ payload
123
+ }, [payload]);
124
+ },
125
+ subscribe: subscribe ?? ((callback) => {
126
+ const handler = (event) => {
127
+ const message = event.data;
128
+ if (channel && message.channel !== channel) return;
129
+ log.trace("received", { message }, {
130
+ "~LogMeta": "~LogMeta",
131
+ F: __dxlog_file$1,
132
+ L: 46,
133
+ S: void 0
134
+ });
135
+ callback(new Uint8Array(message.payload));
136
+ };
137
+ port.onmessage = handler;
138
+ return () => {
139
+ port.onmessage = null;
140
+ };
141
+ })
142
+ });
143
+ //#endregion
144
+ //#region src/port-muxer.ts
145
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/mesh/rpc-tunnel/src/port-muxer.ts";
146
+ /**
147
+ * Facilitates the multiplexing of multiple RpcPorts over a single MessagePort.
148
+ */
149
+ var PortMuxer = class {
150
+ _messagePort;
151
+ _activeChannels = /* @__PURE__ */ new Map();
152
+ _rpcPorts = /* @__PURE__ */ new Map();
153
+ constructor(_messagePort) {
154
+ this._messagePort = _messagePort;
155
+ if (this._messagePort) this._messagePort.onmessage = (event) => this.onWorkerMessage(event);
156
+ if (typeof window !== "undefined") window.addEventListener("message", (event) => this.onWindowMessage(event));
157
+ }
158
+ createWorkerPort(options) {
159
+ if (!this._messagePort) throw new Error("Message port is required to create worker ports");
160
+ const port = createWorkerPort({
161
+ ...options,
162
+ port: this._messagePort,
163
+ subscribe: (callback) => {
164
+ this._activeChannels.set(options.channel, callback);
165
+ return () => this._activeChannels.delete(options.channel);
166
+ }
167
+ });
168
+ this._rpcPorts.set(options.channel, port);
169
+ return port;
170
+ }
171
+ createIFramePort(options) {
172
+ const port = createIFramePort(options);
173
+ this._rpcPorts.set(options.channel, port);
174
+ return port;
175
+ }
176
+ onWorkerMessage(event) {
177
+ const message = event.data;
178
+ log.debug("Recieved message from worker port", {
179
+ channel: message.channel,
180
+ payload: message.payload
181
+ }, {
182
+ "~LogMeta": "~LogMeta",
183
+ F: __dxlog_file,
184
+ L: 56,
185
+ S: this
186
+ });
187
+ this._activeChannels.get(message.channel)?.(new Uint8Array(message.payload));
188
+ }
189
+ onWindowMessage(event) {
190
+ const message = event.data;
191
+ log.debug("Recieved message from window", {
192
+ channel: message.channel,
193
+ payload: message.payload
194
+ }, {
195
+ "~LogMeta": "~LogMeta",
196
+ F: __dxlog_file,
197
+ L: 67,
198
+ S: this
199
+ });
200
+ }
201
+ };
202
+ //#endregion
203
+ export { PortMuxer, createIFrame, createIFramePort, createWorkerPort };
204
+
205
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/ports/iframe.ts","../../src/ports/worker.ts","../../src/port-muxer.ts"],"sourcesContent":["//\n// Copyright 2022 DXOS.org\n//\n\nimport UAParser from 'ua-parser-js';\n\nimport { log } from '@dxos/log';\nimport { type RpcPort } from '@dxos/rpc';\n\nimport { type MessageData } from '../message';\n\nlet browser: string | undefined;\nlet os: string | undefined;\n\nif (typeof navigator !== 'undefined') {\n // TODO(wittjosiah): Stop user agent parsing.\n const parser = new UAParser(navigator.userAgent);\n browser = parser.getBrowser().name;\n os = parser.getOS().name;\n}\n\nconst sendToIFrame = (iframe: HTMLIFrameElement, origin: string, message: MessageData) => {\n if (!iframe.contentWindow) {\n log('IFrame content window missing', { origin });\n return;\n }\n\n if (browser === 'Chrome' && os === 'iOS') {\n iframe.contentWindow.postMessage(message, origin);\n } else {\n iframe.contentWindow.postMessage(message, origin, [message.payload]);\n }\n};\n\nconst sendToParentWindow = (origin: string, message: MessageData) => {\n if (browser === 'Chrome' && os === 'iOS') {\n window.parent.postMessage(message, origin);\n } else {\n window.parent.postMessage(message, origin, [message.payload]);\n }\n};\n\nexport type IFramePortOptions = {\n channel: string;\n iframe?: HTMLIFrameElement;\n origin?: string;\n onOrigin?: (origin: string) => void;\n};\n\n/**\n * Create a RPC port with an iframe over window messaging.\n * @param options.channel Identifier for sent/recieved messages.\n * @param options.iframe Instance of the iframe if sending to child.\n * @param options.origin Origin of the destination window.\n * @param options.onOrigin Callback triggered when origin of destination window is verified.\n * @returns RPC port for messaging.\n */\nexport const createIFramePort = ({ channel, iframe, origin, onOrigin }: IFramePortOptions): RpcPort => {\n return {\n send: async (data) => {\n if (!origin) {\n log('no origin set', { channel });\n return;\n }\n\n log('sending', { channel, data: data.length });\n const payload = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);\n const message = { channel, payload };\n if (iframe) {\n sendToIFrame(iframe, origin, message);\n } else {\n sendToParentWindow(origin, message);\n }\n },\n\n subscribe: (callback) => {\n const handler = (event: MessageEvent<unknown>) => {\n if (!iframe && event.source !== window.parent) {\n // Not from parent window.\n return;\n } else if (iframe && event.source !== iframe.contentWindow) {\n // Not from child window.\n return;\n }\n\n const isMessageData =\n event.data && typeof event.data === 'object' && 'channel' in event.data && 'payload' in event.data;\n const message = isMessageData ? (event.data as MessageData) : undefined;\n if (message?.channel !== channel) {\n return;\n }\n\n if (!origin) {\n origin = event.origin;\n onOrigin?.(origin);\n }\n\n log('received', message);\n callback(new Uint8Array(message.payload));\n };\n\n window.addEventListener('message', handler);\n return () => window.removeEventListener('message', handler);\n },\n };\n};\n\nexport type CreateIFrameOptions = {\n hidden?: boolean;\n allow?: string;\n};\n\n/**\n * Create a hidden iframe and insert it into the DOM.\n * If an element with the same id already exists it will be returned instead.\n * @param source Source of the iframe.\n * @param id DOM id of the iframe.\n * @returns The created iframe.\n */\nexport const createIFrame = (source: string, id: string, { hidden = true, allow }: CreateIFrameOptions = {}) => {\n const create = () => {\n const iframe = document.createElement('iframe') as HTMLIFrameElement;\n iframe.id = id;\n iframe.src = source;\n hidden && iframe.setAttribute('style', 'display: none;');\n allow && iframe.setAttribute('allow', allow);\n document.body.appendChild(iframe);\n return iframe;\n };\n\n return (document.getElementById(id) as HTMLIFrameElement) ?? create();\n};\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { log } from '@dxos/log';\nimport { type RpcPort } from '@dxos/rpc';\n\nimport { type MessageData } from '../message';\n\nexport type WorkerPortOptions = {\n port: MessagePort;\n channel?: string;\n subscribe?: RpcPort['subscribe'];\n};\n\n/**\n * Create a RPC port for a worker.\n * @param options.port Message port to send message on.\n * @param options.channel Identifier for sent/recieved messages.\n * @param options.subscribe\n * @returns RPC port for messaging.\n */\n// TODO(wittjosiah): Rename for more general purpose MessagePort.\nexport const createWorkerPort = ({ port, channel, subscribe }: WorkerPortOptions): RpcPort => ({\n send: async (message) => {\n // Based on https://stackoverflow.com/a/54646864/2804332.\n const payload = message.buffer.slice(message.byteOffset, message.byteOffset + message.byteLength);\n port.postMessage(\n {\n channel,\n payload,\n },\n [payload],\n );\n },\n\n subscribe:\n subscribe ??\n ((callback) => {\n const handler = (event: MessageEvent<MessageData>) => {\n const message = event.data;\n if (channel && message.channel !== channel) {\n return;\n }\n\n log.trace('received', { message });\n callback(new Uint8Array(message.payload));\n };\n\n port.onmessage = handler;\n return () => {\n port.onmessage = null;\n };\n }),\n});\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { log } from '@dxos/log';\nimport { type RpcPort } from '@dxos/rpc';\n\nimport { type MessageData } from './message';\nimport { type IFramePortOptions, type WorkerPortOptions, createIFramePort, createWorkerPort } from './ports';\n\n/**\n * Facilitates the multiplexing of multiple RpcPorts over a single MessagePort.\n */\nexport class PortMuxer {\n private readonly _activeChannels = new Map<string, (msg: Uint8Array) => void>();\n\n private readonly _rpcPorts = new Map<string, RpcPort>();\n\n constructor(private readonly _messagePort?: MessagePort) {\n if (this._messagePort) {\n this._messagePort.onmessage = (event) => this.onWorkerMessage(event);\n }\n\n if (typeof window !== 'undefined') {\n window.addEventListener('message', (event) => this.onWindowMessage(event));\n }\n }\n\n createWorkerPort(options: Omit<WorkerPortOptions, 'port' | 'subscribe' | 'channel'> & { channel: string }): RpcPort {\n if (!this._messagePort) {\n throw new Error('Message port is required to create worker ports');\n }\n\n const port = createWorkerPort({\n ...options,\n port: this._messagePort,\n subscribe: (callback) => {\n this._activeChannels.set(options.channel, callback);\n return () => this._activeChannels.delete(options.channel);\n },\n });\n this._rpcPorts.set(options.channel, port);\n\n return port;\n }\n\n createIFramePort(options: IFramePortOptions): RpcPort {\n const port = createIFramePort(options);\n this._rpcPorts.set(options.channel, port);\n\n return port;\n }\n\n private onWorkerMessage(event: MessageEvent<MessageData>): void {\n const message = event.data;\n log.debug('Recieved message from worker port', {\n channel: message.channel,\n payload: message.payload,\n });\n\n const callback = this._activeChannels.get(message.channel);\n callback?.(new Uint8Array(message.payload));\n }\n\n private onWindowMessage(event: MessageEvent<MessageData>): void {\n const message = event.data;\n log.debug('Recieved message from window', {\n channel: message.channel,\n payload: message.payload,\n });\n }\n}\n"],"mappings":";;;;AAWA,IAAI;AACJ,IAAI;AAEJ,IAAI,OAAO,cAAc,aAAa;CAEpC,MAAM,SAAS,IAAI,SAAS,UAAU,SAAS;CAC/C,UAAU,OAAO,WAAW,CAAC,CAAC;CAC9B,KAAK,OAAO,MAAM,CAAC,CAAC;AACtB;AAEA,IAAM,gBAAgB,QAA2B,QAAgB,YAAyB;CACxF,IAAI,CAAC,OAAO,eAAe;EACzB,IAAI,iCAAiC,EAAE,OAAO,GAAA;GAAA,YAAA;GAAA,GAAA;GAAA,GAAA;GAAA,GAAA,KAAA;EAAA,CAAC;EAC/C;CACF;CAEA,IAAI,YAAY,YAAY,OAAO,OACjC,OAAO,cAAc,YAAY,SAAS,MAAM;MAEhD,OAAO,cAAc,YAAY,SAAS,QAAQ,CAAC,QAAQ,OAAO,CAAC;AAEvE;AAEA,IAAM,sBAAsB,QAAgB,YAAyB;CACnE,IAAI,YAAY,YAAY,OAAO,OACjC,OAAO,OAAO,YAAY,SAAS,MAAM;MAEzC,OAAO,OAAO,YAAY,SAAS,QAAQ,CAAC,QAAQ,OAAO,CAAC;AAEhE;;;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