osra 0.2.7 → 0.2.8
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.
- package/build/index.js +33 -34
- package/build/index.js.map +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
const P = "__OSRA_KEY__", pe = "__OSRA_DEFAULT_KEY__", M = "__OSRA_BOX__", b = {
|
|
2
2
|
[M]: "revivable",
|
|
3
3
|
type: ""
|
|
4
|
-
}, ge = (e, t) => e && typeof e == "object" && M in e && e[M] === "revivable",
|
|
4
|
+
}, ge = (e, t) => e && typeof e == "object" && M in e && e[M] === "revivable", q = "context", K = Symbol.for("OSRA_CONTEXT"), be = { [K]: !0 }, me = (e) => e !== null && typeof e == "object" && K in e, ue = (e, t) => ({
|
|
5
5
|
...b,
|
|
6
|
-
type:
|
|
6
|
+
type: q
|
|
7
7
|
}), Ae = (e, t) => t.messageContext ?? {}, he = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
8
8
|
__proto__: null,
|
|
9
9
|
OSRA_CONTEXT: be,
|
|
10
10
|
box: ue,
|
|
11
11
|
isType: me,
|
|
12
12
|
revive: Ae,
|
|
13
|
-
type:
|
|
13
|
+
type: q
|
|
14
14
|
}, Symbol.toStringTag, { value: "Module" })), we = () => {
|
|
15
15
|
const e = /* @__PURE__ */ new Map(), t = {
|
|
16
16
|
getUniqueUuid: () => {
|
|
@@ -43,14 +43,14 @@ const P = "__OSRA_KEY__", pe = "__OSRA_DEFAULT_KEY__", M = "__OSRA_BOX__", b = {
|
|
|
43
43
|
}
|
|
44
44
|
};
|
|
45
45
|
return t;
|
|
46
|
-
},
|
|
46
|
+
}, v = (e, t) => _e(e) && e[P] === t, Ue = ({ listener: e, transport: t, remoteName: r, key: n = P, unregisterSignal: a }) => {
|
|
47
47
|
const s = (o) => {
|
|
48
48
|
if (typeof o == "function")
|
|
49
49
|
o(e);
|
|
50
50
|
else if (O(o) || R(o) || $(o)) {
|
|
51
51
|
const c = (y, l) => {
|
|
52
52
|
const f = (p, i) => {
|
|
53
|
-
|
|
53
|
+
v(p, n) && (r && p.name !== r || e(p, { port: l, sender: i }));
|
|
54
54
|
};
|
|
55
55
|
y.addListener(f), a && a.addEventListener(
|
|
56
56
|
"abort",
|
|
@@ -68,7 +68,7 @@ const P = "__OSRA_KEY__", pe = "__OSRA_DEFAULT_KEY__", M = "__OSRA_BOX__", b = {
|
|
|
68
68
|
} else $(o) ? c(o) : c(o.onMessage);
|
|
69
69
|
} else {
|
|
70
70
|
const c = (y) => {
|
|
71
|
-
|
|
71
|
+
v(y.data, n) && (r && y.data.name !== r || e(y.data, { receiveTransport: o, source: y.source }));
|
|
72
72
|
};
|
|
73
73
|
o.addEventListener("message", c), a && a.addEventListener(
|
|
74
74
|
"abort",
|
|
@@ -84,7 +84,7 @@ const P = "__OSRA_KEY__", pe = "__OSRA_DEFAULT_KEY__", M = "__OSRA_BOX__", b = {
|
|
|
84
84
|
J(e) ? a(e.emit) : a(e);
|
|
85
85
|
};
|
|
86
86
|
new Int8Array(), new Uint8Array(), new Uint8ClampedArray(), new Int16Array(), new Uint16Array(), new Int32Array(), new Uint32Array(), new Float16Array(), new Float32Array(), new Float64Array(), new BigInt64Array(), new BigUint64Array();
|
|
87
|
-
const k = (e) => e instanceof WebSocket, X = (e) => globalThis.ServiceWorkerContainer && e instanceof ServiceWorkerContainer, Y = (e) => globalThis.Worker && e instanceof Worker, G = (e) => globalThis.DedicatedWorkerGlobalScope && e instanceof DedicatedWorkerGlobalScope, D = (e) => globalThis.SharedWorker && e instanceof SharedWorker, H = (e) => e instanceof MessagePort, _e = (e) => !!(e && typeof e == "object" && e[P]), Me = (e) => !!(globalThis.SharedArrayBuffer && e instanceof globalThis.SharedArrayBuffer),
|
|
87
|
+
const k = (e) => e instanceof WebSocket, X = (e) => globalThis.ServiceWorkerContainer && e instanceof ServiceWorkerContainer, Y = (e) => globalThis.Worker && e instanceof Worker, G = (e) => globalThis.DedicatedWorkerGlobalScope && e instanceof DedicatedWorkerGlobalScope, D = (e) => globalThis.SharedWorker && e instanceof SharedWorker, H = (e) => e instanceof MessagePort, _e = (e) => !!(e && typeof e == "object" && e[P]), Me = (e) => !!(globalThis.SharedArrayBuffer && e instanceof globalThis.SharedArrayBuffer), Ce = (e) => globalThis.ArrayBuffer && e instanceof globalThis.ArrayBuffer || globalThis.MessagePort && e instanceof globalThis.MessagePort || globalThis.ReadableStream && e instanceof globalThis.ReadableStream || globalThis.WritableStream && e instanceof globalThis.WritableStream || globalThis.TransformStream && e instanceof globalThis.TransformStream ? !0 : !!(globalThis.ImageBitmap && e instanceof globalThis.ImageBitmap), O = (e, t = !1) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && "name" in e && "disconnect" in e && "postMessage" in e && (!t || "sender" in e && "onMessage" in e && "onDisconnect" in e)), R = (e) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && e.addListener && e.hasListener && e.removeListener), $ = (e) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && e.addListener && e.hasListener && e.removeListener), z = (e) => {
|
|
88
88
|
if (!e || typeof e != "object") return !1;
|
|
89
89
|
try {
|
|
90
90
|
return e.window === e;
|
|
@@ -96,8 +96,8 @@ const k = (e) => e instanceof WebSocket, X = (e) => globalThis.ServiceWorkerCont
|
|
|
96
96
|
return !1;
|
|
97
97
|
}
|
|
98
98
|
}
|
|
99
|
-
}, N = (e) => k(e) || O(e), Q = (e) => k(e) || O(e) || R(e) || $(e), S = (e) => "isJson" in e && e.isJson === !0 || N(e) || Q(e),
|
|
100
|
-
const t = [], r = (n) => Me(n) ? void 0 :
|
|
99
|
+
}, N = (e) => k(e) || O(e), Q = (e) => k(e) || O(e) || R(e) || $(e), S = (e) => "isJson" in e && e.isJson === !0 || N(e) || Q(e), C = (e) => z(e) || N(e) || X(e) || Y(e) || G(e) || D(e) || H(e) || Z(e), W = (e) => z(e) || Q(e) || X(e) || Y(e) || G(e) || D(e) || H(e) || ee(e), Z = (e) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && "emit" in e && (C(e.emit) || typeof e.emit == "function")), ee = (e) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && "receive" in e && (W(e.receive) || typeof e.receive == "function")), J = (e) => Z(e) || ee(e), U = (e) => {
|
|
100
|
+
const t = [], r = (n) => Me(n) ? void 0 : Ce(n) ? t.push(n) : Array.isArray(n) ? n.map(r) : n && typeof n == "object" ? Object.values(n).map(r) : void 0;
|
|
101
101
|
return r(e), t;
|
|
102
102
|
}, E = (e, t = !1) => {
|
|
103
103
|
const { port1: r, port2: n } = new MessageChannel(), a = new Promise(
|
|
@@ -107,7 +107,7 @@ const k = (e) => e instanceof WebSocket, X = (e) => globalThis.ServiceWorkerCont
|
|
|
107
107
|
)
|
|
108
108
|
);
|
|
109
109
|
return r.start(), n.postMessage(e, t ? U(e) : []), a;
|
|
110
|
-
},
|
|
110
|
+
}, Be = async () => {
|
|
111
111
|
const { port1: e } = new MessageChannel();
|
|
112
112
|
return await E(e, !0) instanceof MessagePort;
|
|
113
113
|
}, Pe = async () => {
|
|
@@ -130,7 +130,7 @@ const k = (e) => e instanceof WebSocket, X = (e) => globalThis.ServiceWorkerCont
|
|
|
130
130
|
r,
|
|
131
131
|
n
|
|
132
132
|
] = await Promise.all([
|
|
133
|
-
|
|
133
|
+
Be().catch(() => !1),
|
|
134
134
|
Pe().catch(() => !1),
|
|
135
135
|
Oe().catch(() => !1),
|
|
136
136
|
Se().catch(() => !1)
|
|
@@ -166,22 +166,22 @@ const k = (e) => e instanceof WebSocket, X = (e) => globalThis.ServiceWorkerCont
|
|
|
166
166
|
...b,
|
|
167
167
|
type: ne,
|
|
168
168
|
entries: [...e.entries()]
|
|
169
|
-
}), Je = (e, t) => new Headers(e.entries),
|
|
169
|
+
}), Je = (e, t) => new Headers(e.entries), xe = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
170
170
|
__proto__: null,
|
|
171
171
|
box: ze,
|
|
172
172
|
isType: De,
|
|
173
173
|
revive: Je,
|
|
174
174
|
type: ne
|
|
175
|
-
}, Symbol.toStringTag, { value: "Module" })), se = "error",
|
|
175
|
+
}, Symbol.toStringTag, { value: "Module" })), se = "error", Ve = (e) => e instanceof Error, ve = (e, t) => ({
|
|
176
176
|
...b,
|
|
177
177
|
type: se,
|
|
178
178
|
message: e.message,
|
|
179
179
|
stack: e.stack || e.toString()
|
|
180
|
-
}),
|
|
180
|
+
}), qe = (e, t) => new Error(e.message, { cause: e.stack }), Ke = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
181
181
|
__proto__: null,
|
|
182
|
-
box:
|
|
183
|
-
isType:
|
|
184
|
-
revive:
|
|
182
|
+
box: ve,
|
|
183
|
+
isType: Ve,
|
|
184
|
+
revive: qe,
|
|
185
185
|
type: se
|
|
186
186
|
}, Symbol.toStringTag, { value: "Module" })), oe = "typedArray", Xe = [
|
|
187
187
|
Int8Array,
|
|
@@ -222,7 +222,7 @@ const ae = (e) => {
|
|
|
222
222
|
type: oe,
|
|
223
223
|
typedArrayToType: ae,
|
|
224
224
|
typedArrayTypeToTypedArrayConstructor: ie
|
|
225
|
-
}, Symbol.toStringTag, { value: "Module" })),
|
|
225
|
+
}, Symbol.toStringTag, { value: "Module" })), B = new FinalizationRegistry((e) => {
|
|
226
226
|
e.sendMessage({
|
|
227
227
|
type: "message-port-close",
|
|
228
228
|
remoteUuid: e.remoteUuid,
|
|
@@ -244,7 +244,7 @@ const ae = (e) => {
|
|
|
244
244
|
if (f.portId !== s) return;
|
|
245
245
|
t.messageChannels.free(s);
|
|
246
246
|
const i = o.deref();
|
|
247
|
-
i && (
|
|
247
|
+
i && (B.unregister(i), i.close()), t.eventTarget.removeEventListener("message", c);
|
|
248
248
|
return;
|
|
249
249
|
}
|
|
250
250
|
if (f.type !== "message" || f.portId !== s) return;
|
|
@@ -255,7 +255,7 @@ const ae = (e) => {
|
|
|
255
255
|
}
|
|
256
256
|
p.postMessage(f.data, U(f.data));
|
|
257
257
|
};
|
|
258
|
-
return
|
|
258
|
+
return B.register(o.deref(), {
|
|
259
259
|
sendMessage: t.sendMessage,
|
|
260
260
|
remoteUuid: t.remoteUuid,
|
|
261
261
|
portId: s,
|
|
@@ -287,7 +287,7 @@ const ae = (e) => {
|
|
|
287
287
|
const { message: u } = i;
|
|
288
288
|
if (u.type !== "message-port-close" || u.portId !== n) return;
|
|
289
289
|
const w = y.deref();
|
|
290
|
-
w &&
|
|
290
|
+
w && B.unregister(w), p();
|
|
291
291
|
}, f = ({ data: i }) => {
|
|
292
292
|
if (i.type !== "message" || i.portId !== n) return;
|
|
293
293
|
const u = y.deref();
|
|
@@ -306,7 +306,7 @@ const ae = (e) => {
|
|
|
306
306
|
const i = t.messageChannels.get(n);
|
|
307
307
|
i && (i.port1.close(), i.port2 && i.port2.close()), t.messageChannels.free(n);
|
|
308
308
|
};
|
|
309
|
-
return
|
|
309
|
+
return B.register(a, {
|
|
310
310
|
sendMessage: t.sendMessage,
|
|
311
311
|
remoteUuid: t.remoteUuid,
|
|
312
312
|
portId: n,
|
|
@@ -436,7 +436,7 @@ const ae = (e) => {
|
|
|
436
436
|
Re,
|
|
437
437
|
he,
|
|
438
438
|
ke,
|
|
439
|
-
|
|
439
|
+
xe,
|
|
440
440
|
Ke,
|
|
441
441
|
Ne,
|
|
442
442
|
nt,
|
|
@@ -472,7 +472,8 @@ const ae = (e) => {
|
|
|
472
472
|
messageChannels: we(),
|
|
473
473
|
sendMessage: o,
|
|
474
474
|
eventTarget: s,
|
|
475
|
-
revivableModules: pt
|
|
475
|
+
revivableModules: pt,
|
|
476
|
+
messageContext: void 0
|
|
476
477
|
};
|
|
477
478
|
let l;
|
|
478
479
|
const f = new Promise((p, i) => {
|
|
@@ -492,9 +493,7 @@ const ae = (e) => {
|
|
|
492
493
|
revivableContext: y,
|
|
493
494
|
close: () => {
|
|
494
495
|
},
|
|
495
|
-
remoteValue: f.then(
|
|
496
|
-
({ message: p, messageContext: i }) => h(p.data, { ...y, messageContext: i })
|
|
497
|
-
)
|
|
496
|
+
remoteValue: f.then(({ message: p, messageContext: i }) => (y.messageContext = i, h(p.data, y)))
|
|
498
497
|
};
|
|
499
498
|
}, bt = ({ value: e, uuid: t, platformCapabilities: r, send: n, close: a }) => ({
|
|
500
499
|
close: () => {
|
|
@@ -536,12 +535,12 @@ const ut = async (e, {
|
|
|
536
535
|
const w = new Promise((d) => {
|
|
537
536
|
u = d;
|
|
538
537
|
});
|
|
539
|
-
let A = globalThis.crypto.randomUUID(),
|
|
538
|
+
let A = globalThis.crypto.randomUUID(), x = !1;
|
|
540
539
|
o && o.addEventListener("abort", () => {
|
|
541
|
-
|
|
540
|
+
x = !0;
|
|
542
541
|
});
|
|
543
542
|
const T = (d, _) => {
|
|
544
|
-
if (
|
|
543
|
+
if (x) return;
|
|
545
544
|
const g = U(_);
|
|
546
545
|
Te(
|
|
547
546
|
d,
|
|
@@ -556,7 +555,7 @@ const ut = async (e, {
|
|
|
556
555
|
);
|
|
557
556
|
}, le = async (d, _) => {
|
|
558
557
|
if (d.uuid !== A) {
|
|
559
|
-
if (!
|
|
558
|
+
if (!C(f))
|
|
560
559
|
throw new Error("Unidirectional receiving mode not implemented");
|
|
561
560
|
if (d.type === "announce") {
|
|
562
561
|
if (!d.remoteUuid) {
|
|
@@ -566,7 +565,7 @@ const ut = async (e, {
|
|
|
566
565
|
if (d.remoteUuid !== A || i.has(d.uuid))
|
|
567
566
|
return;
|
|
568
567
|
T(f, { type: "announce", remoteUuid: d.uuid });
|
|
569
|
-
const g = new mt(),
|
|
568
|
+
const g = new mt(), V = {
|
|
570
569
|
type: "bidirectional",
|
|
571
570
|
eventTarget: g,
|
|
572
571
|
connection: gt({
|
|
@@ -580,7 +579,7 @@ const ut = async (e, {
|
|
|
580
579
|
close: () => void i.delete(d.uuid)
|
|
581
580
|
})
|
|
582
581
|
};
|
|
583
|
-
i.set(d.uuid,
|
|
582
|
+
i.set(d.uuid, V), V.connection.remoteValue.then(
|
|
584
583
|
(L) => u(L)
|
|
585
584
|
);
|
|
586
585
|
} else if (d.type === "reject-uuid-taken") {
|
|
@@ -614,7 +613,7 @@ const ut = async (e, {
|
|
|
614
613
|
remoteName: n,
|
|
615
614
|
key: a,
|
|
616
615
|
unregisterSignal: o
|
|
617
|
-
}),
|
|
616
|
+
}), C(f) && T(f, { type: "announce" }), C(f) && !W(f)) {
|
|
618
617
|
const { remoteValueProxy: d } = bt({
|
|
619
618
|
value: e,
|
|
620
619
|
uuid: A,
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/types.ts","../src/revivables/utils.ts","../src/revivables/context.ts","../src/utils/allocator.ts","../src/utils/platform.ts","../src/utils/type-guards.ts","../src/utils/transferable.ts","../src/utils/capabilities.ts","../src/revivables/array-buffer.ts","../src/revivables/date.ts","../src/revivables/headers.ts","../src/revivables/error.ts","../src/revivables/typed-array.ts","../src/revivables/message-port.ts","../src/revivables/promise.ts","../src/revivables/function.ts","../src/revivables/readable-stream.ts","../src/revivables/index.ts","../src/utils/connection.ts","../node_modules/typescript-event-target/dist/index.mjs","../src/index.ts"],"sourcesContent":["import { TypedEventTarget } from 'typescript-event-target'\r\nimport type { TypedArray, WebExtOnConnect, WebExtOnMessage, WebExtPort, WebExtRuntime, WebExtSender } from './utils/type-guards'\r\nimport { DefaultRevivableModule, DefaultRevivableModules, RevivableModule } from './revivables'\r\nimport { InferRevivables } from './revivables/utils'\r\n\r\nexport const OSRA_KEY = '__OSRA_KEY__' as const\r\nexport const OSRA_DEFAULT_KEY = '__OSRA_DEFAULT_KEY__' as const\r\nexport const OSRA_BOX = '__OSRA_BOX__' as const\r\n\r\nexport type Uuid = `${string}-${string}-${string}-${string}-${string}`\r\n\r\nexport type Jsonable =\r\n | boolean\r\n | null\r\n | number\r\n | string\r\n | { [key: string]: Jsonable }\r\n | Array<Jsonable>\r\n\r\nexport type Structurable =\r\n | Jsonable\r\n /** not really structureable but here for convenience */\r\n | void\r\n | undefined\r\n | BigInt\r\n | Date\r\n | RegExp\r\n | Blob\r\n | File\r\n | FileList\r\n | ArrayBuffer\r\n | ArrayBufferView\r\n | ImageBitmap\r\n | ImageData\r\n | { [key: string]: Structurable }\r\n | Array<Structurable>\r\n | Map<Structurable, Structurable>\r\n | Set<Structurable>\r\n \r\nexport type StructurableTransferable =\r\n | Structurable\r\n | Transferable\r\n | { [key: string]: StructurableTransferable }\r\n | Array<StructurableTransferable>\r\n | Map<StructurableTransferable, StructurableTransferable>\r\n | Set<StructurableTransferable>\r\n\r\nexport type Capable<TModules extends readonly RevivableModule[] = DefaultRevivableModules> =\r\n | StructurableTransferable\r\n | InferRevivables<TModules>\r\n | { [key: string]: Capable }\r\n | Array<Capable>\r\n | Map<Capable, Capable>\r\n | Set<Capable>\r\n\r\nexport type MessageBase = {\r\n [OSRA_KEY]: string\r\n /** UUID of the client that sent the message */\r\n uuid: Uuid\r\n name?: string\r\n}\r\n\r\nexport type ProtocolMessage =\r\n | {\r\n type: 'announce'\r\n /** Only set when acknowledging a remote announcement */\r\n remoteUuid?: Uuid\r\n }\r\n | {\r\n /** uuid already taken, try announcing with another one */\r\n type: 'reject-uuid-taken'\r\n remoteUuid: Uuid\r\n }\r\n | {\r\n type: 'close'\r\n remoteUuid: Uuid\r\n }\r\n\r\nexport type BidirectionalConnectionMessage =\r\n | {\r\n type: 'init'\r\n remoteUuid: Uuid\r\n data: Capable\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n /** uuid of the messagePort that the message was sent through */\r\n portId: Uuid\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message-port-close'\r\n remoteUuid: Uuid\r\n /** uuid of the messagePort that closed */\r\n portId: string\r\n }\r\n\r\nexport type UnidirectionalConnectionMessage = {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n portId: Uuid\r\n}\r\n\r\nexport type ConnectionMessage =\r\n | BidirectionalConnectionMessage\r\n | UnidirectionalConnectionMessage\r\n\r\nexport type MessageVariant =\r\n | ProtocolMessage\r\n | ConnectionMessage\r\n\r\nexport type Message =\r\n | MessageBase\r\n & MessageVariant\r\n\r\nexport type MessageContext = {\r\n port?: MessagePort | WebExtPort // WebExtension\r\n sender?: WebExtSender // WebExtension\r\n receiveTransport?: ReceivePlatformTransport\r\n source?: MessageEventSource | null // Window, Worker, WebSocket, ect...\r\n}\r\n\r\nexport type MessageEventDetail = {\r\n message: Message\r\n messageContext: MessageContext\r\n}\r\n\r\nexport type MessageEventMap = {\r\n message: CustomEvent<MessageEventDetail>\r\n}\r\nexport type MessageEventTarget = TypedEventTarget<MessageEventMap>\r\n\r\nexport type CustomTransport =\r\n { isJson?: boolean }\r\n & (\r\n | {\r\n receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void)\r\n emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void)\r\n }\r\n | { receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void) }\r\n | { emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void) }\r\n )\r\n\r\nexport type CustomEmitTransport = Extract<CustomTransport, { emit: any }>\r\nexport type CustomReceiveTransport = Extract<CustomTransport, { receive: any }>\r\n\r\nexport type EmitJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n\r\nexport type ReceiveJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n | WebExtOnConnect\r\n | WebExtOnMessage\r\n\r\nexport type JsonPlatformTransport =\r\n | { isJson: true }\r\n | EmitJsonPlatformTransport\r\n | ReceiveJsonPlatformTransport\r\n\r\nexport type EmitPlatformTransport =\r\n | EmitJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type ReceivePlatformTransport =\r\n | ReceiveJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type PlatformTransport =\r\n | EmitPlatformTransport\r\n | ReceivePlatformTransport\r\n\r\nexport type EmitTransport = EmitPlatformTransport & Extract<CustomTransport, { emit: any }>\r\nexport type ReceiveTransport = ReceivePlatformTransport & Extract<CustomTransport, { receive: any }>\r\n\r\nexport type Transport =\r\n | PlatformTransport\r\n | CustomTransport\r\n","import type { DefaultRevivableModules, RevivableModule } from '.'\r\nimport type { ConnectionMessage, MessageContext, MessageEventTarget, Transport, Uuid } from '../types'\r\nimport type { MessageChannelAllocator, PlatformCapabilities } from '../utils'\r\n\r\nimport { OSRA_BOX } from '../types'\r\n\r\nexport declare const UnderlyingType: unique symbol\r\nexport type UnderlyingType = typeof UnderlyingType\r\n\r\nexport const BoxBase = {\r\n [OSRA_BOX]: 'revivable',\r\n type: '' as string\r\n} as const\r\n\r\nexport type BoxBase<T extends string = string> =\r\n & typeof BoxBase\r\n & { type: T }\r\n\r\nexport type RevivableContext<TModules extends readonly RevivableModule[] = DefaultRevivableModules> = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n revivableModules: TModules\r\n eventTarget: MessageEventTarget\r\n /** MessageContext of the message being revived, used by OSRA_CONTEXT revivable */\r\n messageContext?: MessageContext\r\n}\r\n\r\nexport type ExtractModule<T> = T extends { isType: (value: unknown) => value is infer S } ? S : never\r\nexport type ExtractType<T> = T extends { isType: (value: unknown) => value is infer S } ? S : never\r\nexport type ExtractBoxInput<T> = T extends { box: (value: infer S) => value is any } ? S : never\r\nexport type ExtractReviveInput<T> = T extends { revive: (value: infer S) => value is any } ? S : never\r\nexport type ExtractBox<T> = T extends { box: (...args: any[]) => infer B } ? B : never\r\nexport type InferRevivables<TModules extends readonly unknown[]> =\r\n ExtractType<TModules[number]>\r\nexport type InferRevivableBox<TModules extends readonly unknown[]> =\r\n ExtractBox<TModules[number]>\r\n\r\nexport const isRevivableBox = <T extends RevivableContext>(value: any, _context: T): value is InferRevivableBox<T['revivableModules']> =>\r\n value\r\n && typeof value === 'object'\r\n && OSRA_BOX in value\r\n && value[OSRA_BOX] === 'revivable'\r\n","import type { MessageContext } from '../types'\r\nimport type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'context' as const\r\n\r\n/**\r\n * Internal symbol used to identify OSRA_CONTEXT objects at runtime.\r\n */\r\nconst OSRA_CONTEXT_MARKER = Symbol.for('OSRA_CONTEXT')\r\n\r\n/**\r\n * A special token that gets transformed into the MessageContext when revived on the receiving side.\r\n * Pass this value in your exposed API to receive information about the message context.\r\n *\r\n * Typed as MessageContext so it can be passed directly where MessageContext is expected.\r\n */\r\nexport const OSRA_CONTEXT: MessageContext = { [OSRA_CONTEXT_MARKER]: true } as MessageContext\r\n\r\nexport const isType = (value: unknown): value is MessageContext =>\r\n value !== null &&\r\n typeof value === 'object' &&\r\n OSRA_CONTEXT_MARKER in value\r\n\r\nexport const box = <T extends MessageContext, T2 extends RevivableContext>(\r\n _value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n _value: T,\r\n context: T2\r\n): MessageContext => {\r\n return context.messageContext ?? {}\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(OSRA_CONTEXT, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: MessageContext = revived\r\n // @ts-expect-error - not a MessageContext\r\n const notContext: string = revived\r\n}\r\n","import type { StructurableTransferable, Uuid } from '../types'\r\nimport type { StrictMessageChannel, StrictMessagePort } from './message-channel'\r\n\r\nexport const makeAllocator = <T>() => {\r\n const channels = new Map<string, T>()\r\n\r\n const alloc = (value: T): string => {\r\n let uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n channels.set(uuid, value)\r\n return uuid\r\n }\r\n\r\n const has = (uuid: string) => channels.has(uuid)\r\n const get = (uuid: string) => channels.get(uuid)\r\n\r\n const free = (uuid: string) => {\r\n channels.delete(uuid)\r\n }\r\n\r\n const set = (uuid: string, value: T) => {\r\n channels.set(uuid, value)\r\n }\r\n\r\n return {\r\n alloc,\r\n has,\r\n get,\r\n free,\r\n set\r\n }\r\n}\r\n\r\nexport type Allocator<T> = ReturnType<typeof makeAllocator<T>>\r\n\r\ntype AllocatedMessageChannel<\r\n T extends StructurableTransferable = StructurableTransferable,\r\n T2 extends StructurableTransferable = StructurableTransferable\r\n> = {\r\n uuid: Uuid\r\n /** Local port */\r\n port1: StrictMessagePort<T>\r\n /** Remote port that gets transferred, might be undefined if a remote context created the channel */\r\n port2?: StrictMessagePort<T2>\r\n}\r\n\r\nexport const makeMessageChannelAllocator = () => {\r\n const channels = new Map<string, AllocatedMessageChannel>()\r\n\r\n const result = {\r\n getUniqueUuid: () => {\r\n let uuid: Uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n return uuid\r\n },\r\n set: (uuid: Uuid, messagePorts: { port1: StrictMessagePort, port2?: StrictMessagePort }) => {\r\n channels.set(uuid, { uuid, ...messagePorts })\r\n },\r\n alloc: (\r\n uuid: Uuid | undefined = result.getUniqueUuid(),\r\n messagePorts?: { port1: StrictMessagePort, port2?: StrictMessagePort }\r\n ) => {\r\n if (messagePorts) {\r\n const allocatedMessageChannel = { uuid, ...messagePorts } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n }\r\n const messageChannel = new MessageChannel() as StrictMessageChannel\r\n const allocatedMessageChannel = {\r\n uuid,\r\n port1: messageChannel.port1,\r\n port2: messageChannel.port2\r\n } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n },\r\n has: (uuid: string) => channels.has(uuid),\r\n get: (uuid: string) => channels.get(uuid),\r\n free: (uuid: string) => channels.delete(uuid),\r\n getOrAlloc: (\r\n uuid: Uuid | undefined = result.getUniqueUuid(),\r\n messagePorts?: { port1: StrictMessagePort, port2?: StrictMessagePort }\r\n ) => {\r\n const existingChannel = result.get(uuid)\r\n if (existingChannel) return existingChannel!\r\n return result.alloc(uuid, messagePorts)\r\n }\r\n }\r\n return result\r\n}\r\n\r\nexport type MessageChannelAllocator = ReturnType<typeof makeMessageChannelAllocator>\r\n","import type {\r\n CustomTransport, EmitTransport,\r\n Message, MessageContext,\r\n ReceiveTransport\r\n} from '../types'\r\nimport type { WebExtOnMessage, WebExtPort, WebExtSender } from './type-guards'\r\n\r\nimport { OSRA_KEY } from '../types'\r\nimport {\r\n isOsraMessage, isCustomTransport,\r\n isWebExtensionOnConnect, isWebExtensionOnMessage,\r\n isWebExtensionPort, isWebSocket, isWindow, isSharedWorker\r\n} from './type-guards'\r\n\r\nexport const getWebExtensionGlobal = () => globalThis.browser ?? globalThis.chrome\r\nexport const getWebExtensionRuntime = () => getWebExtensionGlobal().runtime\r\n\r\nexport const checkOsraMessageKey = (message: any, key: string): message is Message =>\r\n isOsraMessage(message)\r\n && message[OSRA_KEY] === key\r\n\r\nexport const registerOsraMessageListener = (\r\n { listener, transport, remoteName, key = OSRA_KEY, unregisterSignal }:\r\n {\r\n listener: (message: Message, messageContext: MessageContext) => Promise<void>\r\n transport: ReceiveTransport\r\n remoteName?: string\r\n key?: string\r\n unregisterSignal?: AbortSignal\r\n }\r\n) => {\r\n const registerListenerOnReceiveTransport = (receiveTransport: Extract<CustomTransport, { receive: any }>['receive']) => {\r\n // Custom function handler\r\n if (typeof receiveTransport === 'function') {\r\n receiveTransport(listener)\r\n // WebExtension handler\r\n } else if (\r\n isWebExtensionPort(receiveTransport)\r\n || isWebExtensionOnConnect(receiveTransport)\r\n || isWebExtensionOnMessage(receiveTransport)\r\n ) {\r\n const listenOnWebExtOnMessage = (onMessage: WebExtOnMessage, port?: WebExtPort) => {\r\n const _listener = (message: object, sender?: WebExtSender) => {\r\n if (!checkOsraMessageKey(message, key)) return\r\n if (remoteName && message.name !== remoteName) return\r\n listener(message, { port, sender })\r\n }\r\n onMessage.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n onMessage.removeListener(_listener)\r\n )\r\n }\r\n }\r\n\r\n // WebExtOnConnect\r\n if (isWebExtensionOnConnect(receiveTransport)) {\r\n const _listener = (port: WebExtPort) => {\r\n listenOnWebExtOnMessage(port.onMessage as WebExtOnMessage, port)\r\n }\r\n receiveTransport.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeListener(_listener)\r\n )\r\n }\r\n // WebExtOnMessage\r\n } else if (isWebExtensionOnMessage(receiveTransport)) {\r\n listenOnWebExtOnMessage(receiveTransport)\r\n } else { // WebExtPort\r\n listenOnWebExtOnMessage(receiveTransport.onMessage as WebExtOnMessage)\r\n }\r\n } else { // Window, Worker, WebSocket, ect...\r\n const messageListener = (event: MessageEvent<Message>) => {\r\n if (!checkOsraMessageKey(event.data, key)) return\r\n if (remoteName && event.data.name !== remoteName) return\r\n listener(event.data, { receiveTransport, source: event.source })\r\n }\r\n receiveTransport.addEventListener('message', messageListener as EventListener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeEventListener('message', messageListener as EventListener)\r\n )\r\n }\r\n }\r\n }\r\n if (isCustomTransport(transport)) {\r\n registerListenerOnReceiveTransport(transport.receive)\r\n } else {\r\n registerListenerOnReceiveTransport(transport)\r\n }\r\n}\r\n\r\nexport const sendOsraMessage = (\r\n transport: EmitTransport,\r\n message: Message,\r\n origin = '*',\r\n transferables: Transferable[] = []\r\n) => {\r\n const sendToEmitTransport = (emitTransport: Extract<EmitTransport, { emit: any }>['emit']) => {\r\n if (typeof emitTransport === 'function') {\r\n emitTransport(message, transferables)\r\n } else if (isWebExtensionPort(emitTransport)) {\r\n emitTransport.postMessage(message)\r\n } else if (isWindow(emitTransport)) {\r\n emitTransport.postMessage(message, origin, transferables)\r\n } else if (isWebSocket(emitTransport)) {\r\n emitTransport.send(JSON.stringify(message))\r\n } else if (isSharedWorker(emitTransport)) {\r\n emitTransport.port.postMessage(message, transferables)\r\n } else { // MessagePort | ServiceWorker | Worker\r\n emitTransport.postMessage(message, transferables)\r\n }\r\n }\r\n\r\n if (isCustomTransport(transport)) {\r\n sendToEmitTransport(transport.emit)\r\n } else {\r\n sendToEmitTransport(transport)\r\n }\r\n}\r\n","import type { Runtime } from 'webextension-polyfill'\r\nimport type {\r\n CustomEmitTransport, CustomReceiveTransport,\r\n CustomTransport, EmitJsonPlatformTransport,\r\n EmitTransport, JsonPlatformTransport,\r\n Message, ReceiveJsonPlatformTransport,\r\n ReceiveTransport, Transport\r\n} from '../types'\r\n\r\nimport { OSRA_BOX, OSRA_KEY } from '../types'\r\nimport { getWebExtensionRuntime } from './platform'\r\n\r\nexport type TransferBox<T extends Transferable = Transferable> = {\r\n [OSRA_BOX]: 'transferable'\r\n value: T\r\n}\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypeArrayType = ReturnType<typeof typedArrayToType>\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypeArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isTypedArray = (value: any): value is TypedArray => typedArrayConstructors.some(typedArray => value instanceof typedArray)\r\nexport const isWebSocket = (value: any) => value instanceof WebSocket\r\nexport const isServiceWorkerContainer = (value: any): value is ServiceWorkerContainer => globalThis.ServiceWorkerContainer && value instanceof ServiceWorkerContainer\r\nexport const isWorker = (value: any): value is Worker => globalThis.Worker && value instanceof Worker\r\n// @ts-expect-error\r\nexport const isDedicatedWorker = (value: any): value is DedicatedWorkerGlobalScope => globalThis.DedicatedWorkerGlobalScope && value instanceof DedicatedWorkerGlobalScope\r\nexport const isSharedWorker = (value: any): value is SharedWorker => globalThis.SharedWorker && value instanceof SharedWorker\r\nexport const isMessagePort = (value: any) => value instanceof MessagePort\r\nexport const isPromise = (value: any) => value instanceof Promise\r\nexport const isFunction = (value: any): value is Function => typeof value === 'function'\r\nexport const isArrayBuffer = (value: any) => value instanceof ArrayBuffer\r\nexport const isReadableStream = (value: any) => value instanceof ReadableStream\r\nexport const isDate = (value: any) => value instanceof Date\r\nexport const isError = (value: any) => value instanceof Error\r\n\r\nexport const isAlwaysBox = (value: any): value is Function | Promise<any> | Date | Error =>\r\n isFunction(value)\r\n || isPromise(value)\r\n || isTypedArray(value)\r\n || isDate(value)\r\n || isError(value)\r\n\r\nexport const isOsraMessage = (value: any): value is Message =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as Message)[OSRA_KEY]\r\n )\r\n\r\nexport const isClonable = (value: any) =>\r\n globalThis.SharedArrayBuffer && value instanceof globalThis.SharedArrayBuffer ? true\r\n : false\r\n\r\nexport const isTransferable = (value: any): value is Transferable =>\r\n globalThis.ArrayBuffer && value instanceof globalThis.ArrayBuffer ? true\r\n : globalThis.MessagePort && value instanceof globalThis.MessagePort ? true\r\n : globalThis.ReadableStream && value instanceof globalThis.ReadableStream ? true\r\n : globalThis.WritableStream && value instanceof globalThis.WritableStream ? true\r\n : globalThis.TransformStream && value instanceof globalThis.TransformStream ? true\r\n : globalThis.ImageBitmap && value instanceof globalThis.ImageBitmap ? true\r\n : false\r\n\r\nexport const isTransferBox = (value: any): value is TransferBox<any> =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as TransferBox<Transferable>)[OSRA_BOX] === 'transferable'\r\n )\r\n\r\nexport type WebExtRuntime = typeof browser.runtime\r\nexport const isWebExtensionRuntime = (value: any): value is WebExtRuntime => {\r\n const runtime = getWebExtensionRuntime()\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && isWebExtensionOnConnect(runtime.onConnect)\r\n && runtime.id\r\n )\r\n}\r\n\r\nexport type WebExtPort = ReturnType<WebExtRuntime['connect']> | Runtime.Port\r\nexport const isWebExtensionPort = (value: any, connectPort: boolean = false): value is WebExtPort => {\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && ('name' in (value as WebExtPort))\r\n && ('disconnect' in (value as WebExtPort))\r\n && ('postMessage' in (value as WebExtPort))\r\n && (\r\n connectPort\r\n // these properties are only present on WebExtPort that were created through runtime.connect()\r\n ? (\r\n ('sender' in (value as WebExtPort))\r\n && ('onMessage' in (value as WebExtPort))\r\n && ('onDisconnect' in (value as WebExtPort))\r\n )\r\n : true\r\n )\r\n )\r\n}\r\n\r\nexport type WebExtSender = NonNullable<WebExtPort['sender']>\r\n\r\nexport type WebExtOnConnect = WebExtRuntime['onConnect']\r\nexport const isWebExtensionOnConnect = (value: any): value is WebExtOnConnect =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (value as WebExtOnConnect).addListener\r\n && (value as WebExtOnConnect).hasListener\r\n && (value as WebExtOnConnect).removeListener\r\n )\r\n\r\nexport type WebExtOnMessage = WebExtRuntime['onMessage']\r\nexport const isWebExtensionOnMessage = (value: any): value is WebExtOnMessage =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (value as WebExtOnMessage).addListener\r\n && (value as WebExtOnMessage).hasListener\r\n && (value as WebExtOnMessage).removeListener\r\n )\r\n\r\nexport const isWindow = (value: unknown): value is Window => {\r\n if (!value || typeof value !== 'object') return false\r\n\r\n try {\r\n return (value as Window).window === value\r\n } catch {\r\n try {\r\n const w = value as Window\r\n return typeof w.closed === 'boolean' && typeof w.close === 'function'\r\n } catch {\r\n return false\r\n }\r\n }\r\n }\r\n\r\nexport type IsEmitJsonOnlyTransport<T extends Transport> = T extends EmitJsonPlatformTransport ? true : false\r\nexport const isEmitJsonOnlyTransport = (value: any): value is EmitJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n\r\nexport type IsReceiveJsonOnlyTransport<T extends Transport> = T extends ReceiveJsonPlatformTransport ? true : false\r\nexport const isReceiveJsonOnlyTransport = (value: any): value is ReceiveJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n || isWebExtensionOnConnect(value)\r\n || isWebExtensionOnMessage(value)\r\n\r\nexport type IsJsonOnlyTransport<T extends Transport> = T extends JsonPlatformTransport ? true : false\r\nexport const isJsonOnlyTransport = (value: Transport): value is Extract<Transport, JsonPlatformTransport> =>\r\n ('isJson' in value && value.isJson === true)\r\n || isEmitJsonOnlyTransport(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n\r\nexport type IsEmitTransport<T extends Transport> = T extends EmitTransport ? true : false\r\nexport const isEmitTransport = (value: any): value is EmitTransport =>\r\n isWindow(value)\r\n || isEmitJsonOnlyTransport(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomEmitTransport(value)\r\n\r\nexport function assertEmitTransport (transport: Transport): asserts transport is EmitTransport {\r\n if (!isEmitTransport(transport)) throw new Error('Transport is not emitable')\r\n}\r\n\r\n\r\nexport type IsReceiveTransport<T extends Transport> = T extends ReceiveTransport ? true : false\r\nexport const isReceiveTransport = (value: any): value is ReceiveTransport =>\r\n isWindow(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport function assertReceiveTransport (transport: Transport): asserts transport is ReceiveTransport {\r\n if (!isReceiveTransport(transport)) throw new Error('Transport is not receiveable')\r\n}\r\n\r\nexport const isCustomEmitTransport = (value: any): value is CustomEmitTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (\r\n 'emit' in value\r\n && (\r\n isEmitTransport(value.emit)\r\n || typeof value.emit === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport const isCustomReceiveTransport = (value: any): value is CustomReceiveTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (\r\n 'receive' in value\r\n && (\r\n isReceiveTransport(value.receive)\r\n || typeof value.receive === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport type IsCustomTransport<T extends Transport> = T extends CustomTransport ? true : false\r\nexport const isCustomTransport = (value: any): value is CustomTransport =>\r\n isCustomEmitTransport(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport const isTransport = (value: any): value is Transport =>\r\n isEmitTransport(value)\r\n || isReceiveTransport(value)\r\n || isCustomTransport(value)\r\n || isJsonOnlyTransport(value)\r\n","import type { Capable } from '../types'\r\nimport type { TransferBox } from './type-guards'\r\n\r\nimport { OSRA_BOX } from '../types'\r\nimport { deepReplace } from './replace'\r\nimport { isClonable, isTransferable, isTransferBox } from './type-guards'\r\n\r\nexport const getTransferableObjects = (value: any): Transferable[] => {\r\n const transferables: Transferable[] = []\r\n const recurse = (value: any): any =>\r\n isClonable(value) ? undefined\r\n : isTransferable(value) ? transferables.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferables\r\n}\r\n\r\nexport const getTransferBoxes = (value: any): TransferBox<Transferable>[] => {\r\n const transferBoxes: TransferBox<any>[] = []\r\n const recurse = (value: any): any =>\r\n isTransferBox(value) ? transferBoxes.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferBoxes\r\n}\r\n\r\n/** This box tells the protocol that the value should be copied instead of transfered */\r\nexport const transfer = <T extends Transferable>(value: T) => ({\r\n [OSRA_BOX]: 'transferable',\r\n value\r\n}) as TransferBox<T>\r\n\r\nexport const recursiveTransfer = <T extends Capable>(value: T) =>\r\n deepReplace(\r\n value,\r\n isTransferable,\r\n (value) => transfer(value)\r\n )\r\n","import { getTransferableObjects } from './transferable'\r\n\r\nexport type PlatformCapabilities = {\r\n jsonOnly: boolean\r\n messagePort: boolean\r\n arrayBuffer: boolean\r\n transferable: boolean\r\n transferableStream: boolean\r\n}\r\n\r\nconst probePlatformCapabilityUtil = <T>(value: T, transfer = false): Promise<T> => {\r\n const { port1, port2 } = new MessageChannel()\r\n const result = new Promise<T>(resolve =>\r\n port1.addEventListener('message', message =>\r\n resolve(message.data)\r\n )\r\n )\r\n port1.start()\r\n port2.postMessage(value, transfer ? getTransferableObjects(value) : [])\r\n return result\r\n}\r\n\r\nconst probeMessagePortTransfer = async () => {\r\n const { port1 } = new MessageChannel()\r\n const port = await probePlatformCapabilityUtil(port1, true)\r\n return port instanceof MessagePort\r\n}\r\n\r\nconst probeArrayBufferClone = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeArrayBufferTransfer = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer, true)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeTransferableStream = async () => {\r\n const stream = new ReadableStream({\r\n start(controller) {\r\n controller.enqueue(new Uint8Array(1))\r\n controller.close()\r\n }\r\n })\r\n const transferableStream = await probePlatformCapabilityUtil(stream, true)\r\n return transferableStream instanceof ReadableStream\r\n}\r\n\r\nexport const probePlatformCapabilities = async (): Promise<PlatformCapabilities> => {\r\n const [\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n ] = await Promise.all([\r\n probeMessagePortTransfer().catch(() => false),\r\n probeArrayBufferClone().catch(() => false),\r\n probeArrayBufferTransfer().catch(() => false),\r\n probeTransferableStream().catch(() => false)\r\n ])\r\n return {\r\n jsonOnly:\r\n !messagePort\r\n && !arrayBuffer\r\n && !transferable\r\n && !transferableStream,\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n }\r\n}\r\n","import type { IsJsonOnlyTransport } from '../utils'\r\nimport type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { isJsonOnlyTransport } from '../utils'\r\n\r\nexport const type = 'arrayBuffer' as const\r\n\r\nexport const isType = (value: unknown): value is ArrayBuffer =>\r\n value instanceof ArrayBuffer\r\n\r\nexport const box = <T extends ArrayBuffer, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n ...(\r\n isJsonOnlyTransport(_context.transport)\r\n ? { base64Buffer: new Uint8Array(value).toBase64() }\r\n : { arrayBuffer: value }\r\n ) as (\r\n IsJsonOnlyTransport<T2['transport']> extends true ? { base64Buffer: string }\r\n : IsJsonOnlyTransport<T2['transport']> extends false ? { arrayBuffer: ArrayBuffer }\r\n : { base64Buffer: string } | { arrayBuffer: ArrayBuffer }\r\n )\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) =>\r\n 'arrayBuffer' in value ? value.arrayBuffer\r\n : (\r\n Uint8Array\r\n .fromBase64(value.base64Buffer)\r\n .buffer\r\n )\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new ArrayBuffer(10), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: ArrayBuffer = revived\r\n // @ts-expect-error - not an ArrayBuffer\r\n const notArrayBuffer: string = revived\r\n // @ts-expect-error - cannot box non-ArrayBuffer\r\n box('not an array buffer', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'date' as const\r\n\r\nexport const isType = (value: unknown): value is Date =>\r\n value instanceof Date\r\n\r\nexport const box = <T extends Date, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n ISOString: value.toISOString()\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n): Date => {\r\n return new Date(value.ISOString)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Date(), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Date = revived\r\n // @ts-expect-error - not a Date\r\n const notDate: string = revived\r\n // @ts-expect-error - cannot box non-Date\r\n box('not a date', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'headers' as const\r\n\r\nexport const isType = (value: unknown): value is Headers =>\r\n value instanceof Headers\r\n\r\nexport const box = <T extends Headers, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n entries: [...value.entries()]\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n): Headers => {\r\n return new Headers(value.entries)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Headers(), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Headers = revived\r\n // @ts-expect-error - not a Headers\r\n const notHeaders: string = revived\r\n // @ts-expect-error - cannot box non-Headers\r\n box('not a header', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'error' as const\r\n\r\nexport const isType = (value: unknown): value is Error =>\r\n value instanceof Error\r\n\r\nexport const box = <T extends Error, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n message: value.message,\r\n stack: value.stack || value.toString()\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => new Error(value.message, { cause: value.stack })\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Error('test'), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Error = revived\r\n // @ts-expect-error - not an Error\r\n const notError: string = revived\r\n // @ts-expect-error - cannot box non-Error\r\n box('not an error', {} as RevivableContext)\r\n}\r\n","import type { IsJsonOnlyTransport } from '../utils'\r\nimport type { RevivableContext, UnderlyingType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { isJsonOnlyTransport } from '../utils'\r\n\r\nexport const type = 'typedArray' as const\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\n\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypedArrayType = ReturnType<typeof typedArrayToType>\r\n\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypedArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isType = (value: unknown): value is TypedArray =>\r\n typedArrayConstructors.some(constructor => value instanceof constructor)\r\n\r\nexport const box = <T extends TypedArray, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n typedArrayType: typedArrayToType(value),\r\n ...(\r\n isJsonOnlyTransport(context.transport)\r\n ? { base64Buffer: new Uint8Array(value.buffer).toBase64() }\r\n : { arrayBuffer: value.buffer }\r\n ) as (\r\n IsJsonOnlyTransport<T2['transport']> extends true ? { base64Buffer: string }\r\n : IsJsonOnlyTransport<T2['transport']> extends false ? { arrayBuffer: ArrayBuffer }\r\n : { base64Buffer: string } | { arrayBuffer: ArrayBuffer }\r\n ) & { [UnderlyingType]: T }\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const TypedArrayConstructor = typedArrayTypeToTypedArrayConstructor(value.typedArrayType as TypedArrayType)\r\n const arrayBuffer =\r\n 'arrayBuffer' in value\r\n ? value.arrayBuffer\r\n : Uint8Array.fromBase64(value.base64Buffer).buffer\r\n return new TypedArrayConstructor(arrayBuffer)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const uint8Boxed = box(new Uint8Array(10), {} as RevivableContext)\r\n const uint8Revived = revive(uint8Boxed, {} as RevivableContext)\r\n const expectedUint8: Uint8Array = uint8Revived\r\n // @ts-expect-error - wrong typed array type\r\n const wrongType: Int32Array = uint8Revived\r\n\r\n const float32Boxed = box(new Float32Array(10), {} as RevivableContext)\r\n const float32Revived = revive(float32Boxed, {} as RevivableContext)\r\n const expectedFloat32: Float32Array = float32Revived\r\n // @ts-expect-error - wrong typed array type\r\n const wrongFloat: Uint8Array = float32Revived\r\n\r\n // @ts-expect-error - cannot box non-TypedArray\r\n box('not a typed array', {} as RevivableContext)\r\n}\r\n","import type { Capable, ConnectionMessage, Message, StructurableTransferable, Uuid } from '../types'\r\nimport type { StrictMessagePort } from '../utils/message-channel'\r\nimport type { RevivableContext, BoxBase as BoxBaseType, UnderlyingType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { OSRA_BOX } from '../types'\r\nimport { getTransferableObjects, isJsonOnlyTransport } from '../utils'\r\n\r\n/**\r\n * FinalizationRegistry for automatically cleaning up MessagePorts when they are garbage collected.\r\n * This is used in JSON-only mode where MessagePorts can't be transferred directly.\r\n */\r\ntype PortCleanupInfo = {\r\n sendMessage: (message: ConnectionMessage) => void\r\n remoteUuid: Uuid\r\n portId: string\r\n cleanup: () => void\r\n}\r\n\r\nconst messagePortRegistry = new FinalizationRegistry<PortCleanupInfo>((info) => {\r\n // Send close message to remote side\r\n info.sendMessage({\r\n type: 'message-port-close',\r\n remoteUuid: info.remoteUuid,\r\n portId: info.portId\r\n })\r\n // Perform local cleanup\r\n info.cleanup()\r\n})\r\n\r\nexport const type = 'messagePort' as const\r\n\r\nexport type BoxedMessagePort<T extends StructurableTransferable = StructurableTransferable> =\r\n & BoxBaseType<typeof type>\r\n & ({ portId: string } | { port: StrictMessagePort<T> })\r\n & { [UnderlyingType]: StrictMessagePort<T> }\r\n\r\ndeclare const StructurableTransferableError: unique symbol\r\ntype StructurableTransferablePort<T> = T extends StructurableTransferable\r\n ? StrictMessagePort<T>\r\n : { [StructurableTransferableError]: 'Message type must extend StructurableTransferable'; __badType__: T }\r\n\r\ntype ExtractStructurableTransferable<T> = T extends StructurableTransferable ? T : never\r\n\r\nexport const isType = (value: unknown): value is MessagePort =>\r\n value instanceof MessagePort\r\n\r\nconst isAlreadyBoxed = (value: unknown): boolean =>\r\n value !== null &&\r\n typeof value === 'object' &&\r\n OSRA_BOX in value &&\r\n (value as Record<string, unknown>)[OSRA_BOX] === 'revivable'\r\n\r\nexport const box = <T, T2 extends RevivableContext = RevivableContext>(\r\n value: StructurableTransferablePort<T>,\r\n context: T2\r\n) => {\r\n if (isJsonOnlyTransport(context.transport)) {\r\n const messagePort = value as StrictMessagePort<ExtractStructurableTransferable<T>>\r\n // Only generate a unique UUID, don't store the port in the allocator.\r\n // Storing the port would create a strong reference that prevents GC and FinalizationRegistry cleanup.\r\n const portId = context.messageChannels.getUniqueUuid()\r\n\r\n // Use WeakRef to allow messagePort to be garbage collected.\r\n // The eventTargetListener would otherwise hold a strong reference preventing GC.\r\n const messagePortRef = new WeakRef(messagePort)\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n // Define listener before registering with FinalizationRegistry so we can remove it in cleanup\r\n const eventTargetListener = ({ detail }: CustomEvent<{ message: Message }>) => {\r\n const { message } = detail\r\n if (message.type === 'message-port-close') {\r\n if (message.portId !== portId) return\r\n context.messageChannels.free(portId)\r\n const port = messagePortRef.deref()\r\n if (port) {\r\n // Unregister from FinalizationRegistry to prevent double-close\r\n messagePortRegistry.unregister(port)\r\n port.close()\r\n }\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n return\r\n }\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n const port = messagePortRef.deref()\r\n if (!port) {\r\n // Port was garbage collected, remove this listener\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n return\r\n }\r\n port.postMessage(message.data as ExtractStructurableTransferable<T>, getTransferableObjects(message.data))\r\n }\r\n\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n // Define this listener before registering so it can be removed in cleanup\r\n function messagePortListener({ data }: MessageEvent) {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: (isAlreadyBoxed(data) ? data : recursiveBox(data as Capable, context)) as Capable,\r\n portId\r\n })\r\n }\r\n\r\n // Register the messagePort for automatic cleanup when garbage collected\r\n // Use messagePort itself as the unregister token\r\n messagePortRegistry.register(messagePortRef.deref()!, {\r\n sendMessage: context.sendMessage,\r\n remoteUuid: context.remoteUuid,\r\n portId,\r\n cleanup: () => {\r\n context.messageChannels.free(portId)\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n messagePortRef.deref()?.removeEventListener('message', messagePortListener)\r\n messagePortRef.deref()?.close()\r\n }\r\n }, messagePortRef.deref())\r\n\r\n messagePortRef.deref()?.addEventListener('message', messagePortListener)\r\n messagePortRef.deref()?.start()\r\n\r\n context.eventTarget.addEventListener('message', eventTargetListener)\r\n \r\n const result = {\r\n ...BoxBase,\r\n type,\r\n portId\r\n }\r\n return result as typeof result & { [UnderlyingType]: StrictMessagePort<ExtractStructurableTransferable<T>> }\r\n }\r\n const result = {\r\n ...BoxBase,\r\n type,\r\n port: value\r\n }\r\n return result as typeof result & { [UnderlyingType]: StrictMessagePort<ExtractStructurableTransferable<T>> }\r\n}\r\n\r\nexport const revive = <T extends StructurableTransferable, T2 extends RevivableContext>(\r\n value: BoxedMessagePort<T>,\r\n context: T2\r\n): StrictMessagePort<T> => {\r\n if ('portId' in value) {\r\n const { portId } = value\r\n const { port1: userPort, port2: internalPort } = new MessageChannel()\r\n\r\n const existingChannel = context.messageChannels.get(value.portId)\r\n const { port1 } =\r\n existingChannel\r\n ? existingChannel\r\n : context.messageChannels.alloc(value.portId as Uuid)\r\n\r\n const userPortRef = new WeakRef(userPort)\r\n\r\n // Define all listeners before registering so they can be removed in cleanup\r\n const eventTargetListener = ({ detail }: CustomEvent<{ message: Message }>) => {\r\n const { message } = detail\r\n if (message.type !== 'message-port-close' || message.portId !== portId) return\r\n const port = userPortRef.deref()\r\n if (port) {\r\n // Unregister from FinalizationRegistry to prevent double-close\r\n messagePortRegistry.unregister(port)\r\n }\r\n performCleanup()\r\n }\r\n\r\n const port1Listener = ({ data: message }: MessageEvent) => {\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n\r\n const port = userPortRef.deref()\r\n if (!port) {\r\n // Port was garbage collected, cleanup\r\n performCleanup()\r\n return\r\n }\r\n\r\n // if the returned messagePort has been registered as internal message port, then we proxy the data without reviving it\r\n if (context.messagePorts.has(port)) {\r\n internalPort.postMessage(message.data)\r\n } else {\r\n // In this case, userPort is actually passed by the user of osra and we should revive all the message data\r\n const revivedData = recursiveRevive(message.data, context)\r\n internalPort.postMessage(revivedData, getTransferableObjects(revivedData))\r\n }\r\n }\r\n\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n // Define this listener before performCleanup so it can be removed in cleanup\r\n function internalPortListener({ data }: MessageEvent) {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: isAlreadyBoxed(data) ? data : recursiveBox(data, context),\r\n portId: portId as Uuid\r\n })\r\n }\r\n\r\n const performCleanup = () => {\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n port1.removeEventListener('message', port1Listener)\r\n internalPort.removeEventListener('message', internalPortListener)\r\n internalPort.close()\r\n // Close the allocator's MessageChannel ports before freeing\r\n // The allocator creates a MessageChannel with port1 and port2 - both must be closed\r\n const allocatedChannel = context.messageChannels.get(portId)\r\n if (allocatedChannel) {\r\n allocatedChannel.port1.close()\r\n if (allocatedChannel.port2) {\r\n allocatedChannel.port2.close()\r\n }\r\n }\r\n context.messageChannels.free(portId)\r\n }\r\n\r\n // Register the userPort for automatic cleanup when garbage collected\r\n // Use userPort itself as the unregister token\r\n messagePortRegistry.register(userPort, {\r\n sendMessage: context.sendMessage,\r\n remoteUuid: context.remoteUuid,\r\n portId,\r\n cleanup: performCleanup\r\n }, userPort)\r\n\r\n internalPort.addEventListener('message', internalPortListener)\r\n internalPort.start()\r\n\r\n // Listen for close messages from the remote side through the main event target\r\n context.eventTarget.addEventListener('message', eventTargetListener)\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n port1.addEventListener('message', port1Listener)\r\n port1.start()\r\n\r\n return userPort as StrictMessagePort<T>\r\n }\r\n return value.port\r\n}\r\n\r\nconst typeCheck = () => {\r\n const port = new MessageChannel().port1 as StrictMessagePort<{ foo: string }>\r\n const boxed = box(port, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: StrictMessagePort<{ foo: string }> = revived\r\n // @ts-expect-error - wrong message type\r\n const wrongType: StrictMessagePort<{ bar: number }> = revived\r\n // @ts-expect-error - non-StructurableTransferable message type\r\n box(new MessageChannel().port1 as StrictMessagePort<Promise<string>>, {} as RevivableContext)\r\n}\r\n","import type { Capable } from '../types'\r\nimport type { RevivableContext } from './utils'\r\nimport type { StrictMessagePort } from '../utils/message-channel'\r\nimport type { UnderlyingType } from '.'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'promise' as const\r\n\r\nexport type Context =\r\n | { type: 'resolve', data: Capable }\r\n | { type: 'reject', error: string }\r\n\r\ndeclare const CapableError: unique symbol\r\ntype CapablePromise<T> = T extends Capable\r\n ? Promise<T>\r\n : { [CapableError]: 'Message type must extend Capable'; __badType__: T }\r\n\r\ntype ExtractCapable<T> = T extends Capable ? T : never\r\n\r\nexport type BoxedPromise<T extends Capable = Capable> = {\r\n __OSRA_BOX__: 'revivable'\r\n type: typeof type\r\n port: ReturnType<typeof boxMessagePort>\r\n [UnderlyingType]: T\r\n}\r\n\r\nexport const isType = (value: unknown): value is Promise<any> =>\r\n value instanceof Promise\r\n\r\nexport const box = <T, T2 extends RevivableContext>(\r\n value: CapablePromise<T>,\r\n context: T2\r\n): BoxedPromise<ExtractCapable<T>> => {\r\n const promise = value as Promise<ExtractCapable<T>>\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const sendResult = (result: Context) => {\r\n const boxedResult = recursiveBox(result, context)\r\n localPort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n localPort.close()\r\n // Clean up the remote port from the set (it was transferred earlier)\r\n context.messagePorts.delete(remotePort)\r\n }\r\n\r\n promise\r\n .then((data: ExtractCapable<T>) => sendResult({ type: 'resolve', data }))\r\n .catch((error: unknown) => sendResult({ type: 'reject', error: (error as Error)?.stack ?? String(error) }))\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n port: boxMessagePort(remotePort as unknown as StrictMessagePort<string>, context)\r\n } as unknown as BoxedPromise<ExtractCapable<T>>\r\n}\r\n\r\nexport const revive = <T extends BoxedPromise, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n) => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort<string>, context)\r\n context.messagePorts.add(port as MessagePort)\r\n return new Promise<T[UnderlyingType]>((resolve, reject) => {\r\n port.addEventListener('message', (event) => {\r\n const data = (event as unknown as MessageEvent<Context>).data\r\n const result = recursiveRevive(data, context) as Context\r\n if (result.type === 'resolve') {\r\n resolve(result.data as T[UnderlyingType])\r\n } else {\r\n reject(result.error)\r\n }\r\n context.messagePorts.delete(port as MessagePort)\r\n port.close()\r\n }, { once: true })\r\n port.start()\r\n })\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(Promise.resolve(1 as const), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Promise<1> = revived\r\n // @ts-expect-error\r\n const notExpected: Promise<string> = revived\r\n // @ts-expect-error\r\n box(1 as const, {} as RevivableContext)\r\n}\r\n","import type { Capable } from '../types'\r\nimport type { UnderlyingType, RevivableContext, BoxBase as BoxBaseType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'function' as const\r\n\r\n/**\r\n * FinalizationRegistry for automatically cleaning up function ports when the revived function is garbage collected.\r\n */\r\ntype FunctionCleanupInfo = {\r\n port: MessagePort\r\n}\r\n\r\nconst functionRegistry = new FinalizationRegistry<FunctionCleanupInfo>((info) => {\r\n // Send a close signal through the port before closing it\r\n try {\r\n info.port.postMessage({ __osra_close__: true })\r\n } catch { /* Port may already be closed */ }\r\n try {\r\n info.port.close()\r\n } catch { /* Port may already be closed */ }\r\n})\r\n\r\nexport type CallContext = [\r\n /** MessagePort or portId that will be used to send the result of the function call */\r\n MessagePort | string,\r\n /** Arguments that will be passed to the function call */\r\n Capable[]\r\n]\r\n\r\nexport type BoxedFunction<T extends (...args: any[]) => any = (...args: any[]) => any> =\r\n & BoxBaseType<typeof type>\r\n & { port: BoxedMessagePort }\r\n & { [UnderlyingType]: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> }\r\n\r\ntype CapableFunction<T> = T extends (...args: infer P) => infer R\r\n ? P extends Capable[]\r\n ? R extends Capable ? T : never\r\n : never\r\n : never\r\n\r\nexport const isType = (value: unknown): value is (...args: any[]) => any =>\r\n typeof value === 'function'\r\n\r\nexport const box = <T extends (...args: any[]) => any, T2 extends RevivableContext>(\r\n value: T & CapableFunction<T>,\r\n context: T2\r\n): BoxedFunction<T> => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const cleanup = () => {\r\n context.messagePorts.delete(remotePort)\r\n localPort.close()\r\n }\r\n\r\n localPort.addEventListener('message', ({ data }: MessageEvent<CallContext | { __osra_close__: true }>) => {\r\n // Check for close signal\r\n if (data && typeof data === 'object' && '__osra_close__' in data) {\r\n cleanup()\r\n return\r\n }\r\n const [returnValuePort, args] = recursiveRevive(data as CallContext, context) as [MessagePort, Capable[]]\r\n const result = (async () => value(...args))()\r\n const boxedResult = recursiveBox(result, context)\r\n returnValuePort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n })\r\n localPort.start()\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n port: boxMessagePort(remotePort as any, context)\r\n } as BoxedFunction<T>\r\n}\r\n\r\nexport const revive = <T extends BoxedFunction, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort, context)\r\n\r\n const func = (...args: Capable[]) =>\r\n new Promise((resolve, reject) => {\r\n const { port1: returnValueLocalPort, port2: returnValueRemotePort } = new MessageChannel()\r\n context.messagePorts.add(returnValueRemotePort)\r\n const callContext = recursiveBox([returnValueRemotePort, args] as const, context)\r\n ;(port as MessagePort).postMessage(callContext, getTransferableObjects(callContext))\r\n // Remove the remote port from the set after transfer (it's neutered now)\r\n context.messagePorts.delete(returnValueRemotePort)\r\n\r\n returnValueLocalPort.addEventListener('message', ({ data }: MessageEvent<Capable>) => {\r\n const result = recursiveRevive(data, context) as Promise<Capable>\r\n result\r\n .then(resolve)\r\n .catch(reject)\r\n .finally(() => {\r\n returnValueLocalPort.close()\r\n })\r\n }, { once: true })\r\n returnValueLocalPort.start()\r\n })\r\n\r\n // Register the function for automatic cleanup when garbage collected\r\n functionRegistry.register(func, { port: port as MessagePort }, func)\r\n\r\n return func\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box((a: number, b: string) => a + b.length, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: (a: number, b: string) => Promise<number> = revived\r\n // @ts-expect-error - wrong return type\r\n const wrongReturn: (a: number, b: string) => Promise<string> = revived\r\n // @ts-expect-error - wrong parameter types\r\n const wrongParams: (a: string, b: number) => Promise<number> = revived\r\n // @ts-expect-error - non-Capable parameter type (Set is not directly Capable as parameter)\r\n box((a: WeakMap<object, string>) => a, {} as RevivableContext)\r\n // @ts-expect-error - non-Capable return type\r\n box(() => new WeakMap(), {} as RevivableContext)\r\n}\r\n","import type { Capable, StructurableTransferable } from '../types'\r\nimport type { RevivableContext } from './utils'\r\nimport type { StrictMessageChannel, StrictMessagePort } from '../utils/message-channel'\r\nimport type { UnderlyingType } from '.'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'readableStream' as const\r\n\r\nexport type PullContext = {\r\n type: 'pull' | 'cancel'\r\n}\r\n\r\nexport type BoxedReadableStream<T extends ReadableStream = ReadableStream> = {\r\n __OSRA_BOX__: 'revivable'\r\n type: typeof type\r\n port: BoxedMessagePort\r\n [UnderlyingType]: T\r\n}\r\n\r\nexport const isType = (value: unknown): value is ReadableStream =>\r\n value instanceof ReadableStream\r\n\r\nexport const box = <T extends ReadableStream, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): BoxedReadableStream<T> => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel() as StrictMessageChannel<StructurableTransferable, StructurableTransferable>\r\n context.messagePorts.add(remotePort as MessagePort)\r\n\r\n const reader = value.getReader()\r\n\r\n ;(localPort as MessagePort).addEventListener('message', async ({ data }) => {\r\n const { type } = recursiveRevive(data, context) as PullContext\r\n if (type === 'pull') {\r\n const pullResult = reader.read()\r\n const boxedResult = recursiveBox(pullResult, context)\r\n ;(localPort as MessagePort).postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n } else {\r\n reader.cancel()\r\n localPort.close()\r\n }\r\n })\r\n localPort.start()\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n port: boxMessagePort(remotePort as MessagePort as StrictMessagePort<Record<string, StructurableTransferable>>, context)\r\n } as BoxedReadableStream<T>\r\n}\r\n\r\nexport const revive = <T extends BoxedReadableStream, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort, context) as MessagePort\r\n context.messagePorts.add(port as MessagePort)\r\n port.start()\r\n\r\n return new ReadableStream({\r\n start(_controller) {},\r\n pull(controller) {\r\n return new Promise((resolve, reject) => {\r\n port.addEventListener('message', async ({ data }) => {\r\n const result = recursiveRevive(data, context) as Promise<ReadableStreamReadResult<any>>\r\n result\r\n .then(result => {\r\n if (result.done) controller.close()\r\n else controller.enqueue(result.value)\r\n resolve()\r\n })\r\n .catch(reject)\r\n }, { once: true })\r\n port.postMessage(recursiveBox({ type: 'pull' }, context))\r\n })\r\n },\r\n cancel() {\r\n port.postMessage(recursiveBox({ type: 'cancel' }, context))\r\n port.close()\r\n }\r\n }) as T[UnderlyingType]\r\n}\r\n\r\nconst typeCheck = () => {\r\n const stream = new ReadableStream<number>()\r\n const boxed = box(stream, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: ReadableStream<number> = revived\r\n // @ts-expect-error - wrong stream type\r\n const wrongType: ReadableStream<string> = revived\r\n // @ts-expect-error - not a ReadableStream\r\n box('not a stream', {} as RevivableContext)\r\n}\r\n","import type { BoxBase, RevivableContext } from './utils'\r\nexport type { UnderlyingType } from './utils'\r\nimport type { DeepReplaceWithBox, DeepReplaceWithRevive, ReplaceWithBox, ReplaceWithRevive } from '../utils/replace'\r\n\r\nimport { Capable } from '../types'\r\nimport { isRevivableBox } from './utils'\r\nimport * as arrayBuffer from './array-buffer'\r\nimport * as context from './context'\r\nimport * as date from './date'\r\nimport * as headers from './headers'\r\nimport * as error from './error'\r\nimport * as typedArray from './typed-array'\r\nimport * as promise from './promise'\r\nimport * as func from './function'\r\nimport * as messagePort from './message-port'\r\nimport * as readableStream from './readable-stream'\r\n\r\nexport type RevivableModule<T extends string = string, T2 = any, T3 extends BoxBase<T> = any> = {\r\n readonly type: T\r\n readonly isType: (value: unknown) => value is T2\r\n readonly box: ((value: T2, context: RevivableContext) => T3) | ((...args: any[]) => any)\r\n readonly revive: (value: T3, context: RevivableContext) => T2\r\n}\r\n\r\nexport const defaultRevivableModules = [\r\n arrayBuffer,\r\n context,\r\n date,\r\n headers,\r\n error,\r\n typedArray,\r\n promise,\r\n func,\r\n messagePort,\r\n readableStream\r\n] as const\r\n\r\nexport type DefaultRevivableModules = typeof defaultRevivableModules\r\n\r\nexport type DefaultRevivableModule = DefaultRevivableModules[number]\r\n\r\nexport const findModuleForValue = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithBox<T, T2['revivableModules'][number]>\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const box = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithBox<T, T2['revivableModules'][number]>\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const recursiveBox = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): DeepReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = DeepReplaceWithBox<T, T2['revivableModules'][number]>\r\n\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n\r\n return (\r\n Array.isArray(value) ? value.map(value => recursiveBox(value, context)) as ReturnCastType\r\n : value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveBox(value, context)\r\n ])\r\n )\r\n ) as ReturnCastType\r\n : value as ReturnCastType\r\n )\r\n}\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithRevive<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithRevive<T, T2['revivableModules'][number]>\r\n const boxType =\r\n isRevivableBox(value, context)\r\n ? value.type\r\n : undefined\r\n const handledByModule = context.revivableModules.find(module => module.type === boxType)\r\n if (handledByModule) {\r\n return (handledByModule.revive as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const recursiveRevive = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): DeepReplaceWithRevive<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = DeepReplaceWithRevive<T, T2['revivableModules'][number]>\r\n\r\n // First check if the value is a revivable box and revive it\r\n if (isRevivableBox(value, context)) {\r\n const handledByModule = context.revivableModules.find(module => module.type === value.type)\r\n if (handledByModule) {\r\n return (handledByModule.revive as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n }\r\n\r\n // Then recurse into arrays and plain objects\r\n return (\r\n Array.isArray(value) ? value.map(value => recursiveRevive(value, context)) as ReturnCastType\r\n : value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveRevive(value, context)\r\n ])\r\n )\r\n ) as ReturnCastType\r\n : value as ReturnCastType\r\n )\r\n}\r\n","import type {\r\n Capable, ConnectionMessage,\r\n Message,\r\n MessageContext,\r\n MessageEventTarget,\r\n Transport,\r\n Uuid\r\n} from '../types'\r\nimport type { MessageChannelAllocator } from './allocator'\r\nimport type { PlatformCapabilities } from './capabilities'\r\nimport type { StrictMessagePort } from './message-channel'\r\n\r\nimport { makeMessageChannelAllocator } from './allocator'\r\nimport { DefaultRevivableModules, defaultRevivableModules, recursiveBox, recursiveRevive, RevivableModule } from '../revivables'\r\n\r\nexport type BidirectionalConnectionContext = {\r\n type: 'bidirectional'\r\n eventTarget: MessageEventTarget\r\n connection: BidirectionalConnection\r\n}\r\nexport type UnidirectionalEmittingConnectionContext = {\r\n type: 'unidirectional-emitting'\r\n connection: UnidirectionalEmittingConnection\r\n}\r\nexport type UnidirectionalReceivingConnectionContext = {\r\n type: 'unidirectional-receiving'\r\n eventTarget: MessageEventTarget\r\n connection: UnidirectionalReceivingConnection\r\n}\r\n\r\nexport type ConnectionContext =\r\n | BidirectionalConnectionContext\r\n | UnidirectionalEmittingConnectionContext\r\n | UnidirectionalReceivingConnectionContext\r\n\r\nexport type ConnectionRevivableContext<TModules extends readonly RevivableModule[] = DefaultRevivableModules> = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n revivableModules: TModules\r\n eventTarget: MessageEventTarget\r\n}\r\n\r\nexport type BidirectionalConnection<T extends Capable = Capable> = {\r\n revivableContext: ConnectionRevivableContext\r\n close: () => void\r\n remoteValue: Promise<T>\r\n}\r\n\r\nexport const startBidirectionalConnection = <T extends Capable>(\r\n { transport, value, uuid, remoteUuid, platformCapabilities, eventTarget, send, close }:\r\n {\r\n transport: Transport\r\n value: Capable\r\n uuid: Uuid\r\n remoteUuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: MessageEventTarget\r\n send: (message: ConnectionMessage) => void\r\n close: () => void\r\n }\r\n) => {\r\n const revivableContext = {\r\n platformCapabilities,\r\n transport,\r\n remoteUuid,\r\n messagePorts: new Set(),\r\n messageChannels: makeMessageChannelAllocator(),\r\n sendMessage: send,\r\n eventTarget,\r\n revivableModules: defaultRevivableModules\r\n } satisfies ConnectionRevivableContext\r\n type InitMessageWithContext = { message: ConnectionMessage & { type: 'init' }, messageContext: MessageContext }\r\n let initResolve: ((data: InitMessageWithContext) => void)\r\n const initMessagePromise = new Promise<InitMessageWithContext>((resolve, reject) => {\r\n initResolve = resolve\r\n })\r\n\r\n eventTarget.addEventListener('message', ({ detail }) => {\r\n const { message, messageContext } = detail\r\n if (message.type === 'init') {\r\n initResolve({ message, messageContext })\r\n return\r\n } else if (message.type === 'message') {\r\n const messageChannel = revivableContext.messageChannels.getOrAlloc(message.portId)\r\n ;(messageChannel.port2 as MessagePort)?.postMessage(message)\r\n }\r\n })\r\n\r\n send({\r\n type: 'init',\r\n remoteUuid,\r\n data: recursiveBox(value, revivableContext) as Capable\r\n })\r\n\r\n return {\r\n revivableContext,\r\n close: () => {\r\n },\r\n remoteValue:\r\n initMessagePromise\r\n .then(({ message, messageContext }) =>\r\n recursiveRevive(message.data, { ...revivableContext, messageContext })\r\n ) as Promise<T>\r\n } satisfies BidirectionalConnection<T>\r\n}\r\n\r\nexport type UnidirectionalEmittingConnection<T extends Capable = Capable> = {\r\n close: () => void\r\n remoteValueProxy: T\r\n}\r\n\r\nexport const startUnidirectionalEmittingConnection = <T extends Capable>(\r\n { value, uuid, platformCapabilities, send, close }:\r\n {\r\n value: Capable\r\n uuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n send: (message: Message) => void\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n },\r\n remoteValueProxy: new Proxy(\r\n new Function(),\r\n {\r\n apply: (target, thisArg, args) => {\r\n },\r\n get: (target, prop) => {\r\n }\r\n }\r\n ) as T\r\n }\r\n}\r\n\r\nexport type UnidirectionalReceivingConnection = {\r\n close: () => void\r\n}\r\n\r\nexport const startUnidirectionalReceivingConnection = (\r\n { uuid, remoteUuid, platformCapabilities, close }:\r\n {\r\n uuid: Uuid\r\n remoteUuid?: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: StrictMessagePort<Message>\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n }\r\n }\r\n}\r\n","var e=class extends EventTarget{dispatchTypedEvent(s,t){return super.dispatchEvent(t)}};export{e as TypedEventTarget};\n","import type {\r\n EmitTransport, Message,\r\n MessageContext, MessageVariant,\r\n Capable, Transport,\r\n MessageEventTarget,\r\n MessageEventMap\r\n} from './types'\r\nexport type { UnderlyingType } from './revivables/utils'\r\nexport type { MessageContext } from './types'\r\nexport { OSRA_CONTEXT } from './revivables/context'\r\nimport type {\r\n PlatformCapabilities, ConnectionContext,\r\n BidirectionalConnectionContext\r\n} from './utils'\r\n\r\nimport { OSRA_DEFAULT_KEY, OSRA_KEY } from './types'\r\nexport { BoxBase } from './revivables/utils'\r\nimport {\r\n probePlatformCapabilities,\r\n registerOsraMessageListener,\r\n sendOsraMessage,\r\n startBidirectionalConnection,\r\n isReceiveTransport,\r\n isEmitTransport,\r\n startUnidirectionalEmittingConnection,\r\n getTransferableObjects,\r\n isJsonOnlyTransport,\r\n isCustomTransport\r\n} from './utils'\r\nimport { TypedEventTarget } from 'typescript-event-target'\r\n\r\n/**\r\n * Protocol mode:\r\n * - Bidirectional mode\r\n * - Unidirectional mode\r\n *\r\n * Transport modes:\r\n * - Capable mode\r\n * - Jsonable mode\r\n */\r\nexport const expose = async <T extends Capable>(\r\n value: Capable,\r\n {\r\n transport: _transport,\r\n name,\r\n remoteName,\r\n key = OSRA_DEFAULT_KEY,\r\n origin = '*',\r\n unregisterSignal,\r\n platformCapabilities: _platformCapabilities,\r\n transferAll,\r\n logger\r\n }: {\r\n transport: Transport\r\n name?: string\r\n remoteName?: string\r\n key?: string\r\n origin?: string\r\n unregisterSignal?: AbortSignal\r\n platformCapabilities?: PlatformCapabilities\r\n transferAll?: boolean\r\n logger?: {}\r\n }\r\n): Promise<T> => {\r\n const transport = {\r\n isJson:\r\n 'isJson' in _transport && _transport.isJson !== undefined\r\n ? _transport.isJson\r\n : isJsonOnlyTransport(_transport),\r\n ...(\r\n isCustomTransport(_transport)\r\n ? _transport\r\n : {\r\n emit: _transport,\r\n receive: _transport\r\n }\r\n )\r\n } satisfies Transport\r\n const platformCapabilities = _platformCapabilities ?? await probePlatformCapabilities()\r\n const connectionContexts = new Map<string, ConnectionContext>()\r\n\r\n let resolveRemoteValue: (connection: T) => void\r\n const remoteValuePromise = new Promise<T>((resolve) => {\r\n resolveRemoteValue = resolve\r\n })\r\n\r\n let uuid = globalThis.crypto.randomUUID()\r\n \r\n \r\n let aborted = false\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () => {\r\n aborted = true\r\n })\r\n }\r\n\r\n const sendMessage = (transport: EmitTransport, message: MessageVariant) => {\r\n if (aborted) return\r\n const transferables = getTransferableObjects(message)\r\n sendOsraMessage(\r\n transport,\r\n {\r\n [OSRA_KEY]: key,\r\n name,\r\n uuid,\r\n ...message\r\n },\r\n origin,\r\n transferables\r\n )\r\n }\r\n\r\n const listener = async (message: Message, messageContext: MessageContext) => {\r\n // means that our own message looped back on the channel\r\n if (message.uuid === uuid) return\r\n // Unidirectional receiving mode\r\n if (!isEmitTransport(transport)) {\r\n // Handle non bidirectional based messages here\r\n throw new Error('Unidirectional receiving mode not implemented')\r\n }\r\n // Bidirectional mode\r\n if (message.type === 'announce') {\r\n if (!message.remoteUuid) {\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n return\r\n }\r\n if (message.remoteUuid !== uuid) return\r\n // todo: re-add uuid collision handling\r\n if (connectionContexts.has(message.uuid)) {\r\n return\r\n }\r\n // Send announce back so the other side can also create a connection\r\n // (in case they missed our initial announce due to timing)\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n const eventTarget = new TypedEventTarget<MessageEventMap>()\r\n const connectionContext = {\r\n type: 'bidirectional',\r\n eventTarget,\r\n connection:\r\n startBidirectionalConnection({\r\n transport,\r\n value,\r\n uuid,\r\n remoteUuid: message.uuid,\r\n platformCapabilities,\r\n eventTarget,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => void connectionContexts.delete(message.uuid)\r\n })\r\n } satisfies BidirectionalConnectionContext\r\n connectionContexts.set(message.uuid, connectionContext)\r\n connectionContext.connection.remoteValue.then((remoteValue) =>\r\n resolveRemoteValue(remoteValue as T)\r\n )\r\n } else if (message.type === 'reject-uuid-taken') {\r\n if (message.remoteUuid !== uuid) return\r\n uuid = globalThis.crypto.randomUUID()\r\n sendMessage(transport, { type: 'announce' })\r\n } else if (message.type === 'close') {\r\n if (message.remoteUuid !== uuid) return\r\n const connectionContext = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connectionContext) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n connectionContext.connection.close()\r\n connectionContexts.delete(message.uuid)\r\n } else { // \"init\" | \"message\" | \"message-port-close\"\r\n if (message.remoteUuid !== uuid) return\r\n const connection = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connection) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n if (connection.type !== 'unidirectional-emitting') {\r\n connection.eventTarget.dispatchTypedEvent(\r\n 'message',\r\n new CustomEvent('message', { detail: { message, messageContext } })\r\n )\r\n }\r\n }\r\n }\r\n\r\n if (isReceiveTransport(transport)) {\r\n registerOsraMessageListener({\r\n listener,\r\n transport,\r\n remoteName,\r\n key,\r\n unregisterSignal\r\n })\r\n }\r\n\r\n if (isEmitTransport(transport)) {\r\n sendMessage(transport, { type: 'announce' })\r\n }\r\n\r\n // Unidirectional emitting mode\r\n if (isEmitTransport(transport) && !isReceiveTransport(transport)) {\r\n const { remoteValueProxy } = startUnidirectionalEmittingConnection<T>({\r\n value,\r\n uuid,\r\n platformCapabilities,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => connectionContexts.delete(uuid)\r\n })\r\n return remoteValueProxy\r\n }\r\n\r\n return remoteValuePromise\r\n}\r\n"],"names":["OSRA_KEY","OSRA_DEFAULT_KEY","OSRA_BOX","BoxBase","isRevivableBox","value","_context","type","OSRA_CONTEXT_MARKER","OSRA_CONTEXT","isType","box","_value","revive","context","makeMessageChannelAllocator","channels","result","uuid","messagePorts","allocatedMessageChannel","messageChannel","existingChannel","checkOsraMessageKey","message","key","isOsraMessage","registerOsraMessageListener","listener","transport","remoteName","unregisterSignal","registerListenerOnReceiveTransport","receiveTransport","isWebExtensionPort","isWebExtensionOnConnect","isWebExtensionOnMessage","listenOnWebExtOnMessage","onMessage","port","_listener","sender","messageListener","event","isCustomTransport","sendOsraMessage","origin","transferables","sendToEmitTransport","emitTransport","isWindow","isWebSocket","isSharedWorker","isServiceWorkerContainer","isWorker","isDedicatedWorker","isMessagePort","isClonable","isTransferable","connectPort","w","isEmitJsonOnlyTransport","isReceiveJsonOnlyTransport","isJsonOnlyTransport","isEmitTransport","isCustomEmitTransport","isReceiveTransport","isCustomReceiveTransport","getTransferableObjects","recurse","probePlatformCapabilityUtil","transfer","port1","port2","resolve","probeMessagePortTransfer","probeArrayBufferClone","buffer","probeArrayBufferTransfer","probeTransferableStream","stream","controller","probePlatformCapabilities","messagePort","arrayBuffer","transferable","transferableStream","typedArrayConstructors","typedArrayToType","typedArrayTypeToTypedArrayConstructor","typedArray","constructor","TypedArrayConstructor","messagePortRegistry","info","isAlreadyBoxed","messagePortListener","data","recursiveBox","portId","messagePortRef","eventTargetListener","detail","internalPortListener","userPort","internalPort","userPortRef","performCleanup","port1Listener","revivedData","recursiveRevive","allocatedChannel","promise","localPort","remotePort","sendResult","boxedResult","error","boxMessagePort","reviveMessagePort","reject","functionRegistry","cleanup","returnValuePort","args","func","returnValueLocalPort","returnValueRemotePort","callContext","reader","pullResult","_controller","defaultRevivableModules","date","headers","readableStream","handledByModule","module","startBidirectionalConnection","remoteUuid","platformCapabilities","eventTarget","send","close","revivableContext","initResolve","initMessagePromise","messageContext","startUnidirectionalEmittingConnection","target","thisArg","prop","e","s","expose","_transport","name","_platformCapabilities","transferAll","logger","connectionContexts","resolveRemoteValue","remoteValuePromise","aborted","sendMessage","TypedEventTarget","connectionContext","remoteValue","connection","remoteValueProxy"],"mappings":"AAKO,MAAMA,IAAW,gBACXC,KAAmB,wBACnBC,IAAW,gBCEXC,IAAU;AAAA,EACrB,CAACD,CAAQ,GAAG;AAAA,EACZ,MAAM;AACR,GA6BaE,KAAiB,CAA6BC,GAAYC,MACrED,KACG,OAAOA,KAAU,YACjBH,KAAYG,KACZA,EAAMH,CAAQ,MAAM,aCxCZK,IAAO,WAKdC,IAAsB,OAAO,IAAI,cAAc,GAQxCC,KAA+B,EAAE,CAACD,CAAmB,GAAG,GAAA,GAExDE,KAAS,CAACL,MACrBA,MAAU,QACV,OAAOA,KAAU,YACjBG,KAAuBH,GAEZM,KAAM,CACjBC,GACAN,OACI;AAAA,EACJ,GAAGH;AAAA,EAAA,MACHI;AACF,IAEaM,KAAS,CACpBD,GACAE,MAEOA,EAAQ,kBAAkB,CAAA;;;;;;;8CCWtBC,KAA8B,MAAM;AAC/C,QAAMC,wBAAe,IAAA,GAEfC,IAAS;AAAA,IACb,eAAe,MAAM;AACnB,UAAIC,IAAa,WAAW,OAAO,WAAA;AACnC,aAAOF,EAAS,IAAIE,CAAI;AACtB,QAAAA,IAAO,WAAW,OAAO,WAAA;AAE3B,aAAOA;AAAA,IACT;AAAA,IACA,KAAK,CAACA,GAAYC,MAA0E;AAC1F,MAAAH,EAAS,IAAIE,GAAM,EAAE,MAAA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,GAAWL,CAAO;AAAA,MACjE,OAAO,MAAMwI,EAAmB,OAAO9I,CAAI;AAAA,IAAA,CAC5C;AACD,WAAOuJ;AAAA,EACT;AAEA,SAAOP;AACT;","x_google_ignoreList":[19]}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/types.ts","../src/revivables/utils.ts","../src/revivables/context.ts","../src/utils/allocator.ts","../src/utils/platform.ts","../src/utils/type-guards.ts","../src/utils/transferable.ts","../src/utils/capabilities.ts","../src/revivables/array-buffer.ts","../src/revivables/date.ts","../src/revivables/headers.ts","../src/revivables/error.ts","../src/revivables/typed-array.ts","../src/revivables/message-port.ts","../src/revivables/promise.ts","../src/revivables/function.ts","../src/revivables/readable-stream.ts","../src/revivables/index.ts","../src/utils/connection.ts","../node_modules/typescript-event-target/dist/index.mjs","../src/index.ts"],"sourcesContent":["import { TypedEventTarget } from 'typescript-event-target'\r\nimport type { TypedArray, WebExtOnConnect, WebExtOnMessage, WebExtPort, WebExtRuntime, WebExtSender } from './utils/type-guards'\r\nimport { DefaultRevivableModule, DefaultRevivableModules, RevivableModule } from './revivables'\r\nimport { InferRevivables } from './revivables/utils'\r\n\r\nexport const OSRA_KEY = '__OSRA_KEY__' as const\r\nexport const OSRA_DEFAULT_KEY = '__OSRA_DEFAULT_KEY__' as const\r\nexport const OSRA_BOX = '__OSRA_BOX__' as const\r\n\r\nexport type Uuid = `${string}-${string}-${string}-${string}-${string}`\r\n\r\nexport type Jsonable =\r\n | boolean\r\n | null\r\n | number\r\n | string\r\n | { [key: string]: Jsonable }\r\n | Array<Jsonable>\r\n\r\nexport type Structurable =\r\n | Jsonable\r\n /** not really structureable but here for convenience */\r\n | void\r\n | undefined\r\n | BigInt\r\n | Date\r\n | RegExp\r\n | Blob\r\n | File\r\n | FileList\r\n | ArrayBuffer\r\n | ArrayBufferView\r\n | ImageBitmap\r\n | ImageData\r\n | { [key: string]: Structurable }\r\n | Array<Structurable>\r\n | Map<Structurable, Structurable>\r\n | Set<Structurable>\r\n \r\nexport type StructurableTransferable =\r\n | Structurable\r\n | Transferable\r\n | { [key: string]: StructurableTransferable }\r\n | Array<StructurableTransferable>\r\n | Map<StructurableTransferable, StructurableTransferable>\r\n | Set<StructurableTransferable>\r\n\r\nexport type Capable<TModules extends readonly RevivableModule[] = DefaultRevivableModules> =\r\n | StructurableTransferable\r\n | InferRevivables<TModules>\r\n | { [key: string]: Capable }\r\n | Array<Capable>\r\n | Map<Capable, Capable>\r\n | Set<Capable>\r\n\r\nexport type MessageBase = {\r\n [OSRA_KEY]: string\r\n /** UUID of the client that sent the message */\r\n uuid: Uuid\r\n name?: string\r\n}\r\n\r\nexport type ProtocolMessage =\r\n | {\r\n type: 'announce'\r\n /** Only set when acknowledging a remote announcement */\r\n remoteUuid?: Uuid\r\n }\r\n | {\r\n /** uuid already taken, try announcing with another one */\r\n type: 'reject-uuid-taken'\r\n remoteUuid: Uuid\r\n }\r\n | {\r\n type: 'close'\r\n remoteUuid: Uuid\r\n }\r\n\r\nexport type BidirectionalConnectionMessage =\r\n | {\r\n type: 'init'\r\n remoteUuid: Uuid\r\n data: Capable\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n /** uuid of the messagePort that the message was sent through */\r\n portId: Uuid\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message-port-close'\r\n remoteUuid: Uuid\r\n /** uuid of the messagePort that closed */\r\n portId: string\r\n }\r\n\r\nexport type UnidirectionalConnectionMessage = {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n portId: Uuid\r\n}\r\n\r\nexport type ConnectionMessage =\r\n | BidirectionalConnectionMessage\r\n | UnidirectionalConnectionMessage\r\n\r\nexport type MessageVariant =\r\n | ProtocolMessage\r\n | ConnectionMessage\r\n\r\nexport type Message =\r\n | MessageBase\r\n & MessageVariant\r\n\r\nexport type MessageContext = {\r\n port?: MessagePort | WebExtPort // WebExtension\r\n sender?: WebExtSender // WebExtension\r\n receiveTransport?: ReceivePlatformTransport\r\n source?: MessageEventSource | null // Window, Worker, WebSocket, ect...\r\n}\r\n\r\nexport type MessageEventDetail = {\r\n message: Message\r\n messageContext: MessageContext\r\n}\r\n\r\nexport type MessageEventMap = {\r\n message: CustomEvent<MessageEventDetail>\r\n}\r\nexport type MessageEventTarget = TypedEventTarget<MessageEventMap>\r\n\r\nexport type CustomTransport =\r\n { isJson?: boolean }\r\n & (\r\n | {\r\n receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void)\r\n emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void)\r\n }\r\n | { receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void) }\r\n | { emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void) }\r\n )\r\n\r\nexport type CustomEmitTransport = Extract<CustomTransport, { emit: any }>\r\nexport type CustomReceiveTransport = Extract<CustomTransport, { receive: any }>\r\n\r\nexport type EmitJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n\r\nexport type ReceiveJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n | WebExtOnConnect\r\n | WebExtOnMessage\r\n\r\nexport type JsonPlatformTransport =\r\n | { isJson: true }\r\n | EmitJsonPlatformTransport\r\n | ReceiveJsonPlatformTransport\r\n\r\nexport type EmitPlatformTransport =\r\n | EmitJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type ReceivePlatformTransport =\r\n | ReceiveJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type PlatformTransport =\r\n | EmitPlatformTransport\r\n | ReceivePlatformTransport\r\n\r\nexport type EmitTransport = EmitPlatformTransport & Extract<CustomTransport, { emit: any }>\r\nexport type ReceiveTransport = ReceivePlatformTransport & Extract<CustomTransport, { receive: any }>\r\n\r\nexport type Transport =\r\n | PlatformTransport\r\n | CustomTransport\r\n","import type { DefaultRevivableModules, RevivableModule } from '.'\r\nimport type { ConnectionMessage, MessageContext, MessageEventTarget, Transport, Uuid } from '../types'\r\nimport type { MessageChannelAllocator, PlatformCapabilities } from '../utils'\r\n\r\nimport { OSRA_BOX } from '../types'\r\n\r\nexport declare const UnderlyingType: unique symbol\r\nexport type UnderlyingType = typeof UnderlyingType\r\n\r\nexport const BoxBase = {\r\n [OSRA_BOX]: 'revivable',\r\n type: '' as string\r\n} as const\r\n\r\nexport type BoxBase<T extends string = string> =\r\n & typeof BoxBase\r\n & { type: T }\r\n\r\nexport type RevivableContext<TModules extends readonly RevivableModule[] = DefaultRevivableModules> = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n revivableModules: TModules\r\n eventTarget: MessageEventTarget\r\n /** MessageContext of the message being revived, used by OSRA_CONTEXT revivable */\r\n messageContext?: MessageContext\r\n}\r\n\r\nexport type ExtractModule<T> = T extends { isType: (value: unknown) => value is infer S } ? S : never\r\nexport type ExtractType<T> = T extends { isType: (value: unknown) => value is infer S } ? S : never\r\nexport type ExtractBoxInput<T> = T extends { box: (value: infer S) => value is any } ? S : never\r\nexport type ExtractReviveInput<T> = T extends { revive: (value: infer S) => value is any } ? S : never\r\nexport type ExtractBox<T> = T extends { box: (...args: any[]) => infer B } ? B : never\r\nexport type InferRevivables<TModules extends readonly unknown[]> =\r\n ExtractType<TModules[number]>\r\nexport type InferRevivableBox<TModules extends readonly unknown[]> =\r\n ExtractBox<TModules[number]>\r\n\r\nexport const isRevivableBox = <T extends RevivableContext>(value: any, _context: T): value is InferRevivableBox<T['revivableModules']> =>\r\n value\r\n && typeof value === 'object'\r\n && OSRA_BOX in value\r\n && value[OSRA_BOX] === 'revivable'\r\n","import type { MessageContext } from '../types'\r\nimport type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'context' as const\r\n\r\n/**\r\n * Internal symbol used to identify OSRA_CONTEXT objects at runtime.\r\n */\r\nconst OSRA_CONTEXT_MARKER = Symbol.for('OSRA_CONTEXT')\r\n\r\n/**\r\n * A special token that gets transformed into the MessageContext when revived on the receiving side.\r\n * Pass this value in your exposed API to receive information about the message context.\r\n *\r\n * Typed as MessageContext so it can be passed directly where MessageContext is expected.\r\n */\r\nexport const OSRA_CONTEXT: MessageContext = { [OSRA_CONTEXT_MARKER]: true } as MessageContext\r\n\r\nexport const isType = (value: unknown): value is MessageContext =>\r\n value !== null &&\r\n typeof value === 'object' &&\r\n OSRA_CONTEXT_MARKER in value\r\n\r\nexport const box = <T extends MessageContext, T2 extends RevivableContext>(\r\n _value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n _value: T,\r\n context: T2\r\n): MessageContext => {\r\n return context.messageContext ?? {}\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(OSRA_CONTEXT, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: MessageContext = revived\r\n // @ts-expect-error - not a MessageContext\r\n const notContext: string = revived\r\n}\r\n","import type { StructurableTransferable, Uuid } from '../types'\r\nimport type { StrictMessageChannel, StrictMessagePort } from './message-channel'\r\n\r\nexport const makeAllocator = <T>() => {\r\n const channels = new Map<string, T>()\r\n\r\n const alloc = (value: T): string => {\r\n let uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n channels.set(uuid, value)\r\n return uuid\r\n }\r\n\r\n const has = (uuid: string) => channels.has(uuid)\r\n const get = (uuid: string) => channels.get(uuid)\r\n\r\n const free = (uuid: string) => {\r\n channels.delete(uuid)\r\n }\r\n\r\n const set = (uuid: string, value: T) => {\r\n channels.set(uuid, value)\r\n }\r\n\r\n return {\r\n alloc,\r\n has,\r\n get,\r\n free,\r\n set\r\n }\r\n}\r\n\r\nexport type Allocator<T> = ReturnType<typeof makeAllocator<T>>\r\n\r\ntype AllocatedMessageChannel<\r\n T extends StructurableTransferable = StructurableTransferable,\r\n T2 extends StructurableTransferable = StructurableTransferable\r\n> = {\r\n uuid: Uuid\r\n /** Local port */\r\n port1: StrictMessagePort<T>\r\n /** Remote port that gets transferred, might be undefined if a remote context created the channel */\r\n port2?: StrictMessagePort<T2>\r\n}\r\n\r\nexport const makeMessageChannelAllocator = () => {\r\n const channels = new Map<string, AllocatedMessageChannel>()\r\n\r\n const result = {\r\n getUniqueUuid: () => {\r\n let uuid: Uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n return uuid\r\n },\r\n set: (uuid: Uuid, messagePorts: { port1: StrictMessagePort, port2?: StrictMessagePort }) => {\r\n channels.set(uuid, { uuid, ...messagePorts })\r\n },\r\n alloc: (\r\n uuid: Uuid | undefined = result.getUniqueUuid(),\r\n messagePorts?: { port1: StrictMessagePort, port2?: StrictMessagePort }\r\n ) => {\r\n if (messagePorts) {\r\n const allocatedMessageChannel = { uuid, ...messagePorts } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n }\r\n const messageChannel = new MessageChannel() as StrictMessageChannel\r\n const allocatedMessageChannel = {\r\n uuid,\r\n port1: messageChannel.port1,\r\n port2: messageChannel.port2\r\n } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n },\r\n has: (uuid: string) => channels.has(uuid),\r\n get: (uuid: string) => channels.get(uuid),\r\n free: (uuid: string) => channels.delete(uuid),\r\n getOrAlloc: (\r\n uuid: Uuid | undefined = result.getUniqueUuid(),\r\n messagePorts?: { port1: StrictMessagePort, port2?: StrictMessagePort }\r\n ) => {\r\n const existingChannel = result.get(uuid)\r\n if (existingChannel) return existingChannel!\r\n return result.alloc(uuid, messagePorts)\r\n }\r\n }\r\n return result\r\n}\r\n\r\nexport type MessageChannelAllocator = ReturnType<typeof makeMessageChannelAllocator>\r\n","import type {\r\n CustomTransport, EmitTransport,\r\n Message, MessageContext,\r\n ReceiveTransport\r\n} from '../types'\r\nimport type { WebExtOnMessage, WebExtPort, WebExtSender } from './type-guards'\r\n\r\nimport { OSRA_KEY } from '../types'\r\nimport {\r\n isOsraMessage, isCustomTransport,\r\n isWebExtensionOnConnect, isWebExtensionOnMessage,\r\n isWebExtensionPort, isWebSocket, isWindow, isSharedWorker\r\n} from './type-guards'\r\n\r\nexport const getWebExtensionGlobal = () => globalThis.browser ?? globalThis.chrome\r\nexport const getWebExtensionRuntime = () => getWebExtensionGlobal().runtime\r\n\r\nexport const checkOsraMessageKey = (message: any, key: string): message is Message =>\r\n isOsraMessage(message)\r\n && message[OSRA_KEY] === key\r\n\r\nexport const registerOsraMessageListener = (\r\n { listener, transport, remoteName, key = OSRA_KEY, unregisterSignal }:\r\n {\r\n listener: (message: Message, messageContext: MessageContext) => Promise<void>\r\n transport: ReceiveTransport\r\n remoteName?: string\r\n key?: string\r\n unregisterSignal?: AbortSignal\r\n }\r\n) => {\r\n const registerListenerOnReceiveTransport = (receiveTransport: Extract<CustomTransport, { receive: any }>['receive']) => {\r\n // Custom function handler\r\n if (typeof receiveTransport === 'function') {\r\n receiveTransport(listener)\r\n // WebExtension handler\r\n } else if (\r\n isWebExtensionPort(receiveTransport)\r\n || isWebExtensionOnConnect(receiveTransport)\r\n || isWebExtensionOnMessage(receiveTransport)\r\n ) {\r\n const listenOnWebExtOnMessage = (onMessage: WebExtOnMessage, port?: WebExtPort) => {\r\n const _listener = (message: object, sender?: WebExtSender) => {\r\n if (!checkOsraMessageKey(message, key)) return\r\n if (remoteName && message.name !== remoteName) return\r\n listener(message, { port, sender })\r\n }\r\n onMessage.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n onMessage.removeListener(_listener)\r\n )\r\n }\r\n }\r\n\r\n // WebExtOnConnect\r\n if (isWebExtensionOnConnect(receiveTransport)) {\r\n const _listener = (port: WebExtPort) => {\r\n listenOnWebExtOnMessage(port.onMessage as WebExtOnMessage, port)\r\n }\r\n receiveTransport.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeListener(_listener)\r\n )\r\n }\r\n // WebExtOnMessage\r\n } else if (isWebExtensionOnMessage(receiveTransport)) {\r\n listenOnWebExtOnMessage(receiveTransport)\r\n } else { // WebExtPort\r\n listenOnWebExtOnMessage(receiveTransport.onMessage as WebExtOnMessage)\r\n }\r\n } else { // Window, Worker, WebSocket, ect...\r\n const messageListener = (event: MessageEvent<Message>) => {\r\n if (!checkOsraMessageKey(event.data, key)) return\r\n if (remoteName && event.data.name !== remoteName) return\r\n listener(event.data, { receiveTransport, source: event.source })\r\n }\r\n receiveTransport.addEventListener('message', messageListener as EventListener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeEventListener('message', messageListener as EventListener)\r\n )\r\n }\r\n }\r\n }\r\n if (isCustomTransport(transport)) {\r\n registerListenerOnReceiveTransport(transport.receive)\r\n } else {\r\n registerListenerOnReceiveTransport(transport)\r\n }\r\n}\r\n\r\nexport const sendOsraMessage = (\r\n transport: EmitTransport,\r\n message: Message,\r\n origin = '*',\r\n transferables: Transferable[] = []\r\n) => {\r\n const sendToEmitTransport = (emitTransport: Extract<EmitTransport, { emit: any }>['emit']) => {\r\n if (typeof emitTransport === 'function') {\r\n emitTransport(message, transferables)\r\n } else if (isWebExtensionPort(emitTransport)) {\r\n emitTransport.postMessage(message)\r\n } else if (isWindow(emitTransport)) {\r\n emitTransport.postMessage(message, origin, transferables)\r\n } else if (isWebSocket(emitTransport)) {\r\n emitTransport.send(JSON.stringify(message))\r\n } else if (isSharedWorker(emitTransport)) {\r\n emitTransport.port.postMessage(message, transferables)\r\n } else { // MessagePort | ServiceWorker | Worker\r\n emitTransport.postMessage(message, transferables)\r\n }\r\n }\r\n\r\n if (isCustomTransport(transport)) {\r\n sendToEmitTransport(transport.emit)\r\n } else {\r\n sendToEmitTransport(transport)\r\n }\r\n}\r\n","import type { Runtime } from 'webextension-polyfill'\r\nimport type {\r\n CustomEmitTransport, CustomReceiveTransport,\r\n CustomTransport, EmitJsonPlatformTransport,\r\n EmitTransport, JsonPlatformTransport,\r\n Message, ReceiveJsonPlatformTransport,\r\n ReceiveTransport, Transport\r\n} from '../types'\r\n\r\nimport { OSRA_BOX, OSRA_KEY } from '../types'\r\nimport { getWebExtensionRuntime } from './platform'\r\n\r\nexport type TransferBox<T extends Transferable = Transferable> = {\r\n [OSRA_BOX]: 'transferable'\r\n value: T\r\n}\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypeArrayType = ReturnType<typeof typedArrayToType>\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypeArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isTypedArray = (value: any): value is TypedArray => typedArrayConstructors.some(typedArray => value instanceof typedArray)\r\nexport const isWebSocket = (value: any) => value instanceof WebSocket\r\nexport const isServiceWorkerContainer = (value: any): value is ServiceWorkerContainer => globalThis.ServiceWorkerContainer && value instanceof ServiceWorkerContainer\r\nexport const isWorker = (value: any): value is Worker => globalThis.Worker && value instanceof Worker\r\n// @ts-expect-error\r\nexport const isDedicatedWorker = (value: any): value is DedicatedWorkerGlobalScope => globalThis.DedicatedWorkerGlobalScope && value instanceof DedicatedWorkerGlobalScope\r\nexport const isSharedWorker = (value: any): value is SharedWorker => globalThis.SharedWorker && value instanceof SharedWorker\r\nexport const isMessagePort = (value: any) => value instanceof MessagePort\r\nexport const isPromise = (value: any) => value instanceof Promise\r\nexport const isFunction = (value: any): value is Function => typeof value === 'function'\r\nexport const isArrayBuffer = (value: any) => value instanceof ArrayBuffer\r\nexport const isReadableStream = (value: any) => value instanceof ReadableStream\r\nexport const isDate = (value: any) => value instanceof Date\r\nexport const isError = (value: any) => value instanceof Error\r\n\r\nexport const isAlwaysBox = (value: any): value is Function | Promise<any> | Date | Error =>\r\n isFunction(value)\r\n || isPromise(value)\r\n || isTypedArray(value)\r\n || isDate(value)\r\n || isError(value)\r\n\r\nexport const isOsraMessage = (value: any): value is Message =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as Message)[OSRA_KEY]\r\n )\r\n\r\nexport const isClonable = (value: any) =>\r\n globalThis.SharedArrayBuffer && value instanceof globalThis.SharedArrayBuffer ? true\r\n : false\r\n\r\nexport const isTransferable = (value: any): value is Transferable =>\r\n globalThis.ArrayBuffer && value instanceof globalThis.ArrayBuffer ? true\r\n : globalThis.MessagePort && value instanceof globalThis.MessagePort ? true\r\n : globalThis.ReadableStream && value instanceof globalThis.ReadableStream ? true\r\n : globalThis.WritableStream && value instanceof globalThis.WritableStream ? true\r\n : globalThis.TransformStream && value instanceof globalThis.TransformStream ? true\r\n : globalThis.ImageBitmap && value instanceof globalThis.ImageBitmap ? true\r\n : false\r\n\r\nexport const isTransferBox = (value: any): value is TransferBox<any> =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as TransferBox<Transferable>)[OSRA_BOX] === 'transferable'\r\n )\r\n\r\nexport type WebExtRuntime = typeof browser.runtime\r\nexport const isWebExtensionRuntime = (value: any): value is WebExtRuntime => {\r\n const runtime = getWebExtensionRuntime()\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && isWebExtensionOnConnect(runtime.onConnect)\r\n && runtime.id\r\n )\r\n}\r\n\r\nexport type WebExtPort = ReturnType<WebExtRuntime['connect']> | Runtime.Port\r\nexport const isWebExtensionPort = (value: any, connectPort: boolean = false): value is WebExtPort => {\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && ('name' in (value as WebExtPort))\r\n && ('disconnect' in (value as WebExtPort))\r\n && ('postMessage' in (value as WebExtPort))\r\n && (\r\n connectPort\r\n // these properties are only present on WebExtPort that were created through runtime.connect()\r\n ? (\r\n ('sender' in (value as WebExtPort))\r\n && ('onMessage' in (value as WebExtPort))\r\n && ('onDisconnect' in (value as WebExtPort))\r\n )\r\n : true\r\n )\r\n )\r\n}\r\n\r\nexport type WebExtSender = NonNullable<WebExtPort['sender']>\r\n\r\nexport type WebExtOnConnect = WebExtRuntime['onConnect']\r\nexport const isWebExtensionOnConnect = (value: any): value is WebExtOnConnect =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (value as WebExtOnConnect).addListener\r\n && (value as WebExtOnConnect).hasListener\r\n && (value as WebExtOnConnect).removeListener\r\n )\r\n\r\nexport type WebExtOnMessage = WebExtRuntime['onMessage']\r\nexport const isWebExtensionOnMessage = (value: any): value is WebExtOnMessage =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (value as WebExtOnMessage).addListener\r\n && (value as WebExtOnMessage).hasListener\r\n && (value as WebExtOnMessage).removeListener\r\n )\r\n\r\nexport const isWindow = (value: unknown): value is Window => {\r\n if (!value || typeof value !== 'object') return false\r\n\r\n try {\r\n return (value as Window).window === value\r\n } catch {\r\n try {\r\n const w = value as Window\r\n return typeof w.closed === 'boolean' && typeof w.close === 'function'\r\n } catch {\r\n return false\r\n }\r\n }\r\n }\r\n\r\nexport type IsEmitJsonOnlyTransport<T extends Transport> = T extends EmitJsonPlatformTransport ? true : false\r\nexport const isEmitJsonOnlyTransport = (value: any): value is EmitJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n\r\nexport type IsReceiveJsonOnlyTransport<T extends Transport> = T extends ReceiveJsonPlatformTransport ? true : false\r\nexport const isReceiveJsonOnlyTransport = (value: any): value is ReceiveJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n || isWebExtensionOnConnect(value)\r\n || isWebExtensionOnMessage(value)\r\n\r\nexport type IsJsonOnlyTransport<T extends Transport> = T extends JsonPlatformTransport ? true : false\r\nexport const isJsonOnlyTransport = (value: Transport): value is Extract<Transport, JsonPlatformTransport> =>\r\n ('isJson' in value && value.isJson === true)\r\n || isEmitJsonOnlyTransport(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n\r\nexport type IsEmitTransport<T extends Transport> = T extends EmitTransport ? true : false\r\nexport const isEmitTransport = (value: any): value is EmitTransport =>\r\n isWindow(value)\r\n || isEmitJsonOnlyTransport(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomEmitTransport(value)\r\n\r\nexport function assertEmitTransport (transport: Transport): asserts transport is EmitTransport {\r\n if (!isEmitTransport(transport)) throw new Error('Transport is not emitable')\r\n}\r\n\r\n\r\nexport type IsReceiveTransport<T extends Transport> = T extends ReceiveTransport ? true : false\r\nexport const isReceiveTransport = (value: any): value is ReceiveTransport =>\r\n isWindow(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport function assertReceiveTransport (transport: Transport): asserts transport is ReceiveTransport {\r\n if (!isReceiveTransport(transport)) throw new Error('Transport is not receiveable')\r\n}\r\n\r\nexport const isCustomEmitTransport = (value: any): value is CustomEmitTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (\r\n 'emit' in value\r\n && (\r\n isEmitTransport(value.emit)\r\n || typeof value.emit === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport const isCustomReceiveTransport = (value: any): value is CustomReceiveTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (\r\n 'receive' in value\r\n && (\r\n isReceiveTransport(value.receive)\r\n || typeof value.receive === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport type IsCustomTransport<T extends Transport> = T extends CustomTransport ? true : false\r\nexport const isCustomTransport = (value: any): value is CustomTransport =>\r\n isCustomEmitTransport(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport const isTransport = (value: any): value is Transport =>\r\n isEmitTransport(value)\r\n || isReceiveTransport(value)\r\n || isCustomTransport(value)\r\n || isJsonOnlyTransport(value)\r\n","import type { Capable } from '../types'\r\nimport type { TransferBox } from './type-guards'\r\n\r\nimport { OSRA_BOX } from '../types'\r\nimport { deepReplace } from './replace'\r\nimport { isClonable, isTransferable, isTransferBox } from './type-guards'\r\n\r\nexport const getTransferableObjects = (value: any): Transferable[] => {\r\n const transferables: Transferable[] = []\r\n const recurse = (value: any): any =>\r\n isClonable(value) ? undefined\r\n : isTransferable(value) ? transferables.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferables\r\n}\r\n\r\nexport const getTransferBoxes = (value: any): TransferBox<Transferable>[] => {\r\n const transferBoxes: TransferBox<any>[] = []\r\n const recurse = (value: any): any =>\r\n isTransferBox(value) ? transferBoxes.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferBoxes\r\n}\r\n\r\n/** This box tells the protocol that the value should be copied instead of transfered */\r\nexport const transfer = <T extends Transferable>(value: T) => ({\r\n [OSRA_BOX]: 'transferable',\r\n value\r\n}) as TransferBox<T>\r\n\r\nexport const recursiveTransfer = <T extends Capable>(value: T) =>\r\n deepReplace(\r\n value,\r\n isTransferable,\r\n (value) => transfer(value)\r\n )\r\n","import { getTransferableObjects } from './transferable'\r\n\r\nexport type PlatformCapabilities = {\r\n jsonOnly: boolean\r\n messagePort: boolean\r\n arrayBuffer: boolean\r\n transferable: boolean\r\n transferableStream: boolean\r\n}\r\n\r\nconst probePlatformCapabilityUtil = <T>(value: T, transfer = false): Promise<T> => {\r\n const { port1, port2 } = new MessageChannel()\r\n const result = new Promise<T>(resolve =>\r\n port1.addEventListener('message', message =>\r\n resolve(message.data)\r\n )\r\n )\r\n port1.start()\r\n port2.postMessage(value, transfer ? getTransferableObjects(value) : [])\r\n return result\r\n}\r\n\r\nconst probeMessagePortTransfer = async () => {\r\n const { port1 } = new MessageChannel()\r\n const port = await probePlatformCapabilityUtil(port1, true)\r\n return port instanceof MessagePort\r\n}\r\n\r\nconst probeArrayBufferClone = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeArrayBufferTransfer = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer, true)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeTransferableStream = async () => {\r\n const stream = new ReadableStream({\r\n start(controller) {\r\n controller.enqueue(new Uint8Array(1))\r\n controller.close()\r\n }\r\n })\r\n const transferableStream = await probePlatformCapabilityUtil(stream, true)\r\n return transferableStream instanceof ReadableStream\r\n}\r\n\r\nexport const probePlatformCapabilities = async (): Promise<PlatformCapabilities> => {\r\n const [\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n ] = await Promise.all([\r\n probeMessagePortTransfer().catch(() => false),\r\n probeArrayBufferClone().catch(() => false),\r\n probeArrayBufferTransfer().catch(() => false),\r\n probeTransferableStream().catch(() => false)\r\n ])\r\n return {\r\n jsonOnly:\r\n !messagePort\r\n && !arrayBuffer\r\n && !transferable\r\n && !transferableStream,\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n }\r\n}\r\n","import type { IsJsonOnlyTransport } from '../utils'\r\nimport type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { isJsonOnlyTransport } from '../utils'\r\n\r\nexport const type = 'arrayBuffer' as const\r\n\r\nexport const isType = (value: unknown): value is ArrayBuffer =>\r\n value instanceof ArrayBuffer\r\n\r\nexport const box = <T extends ArrayBuffer, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n ...(\r\n isJsonOnlyTransport(_context.transport)\r\n ? { base64Buffer: new Uint8Array(value).toBase64() }\r\n : { arrayBuffer: value }\r\n ) as (\r\n IsJsonOnlyTransport<T2['transport']> extends true ? { base64Buffer: string }\r\n : IsJsonOnlyTransport<T2['transport']> extends false ? { arrayBuffer: ArrayBuffer }\r\n : { base64Buffer: string } | { arrayBuffer: ArrayBuffer }\r\n )\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) =>\r\n 'arrayBuffer' in value ? value.arrayBuffer\r\n : (\r\n Uint8Array\r\n .fromBase64(value.base64Buffer)\r\n .buffer\r\n )\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new ArrayBuffer(10), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: ArrayBuffer = revived\r\n // @ts-expect-error - not an ArrayBuffer\r\n const notArrayBuffer: string = revived\r\n // @ts-expect-error - cannot box non-ArrayBuffer\r\n box('not an array buffer', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'date' as const\r\n\r\nexport const isType = (value: unknown): value is Date =>\r\n value instanceof Date\r\n\r\nexport const box = <T extends Date, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n ISOString: value.toISOString()\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n): Date => {\r\n return new Date(value.ISOString)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Date(), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Date = revived\r\n // @ts-expect-error - not a Date\r\n const notDate: string = revived\r\n // @ts-expect-error - cannot box non-Date\r\n box('not a date', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'headers' as const\r\n\r\nexport const isType = (value: unknown): value is Headers =>\r\n value instanceof Headers\r\n\r\nexport const box = <T extends Headers, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n entries: [...value.entries()]\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n): Headers => {\r\n return new Headers(value.entries)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Headers(), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Headers = revived\r\n // @ts-expect-error - not a Headers\r\n const notHeaders: string = revived\r\n // @ts-expect-error - cannot box non-Headers\r\n box('not a header', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'error' as const\r\n\r\nexport const isType = (value: unknown): value is Error =>\r\n value instanceof Error\r\n\r\nexport const box = <T extends Error, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n message: value.message,\r\n stack: value.stack || value.toString()\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => new Error(value.message, { cause: value.stack })\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Error('test'), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Error = revived\r\n // @ts-expect-error - not an Error\r\n const notError: string = revived\r\n // @ts-expect-error - cannot box non-Error\r\n box('not an error', {} as RevivableContext)\r\n}\r\n","import type { IsJsonOnlyTransport } from '../utils'\r\nimport type { RevivableContext, UnderlyingType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { isJsonOnlyTransport } from '../utils'\r\n\r\nexport const type = 'typedArray' as const\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\n\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypedArrayType = ReturnType<typeof typedArrayToType>\r\n\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypedArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isType = (value: unknown): value is TypedArray =>\r\n typedArrayConstructors.some(constructor => value instanceof constructor)\r\n\r\nexport const box = <T extends TypedArray, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n typedArrayType: typedArrayToType(value),\r\n ...(\r\n isJsonOnlyTransport(context.transport)\r\n ? { base64Buffer: new Uint8Array(value.buffer).toBase64() }\r\n : { arrayBuffer: value.buffer }\r\n ) as (\r\n IsJsonOnlyTransport<T2['transport']> extends true ? { base64Buffer: string }\r\n : IsJsonOnlyTransport<T2['transport']> extends false ? { arrayBuffer: ArrayBuffer }\r\n : { base64Buffer: string } | { arrayBuffer: ArrayBuffer }\r\n ) & { [UnderlyingType]: T }\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const TypedArrayConstructor = typedArrayTypeToTypedArrayConstructor(value.typedArrayType as TypedArrayType)\r\n const arrayBuffer =\r\n 'arrayBuffer' in value\r\n ? value.arrayBuffer\r\n : Uint8Array.fromBase64(value.base64Buffer).buffer\r\n return new TypedArrayConstructor(arrayBuffer)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const uint8Boxed = box(new Uint8Array(10), {} as RevivableContext)\r\n const uint8Revived = revive(uint8Boxed, {} as RevivableContext)\r\n const expectedUint8: Uint8Array = uint8Revived\r\n // @ts-expect-error - wrong typed array type\r\n const wrongType: Int32Array = uint8Revived\r\n\r\n const float32Boxed = box(new Float32Array(10), {} as RevivableContext)\r\n const float32Revived = revive(float32Boxed, {} as RevivableContext)\r\n const expectedFloat32: Float32Array = float32Revived\r\n // @ts-expect-error - wrong typed array type\r\n const wrongFloat: Uint8Array = float32Revived\r\n\r\n // @ts-expect-error - cannot box non-TypedArray\r\n box('not a typed array', {} as RevivableContext)\r\n}\r\n","import type { Capable, ConnectionMessage, Message, StructurableTransferable, Uuid } from '../types'\r\nimport type { StrictMessagePort } from '../utils/message-channel'\r\nimport type { RevivableContext, BoxBase as BoxBaseType, UnderlyingType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { OSRA_BOX } from '../types'\r\nimport { getTransferableObjects, isJsonOnlyTransport } from '../utils'\r\n\r\n/**\r\n * FinalizationRegistry for automatically cleaning up MessagePorts when they are garbage collected.\r\n * This is used in JSON-only mode where MessagePorts can't be transferred directly.\r\n */\r\ntype PortCleanupInfo = {\r\n sendMessage: (message: ConnectionMessage) => void\r\n remoteUuid: Uuid\r\n portId: string\r\n cleanup: () => void\r\n}\r\n\r\nconst messagePortRegistry = new FinalizationRegistry<PortCleanupInfo>((info) => {\r\n // Send close message to remote side\r\n info.sendMessage({\r\n type: 'message-port-close',\r\n remoteUuid: info.remoteUuid,\r\n portId: info.portId\r\n })\r\n // Perform local cleanup\r\n info.cleanup()\r\n})\r\n\r\nexport const type = 'messagePort' as const\r\n\r\nexport type BoxedMessagePort<T extends StructurableTransferable = StructurableTransferable> =\r\n & BoxBaseType<typeof type>\r\n & ({ portId: string } | { port: StrictMessagePort<T> })\r\n & { [UnderlyingType]: StrictMessagePort<T> }\r\n\r\ndeclare const StructurableTransferableError: unique symbol\r\ntype StructurableTransferablePort<T> = T extends StructurableTransferable\r\n ? StrictMessagePort<T>\r\n : { [StructurableTransferableError]: 'Message type must extend StructurableTransferable'; __badType__: T }\r\n\r\ntype ExtractStructurableTransferable<T> = T extends StructurableTransferable ? T : never\r\n\r\nexport const isType = (value: unknown): value is MessagePort =>\r\n value instanceof MessagePort\r\n\r\nconst isAlreadyBoxed = (value: unknown): boolean =>\r\n value !== null &&\r\n typeof value === 'object' &&\r\n OSRA_BOX in value &&\r\n (value as Record<string, unknown>)[OSRA_BOX] === 'revivable'\r\n\r\nexport const box = <T, T2 extends RevivableContext = RevivableContext>(\r\n value: StructurableTransferablePort<T>,\r\n context: T2\r\n) => {\r\n if (isJsonOnlyTransport(context.transport)) {\r\n const messagePort = value as StrictMessagePort<ExtractStructurableTransferable<T>>\r\n // Only generate a unique UUID, don't store the port in the allocator.\r\n // Storing the port would create a strong reference that prevents GC and FinalizationRegistry cleanup.\r\n const portId = context.messageChannels.getUniqueUuid()\r\n\r\n // Use WeakRef to allow messagePort to be garbage collected.\r\n // The eventTargetListener would otherwise hold a strong reference preventing GC.\r\n const messagePortRef = new WeakRef(messagePort)\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n // Define listener before registering with FinalizationRegistry so we can remove it in cleanup\r\n const eventTargetListener = ({ detail }: CustomEvent<{ message: Message }>) => {\r\n const { message } = detail\r\n if (message.type === 'message-port-close') {\r\n if (message.portId !== portId) return\r\n context.messageChannels.free(portId)\r\n const port = messagePortRef.deref()\r\n if (port) {\r\n // Unregister from FinalizationRegistry to prevent double-close\r\n messagePortRegistry.unregister(port)\r\n port.close()\r\n }\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n return\r\n }\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n const port = messagePortRef.deref()\r\n if (!port) {\r\n // Port was garbage collected, remove this listener\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n return\r\n }\r\n port.postMessage(message.data as ExtractStructurableTransferable<T>, getTransferableObjects(message.data))\r\n }\r\n\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n // Define this listener before registering so it can be removed in cleanup\r\n function messagePortListener({ data }: MessageEvent) {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: (isAlreadyBoxed(data) ? data : recursiveBox(data as Capable, context)) as Capable,\r\n portId\r\n })\r\n }\r\n\r\n // Register the messagePort for automatic cleanup when garbage collected\r\n // Use messagePort itself as the unregister token\r\n messagePortRegistry.register(messagePortRef.deref()!, {\r\n sendMessage: context.sendMessage,\r\n remoteUuid: context.remoteUuid,\r\n portId,\r\n cleanup: () => {\r\n context.messageChannels.free(portId)\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n messagePortRef.deref()?.removeEventListener('message', messagePortListener)\r\n messagePortRef.deref()?.close()\r\n }\r\n }, messagePortRef.deref())\r\n\r\n messagePortRef.deref()?.addEventListener('message', messagePortListener)\r\n messagePortRef.deref()?.start()\r\n\r\n context.eventTarget.addEventListener('message', eventTargetListener)\r\n \r\n const result = {\r\n ...BoxBase,\r\n type,\r\n portId\r\n }\r\n return result as typeof result & { [UnderlyingType]: StrictMessagePort<ExtractStructurableTransferable<T>> }\r\n }\r\n const result = {\r\n ...BoxBase,\r\n type,\r\n port: value\r\n }\r\n return result as typeof result & { [UnderlyingType]: StrictMessagePort<ExtractStructurableTransferable<T>> }\r\n}\r\n\r\nexport const revive = <T extends StructurableTransferable, T2 extends RevivableContext>(\r\n value: BoxedMessagePort<T>,\r\n context: T2\r\n): StrictMessagePort<T> => {\r\n if ('portId' in value) {\r\n const { portId } = value\r\n const { port1: userPort, port2: internalPort } = new MessageChannel()\r\n\r\n const existingChannel = context.messageChannels.get(value.portId)\r\n const { port1 } =\r\n existingChannel\r\n ? existingChannel\r\n : context.messageChannels.alloc(value.portId as Uuid)\r\n\r\n const userPortRef = new WeakRef(userPort)\r\n\r\n // Define all listeners before registering so they can be removed in cleanup\r\n const eventTargetListener = ({ detail }: CustomEvent<{ message: Message }>) => {\r\n const { message } = detail\r\n if (message.type !== 'message-port-close' || message.portId !== portId) return\r\n const port = userPortRef.deref()\r\n if (port) {\r\n // Unregister from FinalizationRegistry to prevent double-close\r\n messagePortRegistry.unregister(port)\r\n }\r\n performCleanup()\r\n }\r\n\r\n const port1Listener = ({ data: message }: MessageEvent) => {\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n\r\n const port = userPortRef.deref()\r\n if (!port) {\r\n // Port was garbage collected, cleanup\r\n performCleanup()\r\n return\r\n }\r\n\r\n // if the returned messagePort has been registered as internal message port, then we proxy the data without reviving it\r\n if (context.messagePorts.has(port)) {\r\n internalPort.postMessage(message.data)\r\n } else {\r\n // In this case, userPort is actually passed by the user of osra and we should revive all the message data\r\n const revivedData = recursiveRevive(message.data, context)\r\n internalPort.postMessage(revivedData, getTransferableObjects(revivedData))\r\n }\r\n }\r\n\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n // Define this listener before performCleanup so it can be removed in cleanup\r\n function internalPortListener({ data }: MessageEvent) {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: isAlreadyBoxed(data) ? data : recursiveBox(data, context),\r\n portId: portId as Uuid\r\n })\r\n }\r\n\r\n const performCleanup = () => {\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n port1.removeEventListener('message', port1Listener)\r\n internalPort.removeEventListener('message', internalPortListener)\r\n internalPort.close()\r\n // Close the allocator's MessageChannel ports before freeing\r\n // The allocator creates a MessageChannel with port1 and port2 - both must be closed\r\n const allocatedChannel = context.messageChannels.get(portId)\r\n if (allocatedChannel) {\r\n allocatedChannel.port1.close()\r\n if (allocatedChannel.port2) {\r\n allocatedChannel.port2.close()\r\n }\r\n }\r\n context.messageChannels.free(portId)\r\n }\r\n\r\n // Register the userPort for automatic cleanup when garbage collected\r\n // Use userPort itself as the unregister token\r\n messagePortRegistry.register(userPort, {\r\n sendMessage: context.sendMessage,\r\n remoteUuid: context.remoteUuid,\r\n portId,\r\n cleanup: performCleanup\r\n }, userPort)\r\n\r\n internalPort.addEventListener('message', internalPortListener)\r\n internalPort.start()\r\n\r\n // Listen for close messages from the remote side through the main event target\r\n context.eventTarget.addEventListener('message', eventTargetListener)\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n port1.addEventListener('message', port1Listener)\r\n port1.start()\r\n\r\n return userPort as StrictMessagePort<T>\r\n }\r\n return value.port\r\n}\r\n\r\nconst typeCheck = () => {\r\n const port = new MessageChannel().port1 as StrictMessagePort<{ foo: string }>\r\n const boxed = box(port, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: StrictMessagePort<{ foo: string }> = revived\r\n // @ts-expect-error - wrong message type\r\n const wrongType: StrictMessagePort<{ bar: number }> = revived\r\n // @ts-expect-error - non-StructurableTransferable message type\r\n box(new MessageChannel().port1 as StrictMessagePort<Promise<string>>, {} as RevivableContext)\r\n}\r\n","import type { Capable } from '../types'\r\nimport type { RevivableContext } from './utils'\r\nimport type { StrictMessagePort } from '../utils/message-channel'\r\nimport type { UnderlyingType } from '.'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'promise' as const\r\n\r\nexport type Context =\r\n | { type: 'resolve', data: Capable }\r\n | { type: 'reject', error: string }\r\n\r\ndeclare const CapableError: unique symbol\r\ntype CapablePromise<T> = T extends Capable\r\n ? Promise<T>\r\n : { [CapableError]: 'Message type must extend Capable'; __badType__: T }\r\n\r\ntype ExtractCapable<T> = T extends Capable ? T : never\r\n\r\nexport type BoxedPromise<T extends Capable = Capable> = {\r\n __OSRA_BOX__: 'revivable'\r\n type: typeof type\r\n port: ReturnType<typeof boxMessagePort>\r\n [UnderlyingType]: T\r\n}\r\n\r\nexport const isType = (value: unknown): value is Promise<any> =>\r\n value instanceof Promise\r\n\r\nexport const box = <T, T2 extends RevivableContext>(\r\n value: CapablePromise<T>,\r\n context: T2\r\n): BoxedPromise<ExtractCapable<T>> => {\r\n const promise = value as Promise<ExtractCapable<T>>\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const sendResult = (result: Context) => {\r\n const boxedResult = recursiveBox(result, context)\r\n localPort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n localPort.close()\r\n // Clean up the remote port from the set (it was transferred earlier)\r\n context.messagePorts.delete(remotePort)\r\n }\r\n\r\n promise\r\n .then((data: ExtractCapable<T>) => sendResult({ type: 'resolve', data }))\r\n .catch((error: unknown) => sendResult({ type: 'reject', error: (error as Error)?.stack ?? String(error) }))\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n port: boxMessagePort(remotePort as unknown as StrictMessagePort<string>, context)\r\n } as unknown as BoxedPromise<ExtractCapable<T>>\r\n}\r\n\r\nexport const revive = <T extends BoxedPromise, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n) => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort<string>, context)\r\n context.messagePorts.add(port as MessagePort)\r\n return new Promise<T[UnderlyingType]>((resolve, reject) => {\r\n port.addEventListener('message', (event) => {\r\n const data = (event as unknown as MessageEvent<Context>).data\r\n const result = recursiveRevive(data, context) as Context\r\n if (result.type === 'resolve') {\r\n resolve(result.data as T[UnderlyingType])\r\n } else {\r\n reject(result.error)\r\n }\r\n context.messagePorts.delete(port as MessagePort)\r\n port.close()\r\n }, { once: true })\r\n port.start()\r\n })\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(Promise.resolve(1 as const), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Promise<1> = revived\r\n // @ts-expect-error\r\n const notExpected: Promise<string> = revived\r\n // @ts-expect-error\r\n box(1 as const, {} as RevivableContext)\r\n}\r\n","import type { Capable } from '../types'\r\nimport type { UnderlyingType, RevivableContext, BoxBase as BoxBaseType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'function' as const\r\n\r\n/**\r\n * FinalizationRegistry for automatically cleaning up function ports when the revived function is garbage collected.\r\n */\r\ntype FunctionCleanupInfo = {\r\n port: MessagePort\r\n}\r\n\r\nconst functionRegistry = new FinalizationRegistry<FunctionCleanupInfo>((info) => {\r\n // Send a close signal through the port before closing it\r\n try {\r\n info.port.postMessage({ __osra_close__: true })\r\n } catch { /* Port may already be closed */ }\r\n try {\r\n info.port.close()\r\n } catch { /* Port may already be closed */ }\r\n})\r\n\r\nexport type CallContext = [\r\n /** MessagePort or portId that will be used to send the result of the function call */\r\n MessagePort | string,\r\n /** Arguments that will be passed to the function call */\r\n Capable[]\r\n]\r\n\r\nexport type BoxedFunction<T extends (...args: any[]) => any = (...args: any[]) => any> =\r\n & BoxBaseType<typeof type>\r\n & { port: BoxedMessagePort }\r\n & { [UnderlyingType]: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> }\r\n\r\ntype CapableFunction<T> = T extends (...args: infer P) => infer R\r\n ? P extends Capable[]\r\n ? R extends Capable ? T : never\r\n : never\r\n : never\r\n\r\nexport const isType = (value: unknown): value is (...args: any[]) => any =>\r\n typeof value === 'function'\r\n\r\nexport const box = <T extends (...args: any[]) => any, T2 extends RevivableContext>(\r\n value: T & CapableFunction<T>,\r\n context: T2\r\n): BoxedFunction<T> => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const cleanup = () => {\r\n context.messagePorts.delete(remotePort)\r\n localPort.close()\r\n }\r\n\r\n localPort.addEventListener('message', ({ data }: MessageEvent<CallContext | { __osra_close__: true }>) => {\r\n // Check for close signal\r\n if (data && typeof data === 'object' && '__osra_close__' in data) {\r\n cleanup()\r\n return\r\n }\r\n const [returnValuePort, args] = recursiveRevive(data as CallContext, context) as [MessagePort, Capable[]]\r\n const result = (async () => value(...args))()\r\n const boxedResult = recursiveBox(result, context)\r\n returnValuePort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n })\r\n localPort.start()\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n port: boxMessagePort(remotePort as any, context)\r\n } as BoxedFunction<T>\r\n}\r\n\r\nexport const revive = <T extends BoxedFunction, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort, context)\r\n\r\n const func = (...args: Capable[]) =>\r\n new Promise((resolve, reject) => {\r\n const { port1: returnValueLocalPort, port2: returnValueRemotePort } = new MessageChannel()\r\n context.messagePorts.add(returnValueRemotePort)\r\n const callContext = recursiveBox([returnValueRemotePort, args] as const, context)\r\n ;(port as MessagePort).postMessage(callContext, getTransferableObjects(callContext))\r\n // Remove the remote port from the set after transfer (it's neutered now)\r\n context.messagePorts.delete(returnValueRemotePort)\r\n\r\n returnValueLocalPort.addEventListener('message', ({ data }: MessageEvent<Capable>) => {\r\n const result = recursiveRevive(data, context) as Promise<Capable>\r\n result\r\n .then(resolve)\r\n .catch(reject)\r\n .finally(() => {\r\n returnValueLocalPort.close()\r\n })\r\n }, { once: true })\r\n returnValueLocalPort.start()\r\n })\r\n\r\n // Register the function for automatic cleanup when garbage collected\r\n functionRegistry.register(func, { port: port as MessagePort }, func)\r\n\r\n return func\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box((a: number, b: string) => a + b.length, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: (a: number, b: string) => Promise<number> = revived\r\n // @ts-expect-error - wrong return type\r\n const wrongReturn: (a: number, b: string) => Promise<string> = revived\r\n // @ts-expect-error - wrong parameter types\r\n const wrongParams: (a: string, b: number) => Promise<number> = revived\r\n // @ts-expect-error - non-Capable parameter type (Set is not directly Capable as parameter)\r\n box((a: WeakMap<object, string>) => a, {} as RevivableContext)\r\n // @ts-expect-error - non-Capable return type\r\n box(() => new WeakMap(), {} as RevivableContext)\r\n}\r\n","import type { Capable, StructurableTransferable } from '../types'\r\nimport type { RevivableContext } from './utils'\r\nimport type { StrictMessageChannel, StrictMessagePort } from '../utils/message-channel'\r\nimport type { UnderlyingType } from '.'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'readableStream' as const\r\n\r\nexport type PullContext = {\r\n type: 'pull' | 'cancel'\r\n}\r\n\r\nexport type BoxedReadableStream<T extends ReadableStream = ReadableStream> = {\r\n __OSRA_BOX__: 'revivable'\r\n type: typeof type\r\n port: BoxedMessagePort\r\n [UnderlyingType]: T\r\n}\r\n\r\nexport const isType = (value: unknown): value is ReadableStream =>\r\n value instanceof ReadableStream\r\n\r\nexport const box = <T extends ReadableStream, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): BoxedReadableStream<T> => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel() as StrictMessageChannel<StructurableTransferable, StructurableTransferable>\r\n context.messagePorts.add(remotePort as MessagePort)\r\n\r\n const reader = value.getReader()\r\n\r\n ;(localPort as MessagePort).addEventListener('message', async ({ data }) => {\r\n const { type } = recursiveRevive(data, context) as PullContext\r\n if (type === 'pull') {\r\n const pullResult = reader.read()\r\n const boxedResult = recursiveBox(pullResult, context)\r\n ;(localPort as MessagePort).postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n } else {\r\n reader.cancel()\r\n localPort.close()\r\n }\r\n })\r\n localPort.start()\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n port: boxMessagePort(remotePort as MessagePort as StrictMessagePort<Record<string, StructurableTransferable>>, context)\r\n } as BoxedReadableStream<T>\r\n}\r\n\r\nexport const revive = <T extends BoxedReadableStream, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort, context) as MessagePort\r\n context.messagePorts.add(port as MessagePort)\r\n port.start()\r\n\r\n return new ReadableStream({\r\n start(_controller) {},\r\n pull(controller) {\r\n return new Promise((resolve, reject) => {\r\n port.addEventListener('message', async ({ data }) => {\r\n const result = recursiveRevive(data, context) as Promise<ReadableStreamReadResult<any>>\r\n result\r\n .then(result => {\r\n if (result.done) controller.close()\r\n else controller.enqueue(result.value)\r\n resolve()\r\n })\r\n .catch(reject)\r\n }, { once: true })\r\n port.postMessage(recursiveBox({ type: 'pull' }, context))\r\n })\r\n },\r\n cancel() {\r\n port.postMessage(recursiveBox({ type: 'cancel' }, context))\r\n port.close()\r\n }\r\n }) as T[UnderlyingType]\r\n}\r\n\r\nconst typeCheck = () => {\r\n const stream = new ReadableStream<number>()\r\n const boxed = box(stream, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: ReadableStream<number> = revived\r\n // @ts-expect-error - wrong stream type\r\n const wrongType: ReadableStream<string> = revived\r\n // @ts-expect-error - not a ReadableStream\r\n box('not a stream', {} as RevivableContext)\r\n}\r\n","import type { BoxBase, RevivableContext } from './utils'\r\nexport type { UnderlyingType } from './utils'\r\nimport type { DeepReplaceWithBox, DeepReplaceWithRevive, ReplaceWithBox, ReplaceWithRevive } from '../utils/replace'\r\n\r\nimport { Capable } from '../types'\r\nimport { isRevivableBox } from './utils'\r\nimport * as arrayBuffer from './array-buffer'\r\nimport * as context from './context'\r\nimport * as date from './date'\r\nimport * as headers from './headers'\r\nimport * as error from './error'\r\nimport * as typedArray from './typed-array'\r\nimport * as promise from './promise'\r\nimport * as func from './function'\r\nimport * as messagePort from './message-port'\r\nimport * as readableStream from './readable-stream'\r\n\r\nexport type RevivableModule<T extends string = string, T2 = any, T3 extends BoxBase<T> = any> = {\r\n readonly type: T\r\n readonly isType: (value: unknown) => value is T2\r\n readonly box: ((value: T2, context: RevivableContext) => T3) | ((...args: any[]) => any)\r\n readonly revive: (value: T3, context: RevivableContext) => T2\r\n}\r\n\r\nexport const defaultRevivableModules = [\r\n arrayBuffer,\r\n context,\r\n date,\r\n headers,\r\n error,\r\n typedArray,\r\n promise,\r\n func,\r\n messagePort,\r\n readableStream\r\n] as const\r\n\r\nexport type DefaultRevivableModules = typeof defaultRevivableModules\r\n\r\nexport type DefaultRevivableModule = DefaultRevivableModules[number]\r\n\r\nexport const findModuleForValue = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithBox<T, T2['revivableModules'][number]>\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const box = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithBox<T, T2['revivableModules'][number]>\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const recursiveBox = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): DeepReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = DeepReplaceWithBox<T, T2['revivableModules'][number]>\r\n\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n\r\n return (\r\n Array.isArray(value) ? value.map(value => recursiveBox(value, context)) as ReturnCastType\r\n : value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveBox(value, context)\r\n ])\r\n )\r\n ) as ReturnCastType\r\n : value as ReturnCastType\r\n )\r\n}\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithRevive<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithRevive<T, T2['revivableModules'][number]>\r\n const boxType =\r\n isRevivableBox(value, context)\r\n ? value.type\r\n : undefined\r\n const handledByModule = context.revivableModules.find(module => module.type === boxType)\r\n if (handledByModule) {\r\n return (handledByModule.revive as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const recursiveRevive = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): DeepReplaceWithRevive<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = DeepReplaceWithRevive<T, T2['revivableModules'][number]>\r\n\r\n // First check if the value is a revivable box and revive it\r\n if (isRevivableBox(value, context)) {\r\n const handledByModule = context.revivableModules.find(module => module.type === value.type)\r\n if (handledByModule) {\r\n return (handledByModule.revive as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n }\r\n\r\n // Then recurse into arrays and plain objects\r\n return (\r\n Array.isArray(value) ? value.map(value => recursiveRevive(value, context)) as ReturnCastType\r\n : value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveRevive(value, context)\r\n ])\r\n )\r\n ) as ReturnCastType\r\n : value as ReturnCastType\r\n )\r\n}\r\n","import type {\r\n Capable, ConnectionMessage,\r\n Message,\r\n MessageContext,\r\n MessageEventTarget,\r\n Transport,\r\n Uuid\r\n} from '../types'\r\nimport type { MessageChannelAllocator } from './allocator'\r\nimport type { PlatformCapabilities } from './capabilities'\r\nimport type { StrictMessagePort } from './message-channel'\r\n\r\nimport { makeMessageChannelAllocator } from './allocator'\r\nimport { DefaultRevivableModules, defaultRevivableModules, recursiveBox, recursiveRevive, RevivableModule } from '../revivables'\r\n\r\nexport type BidirectionalConnectionContext = {\r\n type: 'bidirectional'\r\n eventTarget: MessageEventTarget\r\n connection: BidirectionalConnection\r\n}\r\nexport type UnidirectionalEmittingConnectionContext = {\r\n type: 'unidirectional-emitting'\r\n connection: UnidirectionalEmittingConnection\r\n}\r\nexport type UnidirectionalReceivingConnectionContext = {\r\n type: 'unidirectional-receiving'\r\n eventTarget: MessageEventTarget\r\n connection: UnidirectionalReceivingConnection\r\n}\r\n\r\nexport type ConnectionContext =\r\n | BidirectionalConnectionContext\r\n | UnidirectionalEmittingConnectionContext\r\n | UnidirectionalReceivingConnectionContext\r\n\r\nexport type ConnectionRevivableContext<TModules extends readonly RevivableModule[] = DefaultRevivableModules> = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n revivableModules: TModules\r\n eventTarget: MessageEventTarget\r\n}\r\n\r\nexport type BidirectionalConnection<T extends Capable = Capable> = {\r\n revivableContext: ConnectionRevivableContext\r\n close: () => void\r\n remoteValue: Promise<T>\r\n}\r\n\r\nexport const startBidirectionalConnection = <T extends Capable>(\r\n { transport, value, uuid, remoteUuid, platformCapabilities, eventTarget, send, close }:\r\n {\r\n transport: Transport\r\n value: Capable\r\n uuid: Uuid\r\n remoteUuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: MessageEventTarget\r\n send: (message: ConnectionMessage) => void\r\n close: () => void\r\n }\r\n) => {\r\n const revivableContext: ConnectionRevivableContext & { messageContext?: MessageContext } = {\r\n platformCapabilities,\r\n transport,\r\n remoteUuid,\r\n messagePorts: new Set<MessagePort>(),\r\n messageChannels: makeMessageChannelAllocator(),\r\n sendMessage: send,\r\n eventTarget,\r\n revivableModules: defaultRevivableModules,\r\n messageContext: undefined\r\n }\r\n type InitMessageWithContext = { message: ConnectionMessage & { type: 'init' }, messageContext: MessageContext }\r\n let initResolve: ((data: InitMessageWithContext) => void)\r\n const initMessagePromise = new Promise<InitMessageWithContext>((resolve, reject) => {\r\n initResolve = resolve\r\n })\r\n\r\n eventTarget.addEventListener('message', ({ detail }) => {\r\n const { message, messageContext } = detail\r\n if (message.type === 'init') {\r\n initResolve({ message, messageContext })\r\n return\r\n } else if (message.type === 'message') {\r\n const messageChannel = revivableContext.messageChannels.getOrAlloc(message.portId)\r\n ;(messageChannel.port2 as MessagePort)?.postMessage(message)\r\n }\r\n })\r\n\r\n send({\r\n type: 'init',\r\n remoteUuid,\r\n data: recursiveBox(value, revivableContext) as Capable\r\n })\r\n\r\n return {\r\n revivableContext,\r\n close: () => {\r\n },\r\n remoteValue:\r\n initMessagePromise\r\n .then(({ message, messageContext }) => {\r\n // Store the messageContext in revivableContext for use by subsequent function calls\r\n revivableContext.messageContext = messageContext\r\n return recursiveRevive(message.data, revivableContext)\r\n }) as Promise<T>\r\n } satisfies BidirectionalConnection<T>\r\n}\r\n\r\nexport type UnidirectionalEmittingConnection<T extends Capable = Capable> = {\r\n close: () => void\r\n remoteValueProxy: T\r\n}\r\n\r\nexport const startUnidirectionalEmittingConnection = <T extends Capable>(\r\n { value, uuid, platformCapabilities, send, close }:\r\n {\r\n value: Capable\r\n uuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n send: (message: Message) => void\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n },\r\n remoteValueProxy: new Proxy(\r\n new Function(),\r\n {\r\n apply: (target, thisArg, args) => {\r\n },\r\n get: (target, prop) => {\r\n }\r\n }\r\n ) as T\r\n }\r\n}\r\n\r\nexport type UnidirectionalReceivingConnection = {\r\n close: () => void\r\n}\r\n\r\nexport const startUnidirectionalReceivingConnection = (\r\n { uuid, remoteUuid, platformCapabilities, close }:\r\n {\r\n uuid: Uuid\r\n remoteUuid?: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: StrictMessagePort<Message>\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n }\r\n }\r\n}\r\n","var e=class extends EventTarget{dispatchTypedEvent(s,t){return super.dispatchEvent(t)}};export{e as TypedEventTarget};\n","import type {\r\n EmitTransport, Message,\r\n MessageContext, MessageVariant,\r\n Capable, Transport,\r\n MessageEventTarget,\r\n MessageEventMap\r\n} from './types'\r\nexport type { UnderlyingType } from './revivables/utils'\r\nexport type { MessageContext } from './types'\r\nexport { OSRA_CONTEXT } from './revivables/context'\r\nimport type {\r\n PlatformCapabilities, ConnectionContext,\r\n BidirectionalConnectionContext\r\n} from './utils'\r\n\r\nimport { OSRA_DEFAULT_KEY, OSRA_KEY } from './types'\r\nexport { BoxBase } from './revivables/utils'\r\nimport {\r\n probePlatformCapabilities,\r\n registerOsraMessageListener,\r\n sendOsraMessage,\r\n startBidirectionalConnection,\r\n isReceiveTransport,\r\n isEmitTransport,\r\n startUnidirectionalEmittingConnection,\r\n getTransferableObjects,\r\n isJsonOnlyTransport,\r\n isCustomTransport\r\n} from './utils'\r\nimport { TypedEventTarget } from 'typescript-event-target'\r\n\r\n/**\r\n * Protocol mode:\r\n * - Bidirectional mode\r\n * - Unidirectional mode\r\n *\r\n * Transport modes:\r\n * - Capable mode\r\n * - Jsonable mode\r\n */\r\nexport const expose = async <T extends Capable>(\r\n value: Capable,\r\n {\r\n transport: _transport,\r\n name,\r\n remoteName,\r\n key = OSRA_DEFAULT_KEY,\r\n origin = '*',\r\n unregisterSignal,\r\n platformCapabilities: _platformCapabilities,\r\n transferAll,\r\n logger\r\n }: {\r\n transport: Transport\r\n name?: string\r\n remoteName?: string\r\n key?: string\r\n origin?: string\r\n unregisterSignal?: AbortSignal\r\n platformCapabilities?: PlatformCapabilities\r\n transferAll?: boolean\r\n logger?: {}\r\n }\r\n): Promise<T> => {\r\n const transport = {\r\n isJson:\r\n 'isJson' in _transport && _transport.isJson !== undefined\r\n ? _transport.isJson\r\n : isJsonOnlyTransport(_transport),\r\n ...(\r\n isCustomTransport(_transport)\r\n ? _transport\r\n : {\r\n emit: _transport,\r\n receive: _transport\r\n }\r\n )\r\n } satisfies Transport\r\n const platformCapabilities = _platformCapabilities ?? await probePlatformCapabilities()\r\n const connectionContexts = new Map<string, ConnectionContext>()\r\n\r\n let resolveRemoteValue: (connection: T) => void\r\n const remoteValuePromise = new Promise<T>((resolve) => {\r\n resolveRemoteValue = resolve\r\n })\r\n\r\n let uuid = globalThis.crypto.randomUUID()\r\n \r\n \r\n let aborted = false\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () => {\r\n aborted = true\r\n })\r\n }\r\n\r\n const sendMessage = (transport: EmitTransport, message: MessageVariant) => {\r\n if (aborted) return\r\n const transferables = getTransferableObjects(message)\r\n sendOsraMessage(\r\n transport,\r\n {\r\n [OSRA_KEY]: key,\r\n name,\r\n uuid,\r\n ...message\r\n },\r\n origin,\r\n transferables\r\n )\r\n }\r\n\r\n const listener = async (message: Message, messageContext: MessageContext) => {\r\n // means that our own message looped back on the channel\r\n if (message.uuid === uuid) return\r\n // Unidirectional receiving mode\r\n if (!isEmitTransport(transport)) {\r\n // Handle non bidirectional based messages here\r\n throw new Error('Unidirectional receiving mode not implemented')\r\n }\r\n // Bidirectional mode\r\n if (message.type === 'announce') {\r\n if (!message.remoteUuid) {\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n return\r\n }\r\n if (message.remoteUuid !== uuid) return\r\n // todo: re-add uuid collision handling\r\n if (connectionContexts.has(message.uuid)) {\r\n return\r\n }\r\n // Send announce back so the other side can also create a connection\r\n // (in case they missed our initial announce due to timing)\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n const eventTarget = new TypedEventTarget<MessageEventMap>()\r\n const connectionContext = {\r\n type: 'bidirectional',\r\n eventTarget,\r\n connection:\r\n startBidirectionalConnection({\r\n transport,\r\n value,\r\n uuid,\r\n remoteUuid: message.uuid,\r\n platformCapabilities,\r\n eventTarget,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => void connectionContexts.delete(message.uuid)\r\n })\r\n } satisfies BidirectionalConnectionContext\r\n connectionContexts.set(message.uuid, connectionContext)\r\n connectionContext.connection.remoteValue.then((remoteValue) =>\r\n resolveRemoteValue(remoteValue as T)\r\n )\r\n } else if (message.type === 'reject-uuid-taken') {\r\n if (message.remoteUuid !== uuid) return\r\n uuid = globalThis.crypto.randomUUID()\r\n sendMessage(transport, { type: 'announce' })\r\n } else if (message.type === 'close') {\r\n if (message.remoteUuid !== uuid) return\r\n const connectionContext = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connectionContext) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n connectionContext.connection.close()\r\n connectionContexts.delete(message.uuid)\r\n } else { // \"init\" | \"message\" | \"message-port-close\"\r\n if (message.remoteUuid !== uuid) return\r\n const connection = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connection) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n if (connection.type !== 'unidirectional-emitting') {\r\n connection.eventTarget.dispatchTypedEvent(\r\n 'message',\r\n new CustomEvent('message', { detail: { message, messageContext } })\r\n )\r\n }\r\n }\r\n }\r\n\r\n if (isReceiveTransport(transport)) {\r\n registerOsraMessageListener({\r\n listener,\r\n transport,\r\n remoteName,\r\n key,\r\n unregisterSignal\r\n })\r\n }\r\n\r\n if (isEmitTransport(transport)) {\r\n sendMessage(transport, { type: 'announce' })\r\n }\r\n\r\n // Unidirectional emitting mode\r\n if (isEmitTransport(transport) && !isReceiveTransport(transport)) {\r\n const { remoteValueProxy } = startUnidirectionalEmittingConnection<T>({\r\n value,\r\n uuid,\r\n platformCapabilities,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => connectionContexts.delete(uuid)\r\n })\r\n return remoteValueProxy\r\n }\r\n\r\n return remoteValuePromise\r\n}\r\n"],"names":["OSRA_KEY","OSRA_DEFAULT_KEY","OSRA_BOX","BoxBase","isRevivableBox","value","_context","type","OSRA_CONTEXT_MARKER","OSRA_CONTEXT","isType","box","_value","revive","context","makeMessageChannelAllocator","channels","result","uuid","messagePorts","allocatedMessageChannel","messageChannel","existingChannel","checkOsraMessageKey","message","key","isOsraMessage","registerOsraMessageListener","listener","transport","remoteName","unregisterSignal","registerListenerOnReceiveTransport","receiveTransport","isWebExtensionPort","isWebExtensionOnConnect","isWebExtensionOnMessage","listenOnWebExtOnMessage","onMessage","port","_listener","sender","messageListener","event","isCustomTransport","sendOsraMessage","origin","transferables","sendToEmitTransport","emitTransport","isWindow","isWebSocket","isSharedWorker","isServiceWorkerContainer","isWorker","isDedicatedWorker","isMessagePort","isClonable","isTransferable","connectPort","w","isEmitJsonOnlyTransport","isReceiveJsonOnlyTransport","isJsonOnlyTransport","isEmitTransport","isCustomEmitTransport","isReceiveTransport","isCustomReceiveTransport","getTransferableObjects","recurse","probePlatformCapabilityUtil","transfer","port1","port2","resolve","probeMessagePortTransfer","probeArrayBufferClone","buffer","probeArrayBufferTransfer","probeTransferableStream","stream","controller","probePlatformCapabilities","messagePort","arrayBuffer","transferable","transferableStream","typedArrayConstructors","typedArrayToType","typedArrayTypeToTypedArrayConstructor","typedArray","constructor","TypedArrayConstructor","messagePortRegistry","info","isAlreadyBoxed","messagePortListener","data","recursiveBox","portId","messagePortRef","eventTargetListener","detail","internalPortListener","userPort","internalPort","userPortRef","performCleanup","port1Listener","revivedData","recursiveRevive","allocatedChannel","promise","localPort","remotePort","sendResult","boxedResult","error","boxMessagePort","reviveMessagePort","reject","functionRegistry","cleanup","returnValuePort","args","func","returnValueLocalPort","returnValueRemotePort","callContext","reader","pullResult","_controller","defaultRevivableModules","date","headers","readableStream","handledByModule","module","startBidirectionalConnection","remoteUuid","platformCapabilities","eventTarget","send","close","revivableContext","initResolve","initMessagePromise","messageContext","startUnidirectionalEmittingConnection","target","thisArg","prop","e","s","expose","_transport","name","_platformCapabilities","transferAll","logger","connectionContexts","resolveRemoteValue","remoteValuePromise","aborted","sendMessage","TypedEventTarget","connectionContext","remoteValue","connection","remoteValueProxy"],"mappings":"AAKO,MAAMA,IAAW,gBACXC,KAAmB,wBACnBC,IAAW,gBCEXC,IAAU;AAAA,EACrB,CAACD,CAAQ,GAAG;AAAA,EACZ,MAAM;AACR,GA6BaE,KAAiB,CAA6BC,GAAYC,MACrED,KACG,OAAOA,KAAU,YACjBH,KAAYG,KACZA,EAAMH,CAAQ,MAAM,aCxCZK,IAAO,WAKdC,IAAsB,OAAO,IAAI,cAAc,GAQxCC,KAA+B,EAAE,CAACD,CAAmB,GAAG,GAAA,GAExDE,KAAS,CAACL,MACrBA,MAAU,QACV,OAAOA,KAAU,YACjBG,KAAuBH,GAEZM,KAAM,CACjBC,GACAN,OACI;AAAA,EACJ,GAAGH;AAAA,EAAA,MACHI;AACF,IAEaM,KAAS,CACpBD,GACAE,MAEOA,EAAQ,kBAAkB,CAAA;;;;;;;8CCWtBC,KAA8B,MAAM;AAC/C,QAAMC,wBAAe,IAAA,GAEfC,IAAS;AAAA,IACb,eAAe,MAAM;AACnB,UAAIC,IAAa,WAAW,OAAO,WAAA;AACnC,aAAOF,EAAS,IAAIE,CAAI;AACtB,QAAAA,IAAO,WAAW,OAAO,WAAA;AAE3B,aAAOA;AAAA,IACT;AAAA,IACA,KAAK,CAACA,GAAYC,MAA0E;AAC1F,MAAAH,EAAS,IAAIE,GAAM,EAAE,MAAAA,GAAM,GAAGC,GAAc;AAAA,IAC9C;AAAA,IACA,OAAO,CACLD,IAAyBD,EAAO,cAAA,GAChCE,MACG;AACH,UAAIA,GAAc;AAChB,cAAMC,IAA0B,EAAE,MAAAF,GAAM,GAAGC,EAAA;AAC3C,eAAAH,EAAS,IAAIE,GAAME,CAAuB,GACnCA;AAAAA,MACT;AACA,Y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