osra 0.2.3 → 0.2.4
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 +4 -4
- package/build/index.js.map +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -191,7 +191,7 @@ const re = (e) => {
|
|
|
191
191
|
typedArrayToType: re,
|
|
192
192
|
typedArrayTypeToTypedArrayConstructor: ne
|
|
193
193
|
}, Symbol.toStringTag, { value: "Module" })), C = new FinalizationRegistry((e) => {
|
|
194
|
-
|
|
194
|
+
e.sendMessage({
|
|
195
195
|
type: "message-port-close",
|
|
196
196
|
remoteUuid: e.remoteUuid,
|
|
197
197
|
portId: e.portId
|
|
@@ -209,7 +209,7 @@ const re = (e) => {
|
|
|
209
209
|
const a = e, s = t.messageChannels.getUniqueUuid(), o = new WeakRef(a), i = ({ detail: y }) => {
|
|
210
210
|
if (y.type === "message-port-close") {
|
|
211
211
|
if (y.portId !== s) return;
|
|
212
|
-
t.messageChannels.free(s)
|
|
212
|
+
t.messageChannels.free(s);
|
|
213
213
|
const l = o.deref();
|
|
214
214
|
l && (C.unregister(l), l.close()), t.eventTarget.removeEventListener("message", i);
|
|
215
215
|
return;
|
|
@@ -227,7 +227,7 @@ const re = (e) => {
|
|
|
227
227
|
remoteUuid: t.remoteUuid,
|
|
228
228
|
portId: s,
|
|
229
229
|
cleanup: () => {
|
|
230
|
-
t.messageChannels.free(s),
|
|
230
|
+
t.messageChannels.free(s), t.eventTarget.removeEventListener("message", i), o.deref()?.removeEventListener("message", n), o.deref()?.close();
|
|
231
231
|
}
|
|
232
232
|
}, o.deref()), o.deref()?.addEventListener("message", n), o.deref()?.start(), t.eventTarget.addEventListener("message", i), {
|
|
233
233
|
...u,
|
|
@@ -270,7 +270,7 @@ const re = (e) => {
|
|
|
270
270
|
}, l = () => {
|
|
271
271
|
t.eventTarget.removeEventListener("message", y), i.removeEventListener("message", p), s.removeEventListener("message", r), s.close();
|
|
272
272
|
const f = t.messageChannels.get(n);
|
|
273
|
-
f && (f.port1.close(), f.port2 && f.port2.close()),
|
|
273
|
+
f && (f.port1.close(), f.port2 && f.port2.close()), t.messageChannels.free(n);
|
|
274
274
|
};
|
|
275
275
|
return C.register(a, {
|
|
276
276
|
sendMessage: t.sendMessage,
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/types.ts","../src/revivables/utils.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/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 MessageEventMap = {\r\n message: CustomEvent<Message>\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, 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}\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 { 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 && 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 && ('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 && (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 && (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: any): value is Window => {\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as Window).document\r\n && (value as Window).location\r\n && (value as Window).navigator\r\n && (value as Window).screen\r\n && (value as Window).history\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 isEmitJsonOnlyTransport(value)\r\n || isWindow(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 isReceiveJsonOnlyTransport(value)\r\n || isWindow(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 '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 '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 isJsonOnlyTransport(value)\r\n || isEmitTransport(value)\r\n || isReceiveTransport(value)\r\n || isCustomTransport(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 = '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 console.log('cleanup', info.portId)\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: message }: CustomEvent<Message>) => {\r\n if (message.type === 'message-port-close') {\r\n if (message.portId !== portId) return\r\n context.messageChannels.free(portId)\r\n console.log('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 console.log('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: message }: CustomEvent<Message>) => {\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 console.log('free', portId)\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 date from './date'\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 date,\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 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 let initResolve: ((message: ConnectionMessage & { type: 'init' }) => void)\r\n const initMessage = new Promise<ConnectionMessage & { type: 'init' }>((resolve, reject) => {\r\n initResolve = resolve\r\n })\r\n\r\n eventTarget.addEventListener('message', ({ detail }) => {\r\n if (detail.type === 'init') {\r\n initResolve(detail)\r\n return\r\n } else if (detail.type === 'message') {\r\n const messageChannel = revivableContext.messageChannels.getOrAlloc(detail.portId)\r\n ;(messageChannel.port2 as MessagePort)?.postMessage(detail)\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 initMessage\r\n .then(initMessage => recursiveRevive(initMessage.data, revivableContext)) 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\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 const sendMessage = (transport: EmitTransport, message: MessageVariant) => {\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 })\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","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","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","type","isType","box","revive","typedArrayConstructors","typedArrayToType","typedArrayTypeToTypedArrayConstructor","typedArray","constructor","context","TypedArrayConstructor","messagePortRegistry","info","isAlreadyBoxed","messagePortListener","data","recursiveBox","portId","messagePortRef","eventTargetListener","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","readableStream","handledByModule","module","startBidirectionalConnection","remoteUuid","platformCapabilities","eventTarget","send","close","revivableContext","initResolve","initMessage","detail","startUnidirectionalEmittingConnection","target","thisArg","prop","e","s","expose","_transport","name","_platformCapabilities","transferAll","logger","connectionContexts","resolveRemoteValue","remoteValuePromise","sendMessage","messageContext","TypedEventTarget","connectionContext","remoteValue","connection","remoteValueProxy"],"mappings":"AAKO,MAAMA,IAAW,gBACXC,KAAmB,wBACnBC,IAAW,gBCEXC,IAAU;AAAA,EACrB,CAACD,CAAQ,GAAG;AAAA,EACZ,MAAM;AACR,GA2BaE,KAAiB,CAA6BC,GAAYC,MACrED,KACG,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,OAAO;AACL,YAAIA,EAAQ,eAAeN,EAAM;AACjC,cAAMwJ,IAAaR,EAAmB,IAAI1I,EAAQ,IAAI;AAEtD,YAAI,CAACkJ,GAAY;AACf,kBAAQ,KAAK,wCAAwClJ,EAAQ,IAAI,EAAE;AACnE;AAAA,QACF;AACA,QAAIkJ,EAAW,SAAS,6BACtBA,EAAW,YAAY;AAAA,UACrB;AAAA,UACA,IAAI,YAAY,WAAW,EAAE,QAAQlJ,GAAS;AAAA,QAAA;AAAA,MAGpD;AAAA;AAAA,EACF;AAiBA,MAfIyC,EAAmBpC,CAAS,KAC9BF,GAA4B;AAAA,IAC1B,UAAAC;AAAA,IACA,WAAAC;AAAA,IACA,YAAAC;AAAA,IACA,KAAAL;AAAA,IACA,kBAAAM;AAAA,EAAA,CACD,GAGCgC,EAAgBlC,CAAS,KAC3BwI,EAAYxI,GAAW,EAAE,MAAM,WAAA,CAAY,GAIzCkC,EAAgBlC,CAAS,KAAK,CAACoC,EAAmBpC,CAAS,GAAG;AAChE,UAAM,EAAE,kBAAA8I,EAAA,IAAqBrB,GAAyC;AAAA,MACpE,OAAAzI;AAAA,MACA,MAAAK;AAAA,MACA,sBAAA4H;AAAA,MACA,MAAM,CAACtH,MAA4B6I,EAAYxI,GAAWL,CAAO;AAAA,MACjE,OAAO,MAAM0I,EAAmB,OAAOhJ,CAAI;AAAA,IAAA,CAC5C;AACD,WAAOyJ;AAAA,EACT;AAEA,SAAOP;AACT;","x_google_ignoreList":[17]}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/types.ts","../src/revivables/utils.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/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 MessageEventMap = {\r\n message: CustomEvent<Message>\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, 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}\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 { 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 && 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 && ('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 && (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 && (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: any): value is Window => {\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as Window).document\r\n && (value as Window).location\r\n && (value as Window).navigator\r\n && (value as Window).screen\r\n && (value as Window).history\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 isEmitJsonOnlyTransport(value)\r\n || isWindow(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 isReceiveJsonOnlyTransport(value)\r\n || isWindow(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 '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 '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 isJsonOnlyTransport(value)\r\n || isEmitTransport(value)\r\n || isReceiveTransport(value)\r\n || isCustomTransport(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 = '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: message }: CustomEvent<Message>) => {\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: message }: CustomEvent<Message>) => {\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 date from './date'\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 date,\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 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 let initResolve: ((message: ConnectionMessage & { type: 'init' }) => void)\r\n const initMessage = new Promise<ConnectionMessage & { type: 'init' }>((resolve, reject) => {\r\n initResolve = resolve\r\n })\r\n\r\n eventTarget.addEventListener('message', ({ detail }) => {\r\n if (detail.type === 'init') {\r\n initResolve(detail)\r\n return\r\n } else if (detail.type === 'message') {\r\n const messageChannel = revivableContext.messageChannels.getOrAlloc(detail.portId)\r\n ;(messageChannel.port2 as MessagePort)?.postMessage(detail)\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 initMessage\r\n .then(initMessage => recursiveRevive(initMessage.data, revivableContext)) 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\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 const sendMessage = (transport: EmitTransport, message: MessageVariant) => {\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 })\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","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","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","type","isType","box","revive","typedArrayConstructors","typedArrayToType","typedArrayTypeToTypedArrayConstructor","typedArray","constructor","context","TypedArrayConstructor","messagePortRegistry","info","isAlreadyBoxed","messagePortListener","data","recursiveBox","portId","messagePortRef","eventTargetListener","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","readableStream","handledByModule","module","startBidirectionalConnection","remoteUuid","platformCapabilities","eventTarget","send","close","revivableContext","initResolve","initMessage","detail","startUnidirectionalEmittingConnection","target","thisArg","prop","e","s","expose","_transport","name","_platformCapabilities","transferAll","logger","connectionContexts","resolveRemoteValue","remoteValuePromise","sendMessage","messageContext","TypedEventTarget","connectionContext","remoteValue","connection","remoteValueProxy"],"mappings":"AAKO,MAAMA,IAAW,gBACXC,KAAmB,wBACnBC,IAAW,gBCEXC,IAAU;AAAA,EACrB,CAACD,CAAQ,GAAG;AAAA,EACZ,MAAM;AACR,GA2BaE,KAAiB,CAA6BC,GAAYC,MACrED,KACG,OAAOA,KAAU,YACjBH,KAAYG,KACZA,EAAMH,CAAQ,MAAM,aCKZK,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,YAAMC,IAAiB,IAAI,eAAA,GACrB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