psionic 0.3.3 → 0.3.5
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/adapters/reconnect.mjs +41 -1
- package/adapters/reconnect.mjs.map +1 -1
- package/adapters/resend.mjs +25 -1
- package/adapters/resend.mjs.map +1 -1
- package/adapters/socket.mjs +159 -2
- package/adapters/socket.mjs.map +1 -1
- package/adapters/websocket.mjs +134 -1
- package/adapters/websocket.mjs.map +1 -1
- package/adapters/webworker.mjs +41 -1
- package/adapters/webworker.mjs.map +1 -1
- package/codecs/cbor.mjs +197 -1
- package/codecs/cbor.mjs.map +1 -1
- package/codecs/psionic.mjs +56 -1
- package/codecs/psionic.mjs.map +1 -1
- package/package.json +1 -1
- package/psionic.mjs +671 -1
- package/psionic.mjs.map +1 -1
- package/session.mjs +91 -1
- package/session.mjs.map +1 -1
- package/utils/react-hooks.mjs +36 -1
- package/utils/react-hooks.mjs.map +1 -1
package/psionic.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"psionic.mjs","names":[],"sources":["../src/psionic.ts"],"sourcesContent":["/**\n * Psionic - Live-updating, cross-language, bidirectional RPC protocol.\n */\n\nimport { type ID, type OperationGenerator, type Session, type OperationTypes, type OperationOutboundCall, createSession } from \"./session\";\n\nconst MAX_ID_LENGTH = 0x40;\n\nexport const Keyword = '@@psion' as const;\nexport let CallContextSymbol = Symbol('call-context');\n\n// Sentinels for function types in codec format.\n// WireCodec converts these to/from wire-safe representations.\nexport const AsyncFnKey = 'f';\nexport const AsyncGenKey = 'g';\n\nexport const STATE_DISCONNECTED = 0 as const;\nexport const STATE_CONNECTING = 1 as const;\nexport const STATE_CONNECTED = 2 as const;\nexport const STATE_LOCAL_DESCRIBED = 3 as const;\nexport const STATE_REMOTE_DESCRIBED = 4 as const;\nexport const STATE_READY = 5 as const;\n\nexport type ReadyState = typeof STATE_DISCONNECTED | typeof STATE_CONNECTING | typeof STATE_CONNECTED | typeof STATE_LOCAL_DESCRIBED | typeof STATE_REMOTE_DESCRIBED | typeof STATE_READY;\n\nexport const OpDescribe = 'D' as const;\nexport const OpCall = 'C' as const;\nexport const OpOK = 'K' as const;\nexport const OpError = 'E' as const;\nexport const OpIterNext = '.' as const;\nexport const OpIterReturn = '<' as const;\nexport const OpIterThrow = '>' as const;\n\nexport type CallFrame = [type: typeof OpCall, id: ID, name: string[], args: any[]];\nexport type DescribeFrame = [type: typeof OpDescribe, id: ID, description: any, swap?: boolean];\nexport type RespondFrame = [type: typeof OpOK, id: ID, result: any];\nexport type ErrorFrame = [type: typeof OpError, id: ID, code: number, error?: string];\nexport type IterNextFrame = [type: typeof OpIterNext, id: ID, operationId: ID, value: any];\nexport type IterReturnFrame = [type: typeof OpIterReturn, id: ID, operationId: ID, value: any];\nexport type IterThrowFrame = [type: typeof OpIterThrow, id: ID, operationId: ID, code: number, error?: string];\nexport type Frame = DescribeFrame | CallFrame | RespondFrame | ErrorFrame | IterNextFrame | IterReturnFrame | IterThrowFrame;\n\nexport type FrameOps = Frame[0];\ntype FrameArgs<K extends FrameOps> = Extract<Frame, [op: K, id: ID, ...any[]]> extends [K, any, ...infer R] ? R : never;\ntype FrameIDAndArgs<K extends FrameOps> = Extract<Frame, [op: K, ...any[]]> extends [K, ...infer R] ? R : never;\n\nexport const Errors = [\n { code: 0, error: `${Keyword}: Remote error` },\n { code: 1, error: `${Keyword}: No remote assigned` },\n { code: 2, error: `${Keyword}: Disconnected` },\n { code: 3, error: `${Keyword}: Protocol violation` },\n { code: 4, error: `${Keyword}: Function not found` },\n { code: 5, error: `${Keyword}: Expired or invalid` },\n { code: 6, error: `${Keyword}: Rejected` },\n] as const;\n\nexport const ErrorGeneric = Errors[0];\nexport const ErrorNoRemote = Errors[1];\nexport const ErrorDisconnected = Errors[2];\nexport const ErrorProtocolViolation = Errors[3];\nexport const ErrorFunctionNotFound = Errors[4];\nexport const ErrorExpiredOrInvalid = Errors[5];\nexport const ErrorRejected = Errors[6];\n\ntype ErrorTypes = typeof Errors[number];\n\n/** Codec for serializing frames to/from wire format. */\nexport type WireCodec = {\n type?: 'text' | 'binary';\n messageToWire: (message: any[]) => string | Uint8Array;\n messageFromWire: (wire: string | Uint8Array) => any[];\n}\n\nexport type BasicDescription = { [key: string]: BasicValue; };\nexport type BasicValue =\n | string | number | boolean | null | undefined\n | ((...args: any[]) => Promise<any>)\n | ((...args: any[]) => AsyncGenerator<any, any, any>)\n | BasicDescription\n | BasicValue[]\n ;;\n\nexport type DescriptionValue<T> =\n [T] extends [(string | number | boolean | null | undefined)] ? T\n // strip context from functions in descriptions, since context is only relevant for in-flight operations, not for the remote's description of its API.\n //: typeof CallContextSymbol extends keyof T ? DescriptionValue<T[typeof CallContextSymbol]>\n : [T] extends [readonly (infer U)[]] ? DescriptionValue<U>[]\n : [T] extends [object] ? Description<T>\n : [T] extends [(...args: infer A extends any[]) => Promise<infer R>] ? (...args: A) => Promise<R>\n : [T] extends [(...args: infer A extends any[]) => AsyncGenerator<infer Y, infer R, infer N>] ? (...args: A) => AsyncGenerator<Y, R, N>\n : never\n ;\n\n\n\n/** Infers concrete types for functions within a description. */\nexport type Description<T> = { [K in keyof T]: DescriptionValue<T[K]>; };\n\nexport type PeerEvents<RemoteAPI> = {\n readyStateChange: (readyState: ReadyState) => void;\n describe: (description: Description<RemoteAPI>) => void;\n error: (err: Error) => void;\n send: (frame: Frame) => void;\n message: (frame: Frame) => void;\n};\n\n/** Transport-level connection to a remote peer. */\nexport type Connection = {\n /** Send a frame to the remote. */\n send: (frame: Frame) => void;\n /** Close the connection and clean up resources. */\n close: (err?: any) => void;\n}\n\n/** Adapter interface for middleware or peers */\nexport type AdapterNext = {\n session: Session;\n handleMessage: Peer[\"handleMessage\"];\n close: Peer[\"close\"];\n};\n\nexport type Adapter = (peer: Peer) => Promise<Connection>;\n\nexport type PeerOptions<LocalAPI extends BasicDescription> = {\n /** Initial description sent to the remote on connect. */\n description?: LocalAPI,\n /** Send full error messages to remote. Default: false. */\n sendErrorMessages?: boolean,\n /** Accept full error messages from remote. Default: false. */\n receiveErrorMessages?: boolean,\n session?: Session;\n};\n\n/** Represents a peer in the network. */\nexport type Peer<RemoteAPI extends BasicDescription = any, LocalAPI extends BasicDescription = any> = {\n session: Session;\n /** Send a frame to the remote peer. */\n send(...frame: any[]): void;\n /** Emit an event to local listeners. */\n emit(key: string, ...args: any[]): void;\n /** Handle an incoming message frame from the remote peer. */\n handleMessage(frame: Frame): void;\n /** Whether to send full error messages to remote. */\n sendErrorMessages?: boolean;\n /** Whether to accept full error messages from remote. */\n receiveErrorMessages?: boolean;\n /** Register an event listener. */\n on: <K extends keyof PeerEvents<RemoteAPI>>(key: K, listener: PeerEvents<RemoteAPI>[K]) => () => void;\n /** Remove an event listener. */\n off: <K extends keyof PeerEvents<RemoteAPI>>(key: K, listener: PeerEvents<RemoteAPI>[K]) => void;\n /** Connect to remote, describe local state, optionally wait for remote description. */\n connect(connect: Adapter, waitForRemoteDescribe?: boolean): Promise<void>,\n /** Remote's described state, with functions replaced by invokers. */\n remote?: Description<RemoteAPI>,\n /** Describe local state to remote. Accepts an object or an updater function. */\n describe: (stateChange: DescribeCallback<Description<LocalAPI>>) => Promise<void>;\n /** Close connection and clean up. Peer can reconnect after closing. */\n close(ex?: any): void;\n /** Copy of the most recently described local state. */\n local?: Description<LocalAPI>;\n /**\n * - `0` STATE_DISCONNECTED: The peer is not connected to any remote.\n * - `1` STATE_CONNECTING: The peer is currently connecting to a new remote.\n * - `2` STATE_CONNECTED: The peer is connected to a remote, but is not yet ready to use.\n * - `3` STATE_LOCAL_DESCRIBED: The peer has described itself, but not received a description.\n * - `4` STATE_REMOTE_DESCRIBED: The peer has received a description, but not described itself.\n * - `5` STATE_READY: The peer is ready to both send and receive messages.\n */\n readyState: ReadyState;\n /** Current remote connection, if any. */\n connection?: Connection;\n get ready(): boolean;\n};\n\ntype EventEmitter<T> = {\n on: <K extends keyof T>(key: K, listener: T[K]) => () => void;\n off: <K extends keyof T>(key: K, listener: T[K]) => void;\n}\n\n/** Create a new event emitter instance. */\nexport function createEventEmitter() {\n const events: Record<string, Set<(...args: any[]) => void>> = {};\n\n function on(key: string, listener: (...args: any[]) => void) {\n if (!events[key]) events[key] = new Set();\n events[key].add(listener);\n return () => off(key, listener);\n }\n\n function emit(key: string, ...args: any[]) {\n if (events[key]) {\n const listeners = Array.from(events[key]);\n for (const listener of listeners) {\n try { listener(...args); }\n catch (ex) {\n if (key !== 'error') emit('error', ex instanceof Error ? ex : new Error(String(ex)));\n }\n }\n return;\n }\n if (key === 'error') {\n console.error(`${Keyword} Unhandled error:`, ...args);\n }\n }\n\n function off(key: string, listener: (...args: any[]) => void) {\n if (events[key]) {\n events[key].delete(listener);\n if (events[key].size === 0) {\n delete events[key];\n }\n }\n }\n\n return { on, emit, off };\n}\n\n/** Either a full state object, or a state updater function. */\ntype DescribeCallback<T> = T | ((current: T) => T);\n\n/** Events emitted by a Describer instance. */\ntype DescriberEvents<T> = {\n /** Emitted when the state changes. */\n change: (description: Description<T>, previous: Description<T>, swap?: boolean) => void;\n};\n\n/** A Describer instance manages state and emits events when the state changes. */\ntype Describer<T> = EventEmitter<DescriberEvents<T>> & {\n /** Get the complete current state. */\n currentState(): T;\n /** Describe a new state change. */\n describe: (stateChange: DescribeCallback<T>) => [prevState: T, newState: T, swap: boolean];\n};\n\n/** Create a new Describer instance, which holds state and emits events when state changes. */\nexport function createDescription<T>(initialState: T): Describer<T> {\n let state = initialState;\n const events = createEventEmitter();\n let result: Describer<T> = {\n currentState() { return state; },\n off: events.off,\n on: events.on,\n describe(stateChange) {\n const prev = state;\n let newState = prev;\n let swapped = true;\n if (typeof stateChange === 'function') {\n newState = (stateChange as ((current: T) => T))(prev);\n swapped = false;\n } else {\n newState = stateChange;\n }\n state = newState;\n if (newState !== prev) {\n events.emit('change', newState, prev, swapped);\n }\n return [prev, newState, swapped] as const;\n }\n };\n return result;\n}\n\n\n/** Create a new disconnected peer instance. */\nexport function createPeer<\n RemoteAPI extends BasicDescription = any,\n LocalAPI extends BasicDescription = any\n>(opts?: PeerOptions<LocalAPI>): Peer<RemoteAPI, LocalAPI> {\n const publicEmitter = createEventEmitter();\n\n const session = opts?.session ?? createSession();\n const peer: Peer<RemoteAPI, LocalAPI> = {\n readyState: STATE_DISCONNECTED,\n session: session,\n emit: publicEmitter.emit,\n on: publicEmitter.on,\n off: publicEmitter.off,\n send: sendRawMessage,\n get ready() { return peer.readyState === STATE_READY; },\n close,\n describe,\n connect,\n sendErrorMessages: opts?.sendErrorMessages ?? false,\n receiveErrorMessages: opts?.receiveErrorMessages ?? false,\n connection: undefined,\n handleMessage: handleMessage,\n };\n peer.remote = session.remoteDescription ? fromCodecDescription(peer, session.remoteDescription) : peer.remote;\n if (opts?.description) peer.local = opts.description as Description<LocalAPI>;\n\n const describer = createDescription<Description<LocalAPI> | undefined>(peer.local);\n\n async function describe(stateChange: DescribeCallback<Description<LocalAPI>>) {\n const [prevState, newState, swap] = describer.describe(stateChange as any);\n peer.local = newState;\n if (peer.readyState < STATE_CONNECTED) return; // not connected, can't send.\n peer.session.localDescription = toCodecDescription(newState);\n const diff = swap ? (newState ?? {}) : diffDescriptions(prevState ?? {}, newState ?? {});\n if (diff === null) return; // unchanged, don't send.\n const encoded = toCodecDescription(diff);\n try {\n await sendAndWait(peer, OpDescribe, encoded, swap || undefined);\n } catch (ex) {\n // we can't safely roll back a describe — drop the connection on failure.\n close(new OperationError(ErrorProtocolViolation));\n throw ex;\n }\n if (peer.readyState === STATE_REMOTE_DESCRIBED) {\n peer.readyState = STATE_READY;\n } else if (peer.readyState < STATE_LOCAL_DESCRIBED) {\n peer.readyState = STATE_LOCAL_DESCRIBED;\n }\n peer.emit('readyStateChange', peer.readyState);\n };\n\n async function connect(newConnection: Adapter, waitForRemoteDescribe: boolean = true) {\n close(null);\n let previousLocal = peer.local;\n peer.readyState = STATE_CONNECTING;\n let previousConnection = peer.connection;\n const connection = await newConnection(peer);\n if ((peer.connection !== previousConnection) || (peer.readyState !== STATE_CONNECTING)) {\n connection.close();\n // If connection was already established or peer was closed during connection,\n // close the new connection and do not assign it.\n return;\n }\n peer.connection = connection;\n peer.local = previousLocal ?? (opts?.description as Description<LocalAPI> | undefined);\n peer.readyState = STATE_CONNECTED;\n peer.emit('readyStateChange', peer.readyState);\n if (peer.local) {\n await describe(peer.local);\n }\n if (waitForRemoteDescribe !== false) {\n await waitUntilRemoteReady(peer);\n }\n }\n\n function close(err: any) {\n if (peer.readyState === STATE_DISCONNECTED) return;\n peer.readyState = STATE_DISCONNECTED;\n peer.emit('readyStateChange', peer.readyState);\n if (peer.connection) {\n peer.connection.close(err);\n }\n }\n\n function sendRawMessage<K extends FrameOps>(type: K, ...message: FrameIDAndArgs<K>) {\n if (!peer.connection) throw new OperationError(ErrorNoRemote);\n const msg = [type, ...message];\n peer.connection.send(msg as any);\n peer.emit('send', msg);\n }\n\n function handleMessage(msg: Frame) {\n peer.emit('message', msg);\n handleIncomingMessage(peer, msg).catch(ex => {\n peer.emit('error', ex instanceof Error ? ex : new Error(String(ex)));\n })\n }\n\n return peer;\n};\n\n/** Resolves when remote has described itself. Rejects on disconnect. */\nexport function waitUntilRemoteReady(peer: Peer) {\n return new Promise<void>(function (resolve, reject) {\n if (peer.readyState >= STATE_REMOTE_DESCRIBED) return resolve();\n const cleanup = peer.on('readyStateChange', readyStateChange);\n function readyStateChange(readyState: ReadyState) {\n if (readyState >= STATE_REMOTE_DESCRIBED) {\n cleanup();\n resolve();\n }\n if (readyState === STATE_DISCONNECTED) {\n cleanup();\n reject(new OperationError(ErrorDisconnected));\n }\n }\n });\n}\n\n/** Converts a local description to wire-safe codec format (functions → sentinel symbols). */\nexport function toCodecDescription(description: any): any {\n const seen = new WeakSet();\n function replacer(v: any): any {\n const value = v?.[CallContextSymbol] ?? v;\n if (isAsyncGeneratorLike(value)) {\n return { [Keyword]: AsyncGenKey };\n }\n if (typeof value === 'function') {\n return { [Keyword]: AsyncFnKey };\n }\n if (value && typeof value === 'object') {\n if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) {\n throw new OperationError(ErrorProtocolViolation);\n }\n const result: any = Array.isArray(value) ? [] : {};\n if (seen.has(value)) {\n throw new OperationError(ErrorProtocolViolation);\n }\n seen.add(value);\n for (const key of Object.keys(value)) {\n if (key === Keyword) throw new OperationError(ErrorProtocolViolation);\n result[key] = replacer(value[key]);\n }\n return result;\n }\n return value;\n }\n const result = replacer(description ?? {});\n return result;\n}\n\n/** Converts a wire-format description into a usable object (sentinel symbols → invoker functions). */\nexport function fromCodecDescription(peer: Peer, description: any): any {\n const seen = new WeakSet();\n function replacer(value: any, currentPath: string[] = []): any {\n if (value?.[Keyword] === AsyncGenKey) return createAsyncGeneratorFunction(peer, currentPath);\n if (value?.[Keyword] === AsyncFnKey) return createAsyncFunction(peer, currentPath);\n if (typeof value === 'function') {\n throw new OperationError(ErrorProtocolViolation);\n }\n if (value && typeof value === 'object') {\n if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) {\n throw new OperationError(ErrorProtocolViolation);\n }\n if (seen.has(value)) {\n throw new OperationError(ErrorProtocolViolation);\n }\n seen.add(value);\n const result: any = Array.isArray(value) ? [] : {};\n for (const key of Object.keys(value)) {\n result[key] = replacer(value[key], [...currentPath, key]);\n }\n return result;\n }\n return value;\n }\n const result = replacer(description ?? {}) as BasicDescription;\n return result;\n}\n\nconst AsyncGeneratorFunction: any = (async function* () { });\n\n/** Creates a local async generator that proxies iteration to the remote. */\nexport function createAsyncGeneratorFunction(peer: Peer, name: string[]) {\n function wrappedAsyncGeneratorFunction(...args: any[]): AsyncGenerator<any, any, any> {\n let _operationId: ID | null = null;\n let closed = false;\n function wrapped<T>(fn: (value: any) => Promise<T>) {\n return (value: any) => {\n if (closed) return { value: undefined, done: true };\n try {\n return fn(value).catch(handleError);\n } catch (err) {\n handleError(err);\n throw err;\n }\n }\n function handleError(err: any) {\n if (_operationId && !closed) {\n const error = safeSendError(peer, err);\n sendAndWait(peer, OpIterThrow, _operationId, error.code, error.error).catch(() => { });\n }\n closed = true;\n throw err;\n }\n }\n\n const nexter = wrapped(async sendValue => {\n const [value, done] = await sendAndWait(peer, OpIterNext, await operationId(), sendValue);\n if (done) closed = true;\n return { value, done: !!done };\n });\n\n const thrower = wrapped(async err => {\n const error = safeSendError(peer, err);\n const [value, done] = await sendAndWait(peer, OpIterThrow, await operationId(), error.code, error.error);\n if (done) closed = true;\n return { value, done: !!done };\n });\n\n const returner = wrapped(async value => {\n closed = true;\n await sendAndWait(peer, OpIterReturn, await operationId(), value).catch(() => { });\n return { value, done: true };\n });\n\n let iterator = {\n [Symbol.asyncIterator]() { return this; },\n next: nexter,\n throw: thrower,\n return: returner\n };\n\n async function operationId() {\n if (_operationId || closed) return _operationId;\n try {\n return _operationId = await sendAndWait(peer, OpCall, name, args);\n } catch (err: any) {\n closed = true;\n throw err;\n }\n }\n\n return iterator as any;\n };\n\n return markAsAsyncGenerator(wrappedAsyncGeneratorFunction);\n}\n\n/** Marks a function as an async generator, setting the appropriate properties. */\nexport function markAsAsyncGenerator<T>(wrappedAsyncGeneratorFunction: T): T {\n Object.defineProperties(wrappedAsyncGeneratorFunction, {\n [Symbol.toStringTag]: { value: AsyncGeneratorFunction[Symbol.toStringTag], writable: true },\n prototype: { value: AsyncGeneratorFunction.prototype, writable: true },\n constructor: { value: AsyncGeneratorFunction.constructor, writable: true }\n });\n return wrappedAsyncGeneratorFunction;\n}\n\n\n/** Sanitizes an error for sending, respecting sendErrorMessages policy. */\nfunction safeSendError(peer: Peer, error: OperationError | { message?: string, code?: number } | string) {\n const code = typeof error === 'string' ? ErrorGeneric.code : (error.code ?? ErrorGeneric.code);\n if (!peer.sendErrorMessages) {\n return { code, error: (Errors[code] ?? ErrorGeneric).error };\n }\n if (typeof error === 'object') {\n return { code: error.code ?? 0, error: error.message };\n }\n if (typeof error === 'string') {\n return { code: ErrorGeneric.code, error };\n }\n return ErrorGeneric;\n}\n\n/** Sanitizes a received error, respecting receiveErrorMessages policy. */\nfunction safeReceiveError(peer: Peer, error: OperationError | { message?: string, code?: number } | string): OperationError {\n let code = typeof error === 'string' ? ErrorGeneric.code : (error.code ?? ErrorGeneric.code);\n if (peer.receiveErrorMessages) {\n const message = typeof error === 'string' ? error : (error.message ?? Errors[code]?.error ?? ErrorGeneric.error);\n return new OperationError(message, code);\n }\n return new OperationError((Errors[code] ?? ErrorGeneric).error, code);\n}\n\n/** Creates a local async function that proxies calls to the remote. */\nexport function createAsyncFunction(peer: Peer, name: string[], waitForPeer: boolean = true) {\n return async function wrappedAsyncFunction(...args: any[]): Promise<any> {\n if (waitForPeer) await waitUntilRemoteReady(peer);\n return await sendAndWait(peer, OpCall, name, args);\n }\n};\n\n/** Sends a frame and returns a promise that resolves when the remote responds. */\nfunction sendAndWait<K extends FrameOps>(peer: Peer, type: K, ...message: FrameArgs<K>): Promise<any> {\n return new Promise<any>(function (resolve, reject) {\n if (!peer.connection) return reject(new OperationError(ErrorNoRemote));\n let operation: OperationOutboundCall | undefined;\n try {\n operation = peer.session.add('outbound-call', { resolve, reject }, reject);\n peer.send(type, operation.id, ...message);\n } catch (ex: any) {\n operation?.cleanup();\n reject(ex);\n }\n });\n}\n\nconst messageHandler: { [K in FrameOps]: (peer: Peer, session: Session, ...data: FrameIDAndArgs<K>) => (ErrorTypes | void) | Promise<ErrorTypes | void> } = {\n async [OpDescribe](peer, _session, id, description, swap) {\n if (typeof description !== 'object' || description === null || Array.isArray(description) || (swap !== undefined && swap !== null && typeof swap !== 'boolean')) {\n throw new OperationError(ErrorProtocolViolation);\n }\n const mapped = fromCodecDescription(peer, description);\n peer.remote = { ...(swap ? mapped : mergeDescriptions(peer.remote, mapped)) };\n peer.session.remoteDescription = toCodecDescription(peer.remote);\n let prevReadyState = peer.readyState;\n if (peer.readyState === STATE_LOCAL_DESCRIBED) {\n peer.readyState = STATE_READY;\n } else if (peer.readyState < STATE_REMOTE_DESCRIBED) {\n peer.readyState = STATE_REMOTE_DESCRIBED;\n }\n if (prevReadyState !== peer.readyState) {\n peer.emit('readyStateChange', peer.readyState);\n }\n peer.emit('describe', peer.remote);\n peer.send(OpOK, id);\n },\n async [OpCall](peer, session, id, name, args) {\n if (!Array.isArray(name) || !Array.isArray(args)) {\n throw new OperationError(ErrorProtocolViolation);\n }\n await handleInvocation(peer, session, id, name, args);\n },\n [OpOK](_peer, session, id, result) {\n const operation = session.use('outbound-call', id);\n if (!operation) return;\n operation.cleanup();\n operation.context.resolve(result);\n },\n [OpError](peer, session, id, code, error) {\n if (typeof code !== 'number') {\n // Invalid error frame — shut down to avoid error loops.\n peer.close();\n return;\n }\n const errorObj = safeReceiveError(peer, { code, message: error });\n const operation = session.use(undefined, id);\n if (!operation) return;\n operation.reject(errorObj);\n },\n async [OpIterNext](peer, session, id, operationId, value) {\n return await withGenerator(peer, session, id, operationId, async (operation) => {\n const result = await operation.context.generator!.next(value);\n if (result.done) operation.cleanup();\n return [result.value, result.done ? 1 : 0];\n });\n },\n async [OpIterReturn](peer, session, id, operationId, value) {\n return await withGenerator(peer, session, id, operationId, async (operation) => {\n const asyncGenerator = operation.context.generator;\n operation.cleanup();\n const result = await asyncGenerator!.return(value);\n return [result.value, result.done ? 1 : 0];\n }, false);\n },\n async [OpIterThrow](peer, session, id, operationId, code, error) {\n if (typeof code !== 'number' || (error !== undefined && typeof error !== 'string')) {\n throw new OperationError(ErrorProtocolViolation);\n }\n return await withGenerator(peer, session, id, operationId, async (operation) => {\n const err = safeReceiveError(peer, { code, message: error });\n const result = await operation.context.generator!.throw(err);\n if (result.done) operation.cleanup();\n return [result.value, result.done ? 1 : 0];\n });\n }\n}\n\n/** Executes an operation on an in-flight generator with protocol validation. */\nasync function withGenerator(peer: Peer, session: Session, id: ID, operationId: ID, fn: (operation: OperationGenerator) => Promise<any>, preventReentry: boolean = true) {\n if (!isValidID(operationId)) throw new OperationError(ErrorProtocolViolation);\n const operation = session.use('generator', operationId);\n if (!operation) throw new OperationError(ErrorExpiredOrInvalid);\n if (!exists()) {\n const err = new OperationError(ErrorFunctionNotFound);\n operation.reject(err);\n throw err;\n }\n if (operation.context.busy && preventReentry) {\n throw new OperationError(ErrorProtocolViolation);\n }\n try {\n operation.context.busy = true;\n const result = await fn(operation);\n if (!exists()) {\n operation.reject(new OperationError(ErrorFunctionNotFound));\n return peer.send(OpOK, id, [undefined, 1]);\n }\n else peer.send(OpOK, id, result);\n } catch (ex: any) {\n operation.cleanup();\n sendError(peer, id, ex?.code, ex);\n throw ex;\n } finally {\n operation.context.busy = false;\n }\n\n function exists() {\n const found = lookupFunction(peer.local, operation!.context.name);\n return found === operation?.context.target;\n }\n}\n\nfunction sendError(peer: Peer, id: ID, inCode: number, error?: any) {\n const str = error?.error ?? error?.message ?? error;\n const code = (typeof error === 'object' && typeof error.code === 'number' ? error.code : inCode) ?? ErrorGeneric.code;\n if (peer.readyState >= STATE_CONNECTED) {\n const sanitized = safeSendError(peer, { code, message: str });\n peer.send(OpError, id, sanitized.code, sanitized.error);\n return;\n }\n if (code !== ErrorNoRemote.code) {\n peer.emit('error', new OperationError(String(str ?? Errors[code]?.error ?? ErrorGeneric.error), code));\n }\n}\n\n/** Routes an incoming frame to the appropriate handler. */\nasync function handleIncomingMessage(peer: Peer, data: Frame) {\n if (!Array.isArray(data) || typeof data[0] !== 'string' || data[0].length !== 1) {\n return;\n }\n\n if (!isValidID(data[1])) throw new OperationError(ErrorProtocolViolation);\n\n const handler = messageHandler[data[0] as FrameOps];\n if (!handler) return;\n\n try {\n return await handler(peer, peer.session, ...data.slice(1) as FrameIDAndArgs<typeof data[0]>);\n } catch (err: any) {\n if (data[0] === OpError) {\n // Don't respond to invalid errors — avoids loops.\n peer.emit('error', err);\n return;\n }\n const error = safeSendError(peer, err);\n try {\n peer.send(OpError, data[1], error.code, error.error);\n } catch { }\n throw err;\n }\n}\n\n/** Resolves a dotted function path against a description object. */\nfunction lookupFunction(origin: Description<any> | undefined, name: string[]): any {\n if (origin === undefined || origin === null) return null;\n let target: any = origin;\n for (let i = 0; target && i < name.length; ++i) {\n if (Object.prototype.hasOwnProperty.call(target, name[i])) {\n target = target[name[i]];\n } else {\n return null;\n }\n }\n if (typeof target !== 'function') return null;\n return target;\n}\n\n/** Context value that can be passed in to described functions */\nexport type CallContext = { peer: Peer, id: ID, operation: OperationTypes };\ntype HasContext<T> = { [CallContextSymbol]: T };\ntype RemoveFirstParameter<T> = T extends (first: CallContext, ...args: infer U) => infer R ? (...args: U) => R : never;\n/** Wraps a function to automatically provide a call context. */\nexport function withContext<T extends Function>(fn: T): RemoveFirstParameter<T> | HasContext<RemoveFirstParameter<T>> {\n const fail = () => { throw new Error(\"withContext functions cannot be wrapped.\"); };\n (fail as any)[CallContextSymbol] = fn;\n return fail as any;\n}\n\n/** Handles an incoming RPC call or generator creation. */\nasync function handleInvocation(peer: Peer, session: Session, id: ID, name: string[], args: any[]) {\n let operation: OperationTypes | undefined = undefined;\n try {\n let target = lookupFunction(peer.local, name);\n if (!target || typeof target !== 'function') {\n throw new OperationError(ErrorFunctionNotFound);\n }\n const cctx: any = { peer, id };\n let callArgs = args;\n if (CallContextSymbol in target) {\n callArgs = [cctx, ...args];\n target = target[CallContextSymbol];\n }\n\n let complete = false;\n if (isAsyncGeneratorLike(target)) {\n // async generator fn\n let context: OperationGenerator['context'] = { target, name };\n operation = session.add('generator', context, function (_err) {\n if (complete || !context.generator) return;\n complete = true;\n context.generator.return(undefined).catch(() => { });\n });\n cctx.operation = operation;\n if (!operation) return peer.send(OpError, id, ErrorRejected.code, ErrorRejected.error);\n context.generator = target(...callArgs);\n peer.send(OpOK, id, operation.id);\n } else {\n // plain async fn\n operation = session.add('inbound-call', undefined, (err) => {\n if (complete) return;\n complete = true;\n try {\n sendError(peer, id, err?.code ?? ErrorGeneric.code, err)\n } catch (ex) { }\n });\n cctx.operation = operation;\n if (!operation) return peer.send(OpError, id, ErrorRejected.code, ErrorRejected.error);\n const result = await Promise.resolve().then(() => target(...callArgs));\n if (complete) return;\n complete = true;\n operation.cleanup();\n if (id) peer.send(OpOK, id, result);\n }\n } catch (ex: any) {\n if (operation) {\n operation.cleanup();\n }\n sendError(peer, id, ex?.code ?? ErrorGeneric.code, ex);\n throw ex;\n }\n}\n\nexport class OperationError extends Error {\n code: number;\n constructor(ex: ErrorTypes | string, code?: number) {\n if (typeof ex === 'string') {\n super(ex);\n this.code = code ?? ErrorGeneric.code;\n } else {\n super(ex.error);\n this.code = code ?? ex.code;\n }\n }\n}\n\nexport function isAsyncGeneratorLike(value: any): boolean {\n if (typeof value !== 'function') return false;\n if (value.constructor?.name === 'AsyncGeneratorFunction') return true;\n if (value.prototype?.[Symbol.asyncIterator]) return true; // bun compat\n return false;\n}\n\n/** Returns a shallow diff of two descriptions, or null if unchanged. */\nfunction diffDescriptions(prev: { [key: string]: any }, next: { [key: string]: any }): object | null {\n const stack = [{ prev: prev as any, next: next as any, path: [] as string[] }];\n const diffResult: any = {};\n let changed = false;\n while (stack.length > 0) {\n const { prev, next, path } = stack.pop()!;\n if (prev === next) continue;\n if (typeof prev === 'function' && typeof next === 'function' && isAsyncGeneratorLike(prev) === isAsyncGeneratorLike(next)) {\n continue; // Same-shaped functions don't need re-describing.\n } else if (Array.isArray(prev) && Array.isArray(next)) {\n if (prev.length !== next.length) {\n changed = true;\n addChange(next);\n } else if (prev.some((item, index) => item !== next[index])) {\n changed = true;\n addChange(next);\n }\n } else if (typeof prev === 'object' && typeof next === 'object' && prev !== null && next !== null) {\n const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);\n for (const key of allKeys) stack.push({ prev: prev[key], next: next[key], path: [...path, key] });\n } else {\n changed = true;\n addChange(next);\n }\n function addChange(next: any) {\n let current = diffResult;\n for (let i = 0; i < path.length - 1; ++i) {\n if (!(path[i] in current)) {\n current[path[i]] = {};\n }\n current = current[path[i]];\n }\n current[path[path.length - 1]] = next ?? null;\n }\n }\n if (!changed) return null;\n return diffResult;\n}\n\n/** Deep-merges a patch into a description. Null values delete keys. */\nexport function mergeDescriptions(original: any, patch: any): any {\n const result = { ...original };\n for (const [key, value] of Object.entries(patch)) {\n if (value === null || value === undefined) {\n delete result[key];\n } else if (Array.isArray(value) || Array.isArray(result[key])) {\n result[key] = value;\n } else if (typeof value === 'object' && value !== null && typeof result[key] === 'object' && result[key] !== null) {\n result[key] = mergeDescriptions(result[key], value);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction isValidID(id: any): id is ID { return typeof id === 'string' && id.length > 0 && id.length < MAX_ID_LENGTH; }\n"],"mappings":"8CAMA,MAEa,EAAU,UACvB,IAAW,EAAoB,OAAO,eAAe,CAIrD,MAAa,EAAa,IACb,EAAc,IAEd,EAAqB,EACrB,EAAmB,EACnB,EAAkB,EAClB,EAAwB,EACxB,EAAyB,EACzB,EAAc,EAId,EAAa,IACb,EAAS,IACT,EAAO,IACP,EAAU,IACV,EAAa,IACb,EAAe,IACf,EAAc,IAed,EAAS,CAClB,CAAE,KAAM,EAAG,MAAO,GAAG,EAAQ,gBAAiB,CAC9C,CAAE,KAAM,EAAG,MAAO,GAAG,EAAQ,sBAAuB,CACpD,CAAE,KAAM,EAAG,MAAO,GAAG,EAAQ,gBAAiB,CAC9C,CAAE,KAAM,EAAG,MAAO,GAAG,EAAQ,sBAAuB,CACpD,CAAE,KAAM,EAAG,MAAO,GAAG,EAAQ,sBAAuB,CACpD,CAAE,KAAM,EAAG,MAAO,GAAG,EAAQ,sBAAuB,CACpD,CAAE,KAAM,EAAG,MAAO,GAAG,EAAQ,YAAa,CAC7C,CAEY,EAAe,EAAO,GACtB,EAAgB,EAAO,GACvB,EAAoB,EAAO,GAC3B,EAAyB,EAAO,GAChC,EAAwB,EAAO,GAC/B,EAAwB,EAAO,GAC/B,EAAgB,EAAO,GAsHpC,SAAgB,GAAqB,CACjC,IAAM,EAAwD,EAAE,CAEhE,SAAS,EAAG,EAAa,EAAoC,CAGzD,OAFK,EAAO,KAAM,EAAO,GAAO,IAAI,KACpC,EAAO,GAAK,IAAI,EAAS,KACZ,E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AS,UAAY,IAAS,MAAQ,IAAS,KAAM,CAC/F,IAAM,EAAU,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,EAAK,CAAE,GAAG,OAAO,KAAK,EAAK,CAAC,CAAC,CACrE,IAAK,IAAM,KAAO,EAAS,EAAM,KAAK,CAAE,KAAM,EAAK,GAAM,KAAM,EAAK,GAAM,KAAM,CAAC,GAAG,EAAM,EAAI,CAAE,CAAC,MAEjG,EAAU,GACV,EAAU,EAAK,CAEnB,SAAS,EAAU,EAAW,CAC1B,IAAI,EAAU,EACd,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,OAAS,EAAG,EAAE,EAC7B,EAAK,KAAM,IACb,EAAQ,EAAK,IAAM,EAAE,EAEzB,EAAU,EAAQ,EAAK,IAE3B,EAAQ,EAAK,EAAK,OAAS,IAAM,GAAQ,MAIjD,OADK,EACE,EADc,KAKzB,SAAgB,EAAkB,EAAe,EAAiB,CAC9D,IAAM,EAAS,CAAE,GAAG,EAAU,CAC9B,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,EAAM,CACxC,GAAU,KACV,OAAO,EAAO,GACP,MAAM,QAAQ,EAAM,EAAI,MAAM,QAAQ,EAAO,GAAK,CACzD,EAAO,GAAO,EACP,OAAO,GAAU,UAAY,GAAkB,OAAO,EAAO,IAAS,UAAY,EAAO,KAAS,KACzG,EAAO,GAAO,EAAkB,EAAO,GAAM,EAAM,CAEnD,EAAO,GAAO,EAGtB,OAAO,EAGX,SAAS,EAAU,EAAmB,CAAE,OAAO,OAAO,GAAO,UAAY,EAAG,OAAS,GAAK,EAAG,OAAS"}
|
|
1
|
+
{"version":3,"file":"psionic.mjs","names":[],"sources":["../src/psionic.ts"],"sourcesContent":["/**\n * Psionic - Live-updating, cross-language, bidirectional RPC protocol.\n */\n\nimport { type ID, type OperationGenerator, type Session, type OperationTypes, type OperationOutboundCall, createSession } from \"./session\";\n\nconst MAX_ID_LENGTH = 0x40;\n\nexport const Keyword = '@@psion' as const;\nexport let CallContextSymbol = Symbol('call-context');\n\n// Sentinels for function types in codec format.\n// WireCodec converts these to/from wire-safe representations.\nexport const AsyncFnKey = 'f';\nexport const AsyncGenKey = 'g';\n\nexport const STATE_DISCONNECTED = 0 as const;\nexport const STATE_CONNECTING = 1 as const;\nexport const STATE_CONNECTED = 2 as const;\nexport const STATE_LOCAL_DESCRIBED = 3 as const;\nexport const STATE_REMOTE_DESCRIBED = 4 as const;\nexport const STATE_READY = 5 as const;\n\nexport type ReadyState = typeof STATE_DISCONNECTED | typeof STATE_CONNECTING | typeof STATE_CONNECTED | typeof STATE_LOCAL_DESCRIBED | typeof STATE_REMOTE_DESCRIBED | typeof STATE_READY;\n\nexport const OpDescribe = 'D' as const;\nexport const OpCall = 'C' as const;\nexport const OpOK = 'K' as const;\nexport const OpError = 'E' as const;\nexport const OpIterNext = '.' as const;\nexport const OpIterReturn = '<' as const;\nexport const OpIterThrow = '>' as const;\n\nexport type CallFrame = [type: typeof OpCall, id: ID, name: string[], args: any[]];\nexport type DescribeFrame = [type: typeof OpDescribe, id: ID, description: any, swap?: boolean];\nexport type RespondFrame = [type: typeof OpOK, id: ID, result: any];\nexport type ErrorFrame = [type: typeof OpError, id: ID, code: number, error?: string];\nexport type IterNextFrame = [type: typeof OpIterNext, id: ID, operationId: ID, value: any];\nexport type IterReturnFrame = [type: typeof OpIterReturn, id: ID, operationId: ID, value: any];\nexport type IterThrowFrame = [type: typeof OpIterThrow, id: ID, operationId: ID, code: number, error?: string];\nexport type Frame = DescribeFrame | CallFrame | RespondFrame | ErrorFrame | IterNextFrame | IterReturnFrame | IterThrowFrame;\n\nexport type FrameOps = Frame[0];\ntype FrameArgs<K extends FrameOps> = Extract<Frame, [op: K, id: ID, ...any[]]> extends [K, any, ...infer R] ? R : never;\ntype FrameIDAndArgs<K extends FrameOps> = Extract<Frame, [op: K, ...any[]]> extends [K, ...infer R] ? R : never;\n\nexport const Errors = [\n { code: 0, error: `${Keyword}: Remote error` },\n { code: 1, error: `${Keyword}: No remote assigned` },\n { code: 2, error: `${Keyword}: Disconnected` },\n { code: 3, error: `${Keyword}: Protocol violation` },\n { code: 4, error: `${Keyword}: Function not found` },\n { code: 5, error: `${Keyword}: Expired or invalid` },\n { code: 6, error: `${Keyword}: Rejected` },\n] as const;\n\nexport const ErrorGeneric = Errors[0];\nexport const ErrorNoRemote = Errors[1];\nexport const ErrorDisconnected = Errors[2];\nexport const ErrorProtocolViolation = Errors[3];\nexport const ErrorFunctionNotFound = Errors[4];\nexport const ErrorExpiredOrInvalid = Errors[5];\nexport const ErrorRejected = Errors[6];\n\ntype ErrorTypes = typeof Errors[number];\n\n/** Codec for serializing frames to/from wire format. */\nexport type WireCodec = {\n type?: 'text' | 'binary';\n messageToWire: (message: any[]) => string | Uint8Array;\n messageFromWire: (wire: string | Uint8Array) => any[];\n}\n\nexport type BasicDescription = { [key: string]: BasicValue; };\nexport type BasicValue =\n | string | number | boolean | null | undefined\n | ((...args: any[]) => Promise<any>)\n | ((...args: any[]) => AsyncGenerator<any, any, any>)\n | BasicDescription\n | BasicValue[]\n ;;\n\nexport type DescriptionValue<T> =\n [T] extends [(string | number | boolean | null | undefined)] ? T\n // strip context from functions in descriptions, since context is only relevant for in-flight operations, not for the remote's description of its API.\n //: typeof CallContextSymbol extends keyof T ? DescriptionValue<T[typeof CallContextSymbol]>\n : [T] extends [readonly (infer U)[]] ? DescriptionValue<U>[]\n : [T] extends [object] ? Description<T>\n : [T] extends [(...args: infer A extends any[]) => Promise<infer R>] ? (...args: A) => Promise<R>\n : [T] extends [(...args: infer A extends any[]) => AsyncGenerator<infer Y, infer R, infer N>] ? (...args: A) => AsyncGenerator<Y, R, N>\n : never\n ;\n\n\n\n/** Infers concrete types for functions within a description. */\nexport type Description<T> = { [K in keyof T]: DescriptionValue<T[K]>; };\n\nexport type PeerEvents<RemoteAPI> = {\n readyStateChange: (readyState: ReadyState) => void;\n describe: (description: Description<RemoteAPI>) => void;\n error: (err: Error) => void;\n send: (frame: Frame) => void;\n message: (frame: Frame) => void;\n};\n\n/** Transport-level connection to a remote peer. */\nexport type Connection = {\n /** Send a frame to the remote. */\n send: (frame: Frame) => void;\n /** Close the connection and clean up resources. */\n close: (err?: any) => void;\n}\n\n/** Adapter interface for middleware or peers */\nexport type AdapterNext = {\n session: Session;\n handleMessage: Peer[\"handleMessage\"];\n close: Peer[\"close\"];\n};\n\nexport type Adapter = (peer: Peer) => Promise<Connection>;\n\nexport type PeerOptions<LocalAPI extends BasicDescription> = {\n /** Initial description sent to the remote on connect. */\n description?: LocalAPI,\n /** Send full error messages to remote. Default: false. */\n sendErrorMessages?: boolean,\n /** Accept full error messages from remote. Default: false. */\n receiveErrorMessages?: boolean,\n session?: Session;\n};\n\n/** Represents a peer in the network. */\nexport type Peer<RemoteAPI extends BasicDescription = any, LocalAPI extends BasicDescription = any> = {\n session: Session;\n /** Send a frame to the remote peer. */\n send(...frame: any[]): void;\n /** Emit an event to local listeners. */\n emit(key: string, ...args: any[]): void;\n /** Handle an incoming message frame from the remote peer. */\n handleMessage(frame: Frame): void;\n /** Whether to send full error messages to remote. */\n sendErrorMessages?: boolean;\n /** Whether to accept full error messages from remote. */\n receiveErrorMessages?: boolean;\n /** Register an event listener. */\n on: <K extends keyof PeerEvents<RemoteAPI>>(key: K, listener: PeerEvents<RemoteAPI>[K]) => () => void;\n /** Remove an event listener. */\n off: <K extends keyof PeerEvents<RemoteAPI>>(key: K, listener: PeerEvents<RemoteAPI>[K]) => void;\n /** Connect to remote, describe local state, optionally wait for remote description. */\n connect(connect: Adapter, waitForRemoteDescribe?: boolean): Promise<void>,\n /** Remote's described state, with functions replaced by invokers. */\n remote?: Description<RemoteAPI>,\n /** Describe local state to remote. Accepts an object or an updater function. */\n describe: (stateChange: DescribeCallback<Description<LocalAPI>>) => Promise<void>;\n /** Close connection and clean up. Peer can reconnect after closing. */\n close(ex?: any): void;\n /** Copy of the most recently described local state. */\n local?: Description<LocalAPI>;\n /**\n * - `0` STATE_DISCONNECTED: The peer is not connected to any remote.\n * - `1` STATE_CONNECTING: The peer is currently connecting to a new remote.\n * - `2` STATE_CONNECTED: The peer is connected to a remote, but is not yet ready to use.\n * - `3` STATE_LOCAL_DESCRIBED: The peer has described itself, but not received a description.\n * - `4` STATE_REMOTE_DESCRIBED: The peer has received a description, but not described itself.\n * - `5` STATE_READY: The peer is ready to both send and receive messages.\n */\n readyState: ReadyState;\n /** Current remote connection, if any. */\n connection?: Connection;\n get ready(): boolean;\n};\n\ntype EventEmitter<T> = {\n on: <K extends keyof T>(key: K, listener: T[K]) => () => void;\n off: <K extends keyof T>(key: K, listener: T[K]) => void;\n}\n\n/** Create a new event emitter instance. */\nexport function createEventEmitter() {\n const events: Record<string, Set<(...args: any[]) => void>> = {};\n\n function on(key: string, listener: (...args: any[]) => void) {\n if (!events[key]) events[key] = new Set();\n events[key].add(listener);\n return () => off(key, listener);\n }\n\n function emit(key: string, ...args: any[]) {\n if (events[key]) {\n const listeners = Array.from(events[key]);\n for (const listener of listeners) {\n try { listener(...args); }\n catch (ex) {\n if (key !== 'error') emit('error', ex instanceof Error ? ex : new Error(String(ex)));\n }\n }\n return;\n }\n if (key === 'error') {\n console.error(`${Keyword} Unhandled error:`, ...args);\n }\n }\n\n function off(key: string, listener: (...args: any[]) => void) {\n if (events[key]) {\n events[key].delete(listener);\n if (events[key].size === 0) {\n delete events[key];\n }\n }\n }\n\n return { on, emit, off };\n}\n\n/** Either a full state object, or a state updater function. */\ntype DescribeCallback<T> = T | ((current: T) => T);\n\n/** Events emitted by a Describer instance. */\ntype DescriberEvents<T> = {\n /** Emitted when the state changes. */\n change: (description: Description<T>, previous: Description<T>, swap?: boolean) => void;\n};\n\n/** A Describer instance manages state and emits events when the state changes. */\ntype Describer<T> = EventEmitter<DescriberEvents<T>> & {\n /** Get the complete current state. */\n currentState(): T;\n /** Describe a new state change. */\n describe: (stateChange: DescribeCallback<T>) => [prevState: T, newState: T, swap: boolean];\n};\n\n/** Create a new Describer instance, which holds state and emits events when state changes. */\nexport function createDescription<T>(initialState: T): Describer<T> {\n let state = initialState;\n const events = createEventEmitter();\n let result: Describer<T> = {\n currentState() { return state; },\n off: events.off,\n on: events.on,\n describe(stateChange) {\n const prev = state;\n let newState = prev;\n let swapped = true;\n if (typeof stateChange === 'function') {\n newState = (stateChange as ((current: T) => T))(prev);\n swapped = false;\n } else {\n newState = stateChange;\n }\n state = newState;\n if (newState !== prev) {\n events.emit('change', newState, prev, swapped);\n }\n return [prev, newState, swapped] as const;\n }\n };\n return result;\n}\n\n\n/** Create a new disconnected peer instance. */\nexport function createPeer<\n RemoteAPI extends BasicDescription = any,\n LocalAPI extends BasicDescription = any\n>(opts?: PeerOptions<LocalAPI>): Peer<RemoteAPI, LocalAPI> {\n const publicEmitter = createEventEmitter();\n\n const session = opts?.session ?? createSession();\n const peer: Peer<RemoteAPI, LocalAPI> = {\n readyState: STATE_DISCONNECTED,\n session: session,\n emit: publicEmitter.emit,\n on: publicEmitter.on,\n off: publicEmitter.off,\n send: sendRawMessage,\n get ready() { return peer.readyState === STATE_READY; },\n close,\n describe,\n connect,\n sendErrorMessages: opts?.sendErrorMessages ?? false,\n receiveErrorMessages: opts?.receiveErrorMessages ?? false,\n connection: undefined,\n handleMessage: handleMessage,\n };\n peer.remote = session.remoteDescription ? fromCodecDescription(peer, session.remoteDescription) : peer.remote;\n if (opts?.description) peer.local = opts.description as Description<LocalAPI>;\n\n const describer = createDescription<Description<LocalAPI> | undefined>(peer.local);\n\n async function describe(stateChange: DescribeCallback<Description<LocalAPI>>) {\n const [prevState, newState, swap] = describer.describe(stateChange as any);\n peer.local = newState;\n if (peer.readyState < STATE_CONNECTED) return; // not connected, can't send.\n peer.session.localDescription = toCodecDescription(newState);\n const diff = swap ? (newState ?? {}) : diffDescriptions(prevState ?? {}, newState ?? {});\n if (diff === null) return; // unchanged, don't send.\n const encoded = toCodecDescription(diff);\n try {\n await sendAndWait(peer, OpDescribe, encoded, swap || undefined);\n } catch (ex) {\n // we can't safely roll back a describe — drop the connection on failure.\n close(new OperationError(ErrorProtocolViolation));\n throw ex;\n }\n if (peer.readyState === STATE_REMOTE_DESCRIBED) {\n peer.readyState = STATE_READY;\n } else if (peer.readyState < STATE_LOCAL_DESCRIBED) {\n peer.readyState = STATE_LOCAL_DESCRIBED;\n }\n peer.emit('readyStateChange', peer.readyState);\n };\n\n async function connect(newConnection: Adapter, waitForRemoteDescribe: boolean = true) {\n close(null);\n let previousLocal = peer.local;\n peer.readyState = STATE_CONNECTING;\n let previousConnection = peer.connection;\n const connection = await newConnection(peer);\n if ((peer.connection !== previousConnection) || (peer.readyState !== STATE_CONNECTING)) {\n connection.close();\n // If connection was already established or peer was closed during connection,\n // close the new connection and do not assign it.\n return;\n }\n peer.connection = connection;\n peer.local = previousLocal ?? (opts?.description as Description<LocalAPI> | undefined);\n peer.readyState = STATE_CONNECTED;\n peer.emit('readyStateChange', peer.readyState);\n if (peer.local) {\n await describe(peer.local);\n }\n if (waitForRemoteDescribe !== false) {\n await waitUntilRemoteReady(peer);\n }\n }\n\n function close(err: any) {\n if (peer.readyState === STATE_DISCONNECTED) return;\n peer.readyState = STATE_DISCONNECTED;\n peer.emit('readyStateChange', peer.readyState);\n if (peer.session) {\n peer.session.clear();\n }\n if (peer.connection) {\n peer.connection.close(err);\n }\n }\n\n function sendRawMessage<K extends FrameOps>(type: K, ...message: FrameIDAndArgs<K>) {\n if (!peer.connection) throw new OperationError(ErrorNoRemote);\n const msg = [type, ...message];\n peer.connection.send(msg as any);\n peer.emit('send', msg);\n }\n\n function handleMessage(msg: Frame) {\n peer.emit('message', msg);\n handleIncomingMessage(peer, msg).catch(ex => {\n peer.emit('error', ex instanceof Error ? ex : new Error(String(ex)));\n })\n }\n\n return peer;\n};\n\n/** Resolves when remote has described itself. Rejects on disconnect. */\nexport function waitUntilRemoteReady(peer: Peer) {\n return new Promise<void>(function (resolve, reject) {\n if (peer.readyState >= STATE_REMOTE_DESCRIBED) return resolve();\n const cleanup = peer.on('readyStateChange', readyStateChange);\n function readyStateChange(readyState: ReadyState) {\n if (readyState >= STATE_REMOTE_DESCRIBED) {\n cleanup();\n resolve();\n }\n if (readyState === STATE_DISCONNECTED) {\n cleanup();\n reject(new OperationError(ErrorDisconnected));\n }\n }\n });\n}\n\n/** Converts a local description to wire-safe codec format (functions → sentinel symbols). */\nexport function toCodecDescription(description: any): any {\n const seen = new WeakSet();\n function replacer(v: any): any {\n const value = v?.[CallContextSymbol] ?? v;\n if (isAsyncGeneratorLike(value)) {\n return { [Keyword]: AsyncGenKey };\n }\n if (typeof value === 'function') {\n return { [Keyword]: AsyncFnKey };\n }\n if (value && typeof value === 'object') {\n if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) {\n throw new OperationError(ErrorProtocolViolation);\n }\n const result: any = Array.isArray(value) ? [] : {};\n if (seen.has(value)) {\n throw new OperationError(ErrorProtocolViolation);\n }\n seen.add(value);\n for (const key of Object.keys(value)) {\n if (key === Keyword) throw new OperationError(ErrorProtocolViolation);\n result[key] = replacer(value[key]);\n }\n return result;\n }\n return value;\n }\n const result = replacer(description ?? {});\n return result;\n}\n\n/** Converts a wire-format description into a usable object (sentinel symbols → invoker functions). */\nexport function fromCodecDescription(peer: Peer, description: any): any {\n const seen = new WeakSet();\n function replacer(value: any, currentPath: string[] = []): any {\n if (value?.[Keyword] === AsyncGenKey) return createAsyncGeneratorFunction(peer, currentPath);\n if (value?.[Keyword] === AsyncFnKey) return createAsyncFunction(peer, currentPath);\n if (typeof value === 'function') {\n throw new OperationError(ErrorProtocolViolation);\n }\n if (value && typeof value === 'object') {\n if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) {\n throw new OperationError(ErrorProtocolViolation);\n }\n if (seen.has(value)) {\n throw new OperationError(ErrorProtocolViolation);\n }\n seen.add(value);\n const result: any = Array.isArray(value) ? [] : {};\n for (const key of Object.keys(value)) {\n result[key] = replacer(value[key], [...currentPath, key]);\n }\n return result;\n }\n return value;\n }\n const result = replacer(description ?? {}) as BasicDescription;\n return result;\n}\n\nconst AsyncGeneratorFunction: any = (async function* () { });\n\n/** Creates a local async generator that proxies iteration to the remote. */\nexport function createAsyncGeneratorFunction(peer: Peer, name: string[]) {\n function wrappedAsyncGeneratorFunction(...args: any[]): AsyncGenerator<any, any, any> {\n let _operationId: ID | null = null;\n let closed = false;\n function wrapped<T>(fn: (value: any) => Promise<T>) {\n return (value: any) => {\n if (closed) return { value: undefined, done: true };\n try {\n return fn(value).catch(handleError);\n } catch (err) {\n handleError(err);\n throw err;\n }\n }\n function handleError(err: any) {\n if (_operationId && !closed) {\n const error = safeSendError(peer, err);\n sendAndWait(peer, OpIterThrow, _operationId, error.code, error.error).catch(() => { });\n }\n closed = true;\n throw err;\n }\n }\n\n const nexter = wrapped(async sendValue => {\n const [value, done] = await sendAndWait(peer, OpIterNext, await operationId(), sendValue);\n if (done) closed = true;\n return { value, done: !!done };\n });\n\n const thrower = wrapped(async err => {\n const error = safeSendError(peer, err);\n const [value, done] = await sendAndWait(peer, OpIterThrow, await operationId(), error.code, error.error);\n if (done) closed = true;\n return { value, done: !!done };\n });\n\n const returner = wrapped(async value => {\n closed = true;\n await sendAndWait(peer, OpIterReturn, await operationId(), value).catch(() => { });\n return { value, done: true };\n });\n\n let iterator = {\n [Symbol.asyncIterator]() { return this; },\n next: nexter,\n throw: thrower,\n return: returner\n };\n\n async function operationId() {\n if (_operationId || closed) return _operationId;\n try {\n return _operationId = await sendAndWait(peer, OpCall, name, args);\n } catch (err: any) {\n closed = true;\n throw err;\n }\n }\n\n return iterator as any;\n };\n\n return markAsAsyncGenerator(wrappedAsyncGeneratorFunction);\n}\n\n/** Marks a function as an async generator, setting the appropriate properties. */\nexport function markAsAsyncGenerator<T>(wrappedAsyncGeneratorFunction: T): T {\n Object.defineProperties(wrappedAsyncGeneratorFunction, {\n [Symbol.toStringTag]: { value: AsyncGeneratorFunction[Symbol.toStringTag], writable: true },\n prototype: { value: AsyncGeneratorFunction.prototype, writable: true },\n constructor: { value: AsyncGeneratorFunction.constructor, writable: true }\n });\n return wrappedAsyncGeneratorFunction;\n}\n\n\n/** Sanitizes an error for sending, respecting sendErrorMessages policy. */\nfunction safeSendError(peer: Peer, error: OperationError | { message?: string, code?: number } | string) {\n const code = typeof error === 'string' ? ErrorGeneric.code : (error.code ?? ErrorGeneric.code);\n if (!peer.sendErrorMessages) {\n return { code, error: (Errors[code] ?? ErrorGeneric).error };\n }\n if (typeof error === 'object') {\n return { code: error.code ?? 0, error: error.message };\n }\n if (typeof error === 'string') {\n return { code: ErrorGeneric.code, error };\n }\n return ErrorGeneric;\n}\n\n/** Sanitizes a received error, respecting receiveErrorMessages policy. */\nfunction safeReceiveError(peer: Peer, error: OperationError | { message?: string, code?: number } | string): OperationError {\n let code = typeof error === 'string' ? ErrorGeneric.code : (error.code ?? ErrorGeneric.code);\n if (peer.receiveErrorMessages) {\n const message = typeof error === 'string' ? error : (error.message ?? Errors[code]?.error ?? ErrorGeneric.error);\n return new OperationError(message, code);\n }\n return new OperationError((Errors[code] ?? ErrorGeneric).error, code);\n}\n\n/** Creates a local async function that proxies calls to the remote. */\nexport function createAsyncFunction(peer: Peer, name: string[], waitForPeer: boolean = true) {\n return async function wrappedAsyncFunction(...args: any[]): Promise<any> {\n if (waitForPeer) await waitUntilRemoteReady(peer);\n return await sendAndWait(peer, OpCall, name, args);\n }\n};\n\n/** Sends a frame and returns a promise that resolves when the remote responds. */\nfunction sendAndWait<K extends FrameOps>(peer: Peer, type: K, ...message: FrameArgs<K>): Promise<any> {\n return new Promise<any>(function (resolve, reject) {\n if (!peer.connection) return reject(new OperationError(ErrorNoRemote));\n let operation: OperationOutboundCall | undefined;\n try {\n operation = peer.session.add('outbound-call', { resolve, reject }, reject);\n peer.send(type, operation.id, ...message);\n } catch (ex: any) {\n operation?.cleanup();\n reject(ex);\n }\n });\n}\n\nconst messageHandler: { [K in FrameOps]: (peer: Peer, session: Session, ...data: FrameIDAndArgs<K>) => (ErrorTypes | void) | Promise<ErrorTypes | void> } = {\n async [OpDescribe](peer, _session, id, description, swap) {\n if (typeof description !== 'object' || description === null || Array.isArray(description) || (swap !== undefined && swap !== null && typeof swap !== 'boolean')) {\n throw new OperationError(ErrorProtocolViolation);\n }\n const mapped = fromCodecDescription(peer, description);\n peer.remote = { ...(swap ? mapped : mergeDescriptions(peer.remote, mapped)) };\n peer.session.remoteDescription = toCodecDescription(peer.remote);\n let prevReadyState = peer.readyState;\n if (peer.readyState === STATE_LOCAL_DESCRIBED) {\n peer.readyState = STATE_READY;\n } else if (peer.readyState < STATE_REMOTE_DESCRIBED) {\n peer.readyState = STATE_REMOTE_DESCRIBED;\n }\n if (prevReadyState !== peer.readyState) {\n peer.emit('readyStateChange', peer.readyState);\n }\n peer.emit('describe', peer.remote);\n peer.send(OpOK, id);\n },\n async [OpCall](peer, session, id, name, args) {\n if (!Array.isArray(name) || !Array.isArray(args)) {\n throw new OperationError(ErrorProtocolViolation);\n }\n await handleInvocation(peer, session, id, name, args);\n },\n [OpOK](_peer, session, id, result) {\n const operation = session.use('outbound-call', id);\n if (!operation) return;\n operation.cleanup();\n operation.context.resolve(result);\n },\n [OpError](peer, session, id, code, error) {\n if (typeof code !== 'number') {\n // Invalid error frame — shut down to avoid error loops.\n peer.close();\n return;\n }\n const errorObj = safeReceiveError(peer, { code, message: error });\n const operation = session.use(undefined, id);\n if (!operation) return;\n operation.reject(errorObj);\n },\n async [OpIterNext](peer, session, id, operationId, value) {\n return await withGenerator(peer, session, id, operationId, async (operation) => {\n const result = await operation.context.generator!.next(value);\n if (result.done) operation.cleanup();\n return [result.value, result.done ? 1 : 0];\n });\n },\n async [OpIterReturn](peer, session, id, operationId, value) {\n return await withGenerator(peer, session, id, operationId, async (operation) => {\n const asyncGenerator = operation.context.generator;\n operation.cleanup();\n const result = await asyncGenerator!.return(value);\n return [result.value, result.done ? 1 : 0];\n }, false);\n },\n async [OpIterThrow](peer, session, id, operationId, code, error) {\n if (typeof code !== 'number' || (error !== undefined && typeof error !== 'string')) {\n throw new OperationError(ErrorProtocolViolation);\n }\n return await withGenerator(peer, session, id, operationId, async (operation) => {\n const err = safeReceiveError(peer, { code, message: error });\n const result = await operation.context.generator!.throw(err);\n if (result.done) operation.cleanup();\n return [result.value, result.done ? 1 : 0];\n });\n }\n}\n\n/** Executes an operation on an in-flight generator with protocol validation. */\nasync function withGenerator(peer: Peer, session: Session, id: ID, operationId: ID, fn: (operation: OperationGenerator) => Promise<any>, preventReentry: boolean = true) {\n if (!isValidID(operationId)) throw new OperationError(ErrorProtocolViolation);\n const operation = session.use('generator', operationId);\n if (!operation) throw new OperationError(ErrorExpiredOrInvalid);\n if (!exists()) {\n const err = new OperationError(ErrorFunctionNotFound);\n operation.reject(err);\n throw err;\n }\n if (operation.context.busy && preventReentry) {\n throw new OperationError(ErrorProtocolViolation);\n }\n try {\n operation.context.busy = true;\n const result = await fn(operation);\n if (!exists()) {\n operation.reject(new OperationError(ErrorFunctionNotFound));\n return peer.send(OpOK, id, [undefined, 1]);\n }\n else peer.send(OpOK, id, result);\n } catch (ex: any) {\n operation.cleanup();\n sendError(peer, id, ex?.code, ex);\n throw ex;\n } finally {\n operation.context.busy = false;\n }\n\n function exists() {\n const found = lookupFunction(peer.local, operation!.context.name);\n return found === operation?.context.target;\n }\n}\n\nfunction sendError(peer: Peer, id: ID, inCode: number, error?: any) {\n const str = error?.error ?? error?.message ?? error;\n const code = (typeof error === 'object' && typeof error.code === 'number' ? error.code : inCode) ?? ErrorGeneric.code;\n if (peer.readyState >= STATE_CONNECTED) {\n const sanitized = safeSendError(peer, { code, message: str });\n peer.send(OpError, id, sanitized.code, sanitized.error);\n return;\n }\n if (code !== ErrorNoRemote.code) {\n peer.emit('error', new OperationError(String(str ?? Errors[code]?.error ?? ErrorGeneric.error), code));\n }\n}\n\n/** Routes an incoming frame to the appropriate handler. */\nasync function handleIncomingMessage(peer: Peer, data: Frame) {\n if (!Array.isArray(data) || typeof data[0] !== 'string' || data[0].length !== 1) {\n return;\n }\n\n if (!isValidID(data[1])) throw new OperationError(ErrorProtocolViolation);\n\n const handler = messageHandler[data[0] as FrameOps];\n if (!handler) return;\n\n try {\n return await handler(peer, peer.session, ...data.slice(1) as FrameIDAndArgs<typeof data[0]>);\n } catch (err: any) {\n if (data[0] === OpError) {\n // Don't respond to invalid errors — avoids loops.\n peer.emit('error', err);\n return;\n }\n const error = safeSendError(peer, err);\n try {\n peer.send(OpError, data[1], error.code, error.error);\n } catch { }\n throw err;\n }\n}\n\n/** Resolves a dotted function path against a description object. */\nfunction lookupFunction(origin: Description<any> | undefined, name: string[]): any {\n if (origin === undefined || origin === null) return null;\n let target: any = origin;\n for (let i = 0; target && i < name.length; ++i) {\n if (Object.prototype.hasOwnProperty.call(target, name[i])) {\n target = target[name[i]];\n } else {\n return null;\n }\n }\n if (typeof target !== 'function') return null;\n return target;\n}\n\n/** Context value that can be passed in to described functions */\nexport type CallContext = { peer: Peer, id: ID, operation: OperationTypes };\ntype HasContext<T> = { [CallContextSymbol]: T };\ntype RemoveFirstParameter<T> = T extends (first: CallContext, ...args: infer U) => infer R ? (...args: U) => R : never;\n/** Wraps a function to automatically provide a call context. */\nexport function withContext<T extends Function>(fn: T): RemoveFirstParameter<T> | HasContext<RemoveFirstParameter<T>> {\n const fail = () => { throw new Error(\"withContext functions cannot be wrapped.\"); };\n (fail as any)[CallContextSymbol] = fn;\n return fail as any;\n}\n\n/** Handles an incoming RPC call or generator creation. */\nasync function handleInvocation(peer: Peer, session: Session, id: ID, name: string[], args: any[]) {\n let operation: OperationTypes | undefined = undefined;\n try {\n let target = lookupFunction(peer.local, name);\n if (!target || typeof target !== 'function') {\n throw new OperationError(ErrorFunctionNotFound);\n }\n const cctx: any = { peer, id };\n let callArgs = args;\n if (CallContextSymbol in target) {\n callArgs = [cctx, ...args];\n target = target[CallContextSymbol];\n }\n\n let complete = false;\n if (isAsyncGeneratorLike(target)) {\n // async generator fn\n let context: OperationGenerator['context'] = { target, name };\n operation = session.add('generator', context, function (_err) {\n if (complete || !context.generator) return;\n complete = true;\n context.generator.return(undefined).catch(() => { });\n });\n cctx.operation = operation;\n if (!operation) return peer.send(OpError, id, ErrorRejected.code, ErrorRejected.error);\n context.generator = target(...callArgs);\n peer.send(OpOK, id, operation.id);\n } else {\n // plain async fn\n operation = session.add('inbound-call', undefined, (err) => {\n if (complete) return;\n complete = true;\n try {\n sendError(peer, id, err?.code ?? ErrorGeneric.code, err)\n } catch (ex) { }\n });\n cctx.operation = operation;\n if (!operation) return peer.send(OpError, id, ErrorRejected.code, ErrorRejected.error);\n const result = await Promise.resolve().then(() => target(...callArgs));\n if (complete) return;\n complete = true;\n operation.cleanup();\n if (id) peer.send(OpOK, id, result);\n }\n } catch (ex: any) {\n if (operation) {\n operation.cleanup();\n }\n sendError(peer, id, ex?.code ?? ErrorGeneric.code, ex);\n throw ex;\n }\n}\n\nexport class OperationError extends Error {\n code: number;\n constructor(ex: ErrorTypes | string, code?: number) {\n if (typeof ex === 'string') {\n super(ex);\n this.code = code ?? ErrorGeneric.code;\n } else {\n super(ex.error);\n this.code = code ?? ex.code;\n }\n }\n}\n\nexport function isAsyncGeneratorLike(value: any): boolean {\n if (typeof value !== 'function') return false;\n if (value.constructor?.name === 'AsyncGeneratorFunction') return true;\n if (value.prototype?.[Symbol.asyncIterator]) return true; // bun compat\n return false;\n}\n\n/** Returns a shallow diff of two descriptions, or null if unchanged. */\nfunction diffDescriptions(prev: { [key: string]: any }, next: { [key: string]: any }): object | null {\n const stack = [{ prev: prev as any, next: next as any, path: [] as string[] }];\n const diffResult: any = {};\n let changed = false;\n while (stack.length > 0) {\n const { prev, next, path } = stack.pop()!;\n if (prev === next) continue;\n if (typeof prev === 'function' && typeof next === 'function' && isAsyncGeneratorLike(prev) === isAsyncGeneratorLike(next)) {\n continue; // Same-shaped functions don't need re-describing.\n } else if (Array.isArray(prev) && Array.isArray(next)) {\n if (prev.length !== next.length) {\n changed = true;\n addChange(next);\n } else if (prev.some((item, index) => item !== next[index])) {\n changed = true;\n addChange(next);\n }\n } else if (typeof prev === 'object' && typeof next === 'object' && prev !== null && next !== null) {\n const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);\n for (const key of allKeys) stack.push({ prev: prev[key], next: next[key], path: [...path, key] });\n } else {\n changed = true;\n addChange(next);\n }\n function addChange(next: any) {\n let current = diffResult;\n for (let i = 0; i < path.length - 1; ++i) {\n if (!(path[i] in current)) {\n current[path[i]] = {};\n }\n current = current[path[i]];\n }\n current[path[path.length - 1]] = next ?? null;\n }\n }\n if (!changed) return null;\n return diffResult;\n}\n\n/** Deep-merges a patch into a description. Null values delete keys. */\nexport function mergeDescriptions(original: any, patch: any): any {\n const result = { ...original };\n for (const [key, value] of Object.entries(patch)) {\n if (value === null || value === undefined) {\n delete result[key];\n } else if (Array.isArray(value) || Array.isArray(result[key])) {\n result[key] = value;\n } else if (typeof value === 'object' && value !== null && typeof result[key] === 'object' && result[key] !== null) {\n result[key] = mergeDescriptions(result[key], value);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction isValidID(id: any): id is ID { return typeof id === 'string' && id.length > 0 && id.length < MAX_ID_LENGTH; }\n"],"mappings":";;;;;;AAMA,MAAM,gBAAgB;AAEtB,MAAa,UAAU;AACvB,IAAW,oBAAoB,OAAO,eAAe;AAIrD,MAAa,aAAa;AAC1B,MAAa,cAAc;AAE3B,MAAa,qBAAqB;AAClC,MAAa,mBAAmB;AAChC,MAAa,kBAAkB;AAC/B,MAAa,wBAAwB;AACrC,MAAa,yBAAyB;AACtC,MAAa,cAAc;AAI3B,MAAa,aAAa;AAC1B,MAAa,SAAS;AACtB,MAAa,OAAO;AACpB,MAAa,UAAU;AACvB,MAAa,aAAa;AAC1B,MAAa,eAAe;AAC5B,MAAa,cAAc;AAe3B,MAAa,SAAS;CAClB;EAAE,MAAM;EAAG,OAAO,GAAG,QAAQ;EAAiB;CAC9C;EAAE,MAAM;EAAG,OAAO,GAAG,QAAQ;EAAuB;CACpD;EAAE,MAAM;EAAG,OAAO,GA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,kBAAkB,OAAO,MAAM,MAAM;KAEnD,QAAO,OAAO;AAGtB,QAAO;;AAGX,SAAS,UAAU,IAAmB;AAAE,QAAO,OAAO,OAAO,YAAY,GAAG,SAAS,KAAK,GAAG,SAAS"}
|
package/session.mjs
CHANGED
|
@@ -1,2 +1,92 @@
|
|
|
1
|
-
import{ErrorDisconnected
|
|
1
|
+
import { ErrorDisconnected, ErrorExpiredOrInvalid, ErrorRejected, OperationError } from "./psionic.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/session.ts
|
|
4
|
+
/**
|
|
5
|
+
* Creates a default session, which tracks in-flight local and remote peer operations as well as current state.
|
|
6
|
+
*
|
|
7
|
+
* The session can be reused across multiple connections to allow for features like automatic resending of frames on reconnect.
|
|
8
|
+
* Note that the operation calls themselves cannot be serialized, but the session can be reattached to a new peer in the same isolate.
|
|
9
|
+
**/
|
|
10
|
+
function createSession(opts = {}) {
|
|
11
|
+
const idGenerator = monotonicBase36Ids(opts.restore?.lastID);
|
|
12
|
+
const permit = opts.permitOperation ?? ((type, _ctx, counts) => (counts.get(type) ?? 0) < 16);
|
|
13
|
+
const timeout = opts.timeout ?? 1e3 * 60 * 6;
|
|
14
|
+
const setTimeoutFn = opts.setTimeout ?? setTimeout;
|
|
15
|
+
const clearTimeoutFn = opts.clearTimeout ?? clearTimeout;
|
|
16
|
+
const operation = /* @__PURE__ */ new Map();
|
|
17
|
+
const counts = /* @__PURE__ */ new Map();
|
|
18
|
+
const timers = /* @__PURE__ */ new Map();
|
|
19
|
+
function touch(id) {
|
|
20
|
+
clearTimeoutFn(timers.get(id));
|
|
21
|
+
timers.set(id, setTimeoutFn(() => {
|
|
22
|
+
const result = operation.get(id);
|
|
23
|
+
if (!result) return;
|
|
24
|
+
result.reject(new OperationError(ErrorExpiredOrInvalid));
|
|
25
|
+
}, timeout));
|
|
26
|
+
}
|
|
27
|
+
const session = {
|
|
28
|
+
remoteDescription: opts.restore?.remoteDescription,
|
|
29
|
+
localDescription: opts.restore?.localDescription,
|
|
30
|
+
lastID: opts.restore?.lastID,
|
|
31
|
+
meta: opts.restore?.meta ?? {},
|
|
32
|
+
get operations() {
|
|
33
|
+
return counts;
|
|
34
|
+
},
|
|
35
|
+
use(type, id) {
|
|
36
|
+
const result = operation.get(id);
|
|
37
|
+
if (!result || type !== void 0 && result.type !== type) return;
|
|
38
|
+
touch(id);
|
|
39
|
+
return result;
|
|
40
|
+
},
|
|
41
|
+
add(type, context, reject) {
|
|
42
|
+
if (!type) throw new Error("Operation type is required");
|
|
43
|
+
if (!permit(type, context, counts)) throw new OperationError(ErrorRejected);
|
|
44
|
+
let done = false;
|
|
45
|
+
const id = idGenerator();
|
|
46
|
+
session.lastID = id;
|
|
47
|
+
const operationObj = {
|
|
48
|
+
id,
|
|
49
|
+
type,
|
|
50
|
+
context,
|
|
51
|
+
cleanup,
|
|
52
|
+
reject: (error) => {
|
|
53
|
+
if (done) return;
|
|
54
|
+
reject(error);
|
|
55
|
+
cleanup();
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
function cleanup() {
|
|
59
|
+
if (done) return;
|
|
60
|
+
done = true;
|
|
61
|
+
clearTimeoutFn(timers.get(id));
|
|
62
|
+
timers.delete(id);
|
|
63
|
+
operation.delete(id);
|
|
64
|
+
counts.set(type, Math.max(0, (counts.get(type) ?? 1) - 1));
|
|
65
|
+
}
|
|
66
|
+
touch(id);
|
|
67
|
+
operation.set(id, operationObj);
|
|
68
|
+
counts.set(type, (counts.get(type) ?? 0) + 1);
|
|
69
|
+
return operationObj;
|
|
70
|
+
},
|
|
71
|
+
clear() {
|
|
72
|
+
const copy = Array.from(operation.values());
|
|
73
|
+
operation.clear();
|
|
74
|
+
for (const value of copy) value.reject(new OperationError(ErrorDisconnected));
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
return session;
|
|
78
|
+
}
|
|
79
|
+
/** Generates monotonic base-36 IDs, 0 - zzzzzzzzzz, before wrapping. */
|
|
80
|
+
function monotonicBase36Ids(lastID) {
|
|
81
|
+
let previous = lastID ? parseInt(lastID, 36) : 0;
|
|
82
|
+
const maxValue = 36 ** 10;
|
|
83
|
+
return () => {
|
|
84
|
+
const nextID = (previous + 1) % maxValue;
|
|
85
|
+
previous = nextID;
|
|
86
|
+
return nextID.toString(36);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
//#endregion
|
|
91
|
+
export { createSession, monotonicBase36Ids };
|
|
2
92
|
//# sourceMappingURL=session.mjs.map
|
package/session.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.mjs","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { ErrorDisconnected, OperationError, ErrorExpiredOrInvalid, ErrorRejected } from './psionic';\n\nexport type ID = string;\n\nexport type Operation<Type extends string, Context> = {\n id: ID,\n type: Type,\n cleanup: () => void,\n reject: (error: OperationError) => void,\n context: Context\n};\n\nexport type OperationGenerator = Operation<'generator', {\n name: string[];\n /** True while processing next/throw/return — prevents reentry. */\n busy?: boolean,\n target: any,\n generator?: AsyncGenerator<any, any, any>,\n}>;\n\nexport type OperationOutboundCall = Operation<'outbound-call', {\n resolve: (value: any) => void,\n reject: (error: any) => void,\n}>;\n\nexport type OperationInboundCall = Operation<'inbound-call', undefined>;\n\n/** Tracks in-flight operations (promises, generators) for cleanup and policy enforcement. */\nexport type Session = {\n /** Look up an existing operation by id. */\n use<TypeName extends OperationTypes['type'] | undefined, Type extends Extract<OperationTypes, { type: TypeName }>>(type: TypeName | undefined, id: ID): (TypeName extends undefined ? OperationTypes : Type) | undefined;\n /** Register a new operation. */\n add<TypeName extends OperationTypes['type'], Type extends Extract<OperationTypes, { type: TypeName }>>(type: TypeName, context: Type['context'], reject: Type['reject']): Type;\n /** Clear all operations (e.g. on disconnect). */\n clear(reason?: string): void;\n /** Latest merged description of the peer's remote */\n remoteDescription?: any;\n /** Latest merged description of the peer's own state */\n localDescription?: any;\n /** Last generated ID */\n lastID?: ID;\n /** Persistent metadata for the session */\n meta: Record<string, any>;\n};\n\nexport type OperationTypes = OperationGenerator | OperationOutboundCall | OperationInboundCall;\n\nexport type SessionOptions = {\n /** Timeout for in-flight operations in milliseconds. Default is 6 minutes. */\n timeout?: number;\n /** Custom setTimeout function. */\n setTimeout?: (callback: () => void, ms: number) => ReturnType<typeof setTimeout>;\n /** Custom clearTimeout function. */\n clearTimeout?: (id: ReturnType<typeof setTimeout>) => void;\n /** Maximum in-flight operations. Default is 16 per peer. */\n //maxOperation?: { [K in OperationTypes['type']]?: number };\n permitOperation?<TypeName extends OperationTypes['type'], Type extends Extract<OperationTypes, { type: TypeName }>>(type: TypeName, context: Type['context'], counts: Map<OperationTypes['type'], number>): boolean | Promise<boolean>;\n /** State to restore from a previous session. */\n restore?: {\n /** Latest merged description of the peer's remote */\n remoteDescription?: any;\n /** Latest merged description of the peer's own state */\n localDescription?: any;\n /** Last used ID from the previous session */\n lastID?: ID;\n /** Session metadata from the previous session */\n meta?: Record<string, any>;\n }\n};\n\n/** \n * Creates a default session, which tracks in-flight local and remote peer operations as well as current state.\n * \n * The session can be reused across multiple connections to allow for features like automatic resending of frames on reconnect.\n * Note that the operation calls themselves cannot be serialized, but the session can be reattached to a new peer in the same isolate.\n **/\nexport function createSession(opts: SessionOptions = {}): Session {\n const idGenerator = monotonicBase36Ids(opts.restore?.lastID);\n const permit = opts.permitOperation ?? ((type, _ctx, counts) => (counts.get(type) ?? 0) < 0x10);\n const timeout = opts.timeout ?? (1000 * 60 * 6); // Default timeout 6 minutes\n const setTimeoutFn = opts.setTimeout ?? setTimeout;\n const clearTimeoutFn = opts.clearTimeout ?? clearTimeout;\n const operation = new Map<ID, OperationTypes>();\n const counts = new Map<OperationTypes['type'], number>();\n const timers = new Map<ID, any>();\n\n function touch(id: ID) {\n clearTimeoutFn(timers.get(id));\n timers.set(id, setTimeoutFn(() => {\n const result = operation.get(id);\n if (!result) return;\n result.reject(new OperationError(ErrorExpiredOrInvalid));\n }, timeout));\n }\n\n const session = {\n remoteDescription: opts.restore?.remoteDescription,\n localDescription: opts.restore?.localDescription,\n lastID: opts.restore?.lastID,\n meta: opts.restore?.meta ?? {},\n get operations() { return counts; },\n\n use(type, id) {\n const result = operation.get(id);\n if (!result || (type !== undefined && result.type !== type)) return;\n touch(id);\n return result as Extract<OperationTypes, { type: typeof type }>;\n },\n add(type, context, reject) {\n if (!type) throw new Error('Operation type is required');\n if (!permit(type, context, counts)) {\n throw new OperationError(ErrorRejected);\n }\n let done = false;\n const id = idGenerator();\n session.lastID = id;\n const operationObj = {\n id,\n type,\n context,\n cleanup,\n reject: (error: OperationError) => {\n if (done) return;\n reject(error);\n cleanup();\n },\n }\n\n function cleanup() {\n if (done) return;\n done = true;\n clearTimeoutFn(timers.get(id));\n timers.delete(id);\n operation.delete(id);\n counts.set(type, Math.max(0, (counts.get(type) ?? 1) - 1));\n }\n\n touch(id);\n operation.set(id, operationObj as OperationTypes);\n counts.set(type, (counts.get(type) ?? 0) + 1);\n return operationObj;\n },\n clear() {\n const copy = Array.from(operation.values());\n operation.clear();\n for (const value of copy) {\n value.reject(new OperationError(ErrorDisconnected));\n }\n }\n } as Session;\n\n return session;\n}\n\n/** Generates monotonic base-36 IDs, 0 - zzzzzzzzzz, before wrapping. */\nexport function monotonicBase36Ids(lastID?: ID): () => ID {\n let previous = lastID ? parseInt(lastID, 36) : 0;\n const maxValue = (36**10);\n return () => {\n const nextID = (previous + 1) % maxValue;\n previous = nextID;\n return nextID.toString(36) as ID;\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"session.mjs","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { ErrorDisconnected, OperationError, ErrorExpiredOrInvalid, ErrorRejected } from './psionic';\n\nexport type ID = string;\n\nexport type Operation<Type extends string, Context> = {\n id: ID,\n type: Type,\n cleanup: () => void,\n reject: (error: OperationError) => void,\n context: Context\n};\n\nexport type OperationGenerator = Operation<'generator', {\n name: string[];\n /** True while processing next/throw/return — prevents reentry. */\n busy?: boolean,\n target: any,\n generator?: AsyncGenerator<any, any, any>,\n}>;\n\nexport type OperationOutboundCall = Operation<'outbound-call', {\n resolve: (value: any) => void,\n reject: (error: any) => void,\n}>;\n\nexport type OperationInboundCall = Operation<'inbound-call', undefined>;\n\n/** Tracks in-flight operations (promises, generators) for cleanup and policy enforcement. */\nexport type Session = {\n /** Look up an existing operation by id. */\n use<TypeName extends OperationTypes['type'] | undefined, Type extends Extract<OperationTypes, { type: TypeName }>>(type: TypeName | undefined, id: ID): (TypeName extends undefined ? OperationTypes : Type) | undefined;\n /** Register a new operation. */\n add<TypeName extends OperationTypes['type'], Type extends Extract<OperationTypes, { type: TypeName }>>(type: TypeName, context: Type['context'], reject: Type['reject']): Type;\n /** Clear all operations (e.g. on disconnect). */\n clear(reason?: string): void;\n /** Latest merged description of the peer's remote */\n remoteDescription?: any;\n /** Latest merged description of the peer's own state */\n localDescription?: any;\n /** Last generated ID */\n lastID?: ID;\n /** Persistent metadata for the session */\n meta: Record<string, any>;\n};\n\nexport type OperationTypes = OperationGenerator | OperationOutboundCall | OperationInboundCall;\n\nexport type SessionOptions = {\n /** Timeout for in-flight operations in milliseconds. Default is 6 minutes. */\n timeout?: number;\n /** Custom setTimeout function. */\n setTimeout?: (callback: () => void, ms: number) => ReturnType<typeof setTimeout>;\n /** Custom clearTimeout function. */\n clearTimeout?: (id: ReturnType<typeof setTimeout>) => void;\n /** Maximum in-flight operations. Default is 16 per peer. */\n //maxOperation?: { [K in OperationTypes['type']]?: number };\n permitOperation?<TypeName extends OperationTypes['type'], Type extends Extract<OperationTypes, { type: TypeName }>>(type: TypeName, context: Type['context'], counts: Map<OperationTypes['type'], number>): boolean | Promise<boolean>;\n /** State to restore from a previous session. */\n restore?: {\n /** Latest merged description of the peer's remote */\n remoteDescription?: any;\n /** Latest merged description of the peer's own state */\n localDescription?: any;\n /** Last used ID from the previous session */\n lastID?: ID;\n /** Session metadata from the previous session */\n meta?: Record<string, any>;\n }\n};\n\n/** \n * Creates a default session, which tracks in-flight local and remote peer operations as well as current state.\n * \n * The session can be reused across multiple connections to allow for features like automatic resending of frames on reconnect.\n * Note that the operation calls themselves cannot be serialized, but the session can be reattached to a new peer in the same isolate.\n **/\nexport function createSession(opts: SessionOptions = {}): Session {\n const idGenerator = monotonicBase36Ids(opts.restore?.lastID);\n const permit = opts.permitOperation ?? ((type, _ctx, counts) => (counts.get(type) ?? 0) < 0x10);\n const timeout = opts.timeout ?? (1000 * 60 * 6); // Default timeout 6 minutes\n const setTimeoutFn = opts.setTimeout ?? setTimeout;\n const clearTimeoutFn = opts.clearTimeout ?? clearTimeout;\n const operation = new Map<ID, OperationTypes>();\n const counts = new Map<OperationTypes['type'], number>();\n const timers = new Map<ID, any>();\n\n function touch(id: ID) {\n clearTimeoutFn(timers.get(id));\n timers.set(id, setTimeoutFn(() => {\n const result = operation.get(id);\n if (!result) return;\n result.reject(new OperationError(ErrorExpiredOrInvalid));\n }, timeout));\n }\n\n const session = {\n remoteDescription: opts.restore?.remoteDescription,\n localDescription: opts.restore?.localDescription,\n lastID: opts.restore?.lastID,\n meta: opts.restore?.meta ?? {},\n get operations() { return counts; },\n\n use(type, id) {\n const result = operation.get(id);\n if (!result || (type !== undefined && result.type !== type)) return;\n touch(id);\n return result as Extract<OperationTypes, { type: typeof type }>;\n },\n add(type, context, reject) {\n if (!type) throw new Error('Operation type is required');\n if (!permit(type, context, counts)) {\n throw new OperationError(ErrorRejected);\n }\n let done = false;\n const id = idGenerator();\n session.lastID = id;\n const operationObj = {\n id,\n type,\n context,\n cleanup,\n reject: (error: OperationError) => {\n if (done) return;\n reject(error);\n cleanup();\n },\n }\n\n function cleanup() {\n if (done) return;\n done = true;\n clearTimeoutFn(timers.get(id));\n timers.delete(id);\n operation.delete(id);\n counts.set(type, Math.max(0, (counts.get(type) ?? 1) - 1));\n }\n\n touch(id);\n operation.set(id, operationObj as OperationTypes);\n counts.set(type, (counts.get(type) ?? 0) + 1);\n return operationObj;\n },\n clear() {\n const copy = Array.from(operation.values());\n operation.clear();\n for (const value of copy) {\n value.reject(new OperationError(ErrorDisconnected));\n }\n }\n } as Session;\n\n return session;\n}\n\n/** Generates monotonic base-36 IDs, 0 - zzzzzzzzzz, before wrapping. */\nexport function monotonicBase36Ids(lastID?: ID): () => ID {\n let previous = lastID ? parseInt(lastID, 36) : 0;\n const maxValue = (36**10);\n return () => {\n const nextID = (previous + 1) % maxValue;\n previous = nextID;\n return nextID.toString(36) as ID;\n }\n}\n"],"mappings":";;;;;;;;;AA4EA,SAAgB,cAAc,OAAuB,EAAE,EAAW;CAC9D,MAAM,cAAc,mBAAmB,KAAK,SAAS,OAAO;CAC5D,MAAM,SAAS,KAAK,qBAAqB,MAAM,MAAM,YAAY,OAAO,IAAI,KAAK,IAAI,KAAK;CAC1F,MAAM,UAAU,KAAK,WAAY,MAAO,KAAK;CAC7C,MAAM,eAAe,KAAK,cAAc;CACxC,MAAM,iBAAiB,KAAK,gBAAgB;CAC5C,MAAM,4BAAY,IAAI,KAAyB;CAC/C,MAAM,yBAAS,IAAI,KAAqC;CACxD,MAAM,yBAAS,IAAI,KAAc;CAEjC,SAAS,MAAM,IAAQ;AACnB,iBAAe,OAAO,IAAI,GAAG,CAAC;AAC9B,SAAO,IAAI,IAAI,mBAAmB;GAC9B,MAAM,SAAS,UAAU,IAAI,GAAG;AAChC,OAAI,CAAC,OAAQ;AACb,UAAO,OAAO,IAAI,eAAe,sBAAsB,CAAC;KACzD,QAAQ,CAAC;;CAGhB,MAAM,UAAU;EACZ,mBAAmB,KAAK,SAAS;EACjC,kBAAkB,KAAK,SAAS;EAChC,QAAQ,KAAK,SAAS;EACtB,MAAM,KAAK,SAAS,QAAQ,EAAE;EAC9B,IAAI,aAAa;AAAE,UAAO;;EAE1B,IAAI,MAAM,IAAI;GACV,MAAM,SAAS,UAAU,IAAI,GAAG;AAChC,OAAI,CAAC,UAAW,SAAS,UAAa,OAAO,SAAS,KAAO;AAC7D,SAAM,GAAG;AACT,UAAO;;EAEX,IAAI,MAAM,SAAS,QAAQ;AACvB,OAAI,CAAC,KAAM,OAAM,IAAI,MAAM,6BAA6B;AACxD,OAAI,CAAC,OAAO,MAAM,SAAS,OAAO,CAC9B,OAAM,IAAI,eAAe,cAAc;GAE3C,IAAI,OAAO;GACX,MAAM,KAAK,aAAa;AACxB,WAAQ,SAAS;GACjB,MAAM,eAAe;IACjB;IACA;IACA;IACA;IACA,SAAS,UAA0B;AAC/B,SAAI,KAAM;AACV,YAAO,MAAM;AACb,cAAS;;IAEhB;GAED,SAAS,UAAU;AACf,QAAI,KAAM;AACV,WAAO;AACP,mBAAe,OAAO,IAAI,GAAG,CAAC;AAC9B,WAAO,OAAO,GAAG;AACjB,cAAU,OAAO,GAAG;AACpB,WAAO,IAAI,MAAM,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;;AAG9D,SAAM,GAAG;AACT,aAAU,IAAI,IAAI,aAA+B;AACjD,UAAO,IAAI,OAAO,OAAO,IAAI,KAAK,IAAI,KAAK,EAAE;AAC7C,UAAO;;EAEX,QAAQ;GACJ,MAAM,OAAO,MAAM,KAAK,UAAU,QAAQ,CAAC;AAC3C,aAAU,OAAO;AACjB,QAAK,MAAM,SAAS,KAChB,OAAM,OAAO,IAAI,eAAe,kBAAkB,CAAC;;EAG9D;AAED,QAAO;;;AAIX,SAAgB,mBAAmB,QAAuB;CACtD,IAAI,WAAW,SAAS,SAAS,QAAQ,GAAG,GAAG;CAC/C,MAAM,WAAY,MAAI;AACtB,cAAa;EACT,MAAM,UAAU,WAAW,KAAK;AAChC,aAAW;AACX,SAAO,OAAO,SAAS,GAAG"}
|
package/utils/react-hooks.mjs
CHANGED
|
@@ -1,2 +1,37 @@
|
|
|
1
|
-
import{STATE_READY
|
|
1
|
+
import { STATE_READY } from "../psionic.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/react-hooks.ts
|
|
4
|
+
function createPeerHooks(peer, React) {
|
|
5
|
+
const PeerContext = React.createContext(void 0);
|
|
6
|
+
function PeerProvider({ children }) {
|
|
7
|
+
const remote = React.useSyncExternalStore((d) => peer.on("describe", d), () => peer.remote);
|
|
8
|
+
const ready = React.useSyncExternalStore((d) => peer.on("readyStateChange", d), () => peer.readyState >= STATE_READY);
|
|
9
|
+
return React.createElement(PeerContext.Provider, { value: {
|
|
10
|
+
peer,
|
|
11
|
+
remote,
|
|
12
|
+
ready
|
|
13
|
+
} }, children);
|
|
14
|
+
}
|
|
15
|
+
function usePeerRemote() {
|
|
16
|
+
const { remote } = React.useContext(PeerContext);
|
|
17
|
+
return remote;
|
|
18
|
+
}
|
|
19
|
+
function usePeer() {
|
|
20
|
+
const { peer } = React.useContext(PeerContext);
|
|
21
|
+
return peer;
|
|
22
|
+
}
|
|
23
|
+
function usePeerReady() {
|
|
24
|
+
const { ready } = React.useContext(PeerContext);
|
|
25
|
+
return ready;
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
PeerProvider,
|
|
29
|
+
usePeerRemote,
|
|
30
|
+
usePeer,
|
|
31
|
+
usePeerReady
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//#endregion
|
|
36
|
+
export { createPeerHooks };
|
|
2
37
|
//# sourceMappingURL=react-hooks.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-hooks.mjs","names":[],"sources":["../../src/utils/react-hooks.ts"],"sourcesContent":["import { type BasicDescription, type Description, type Peer, STATE_READY } from \"../psionic\";\n\ntype PeerContext<T extends BasicDescription> = { peer: Peer<T>, remote: Peer<T>['remote'], ready: boolean };\n\ntype FC<P> = (props: P) => any | Promise<any>;\ntype ReactShape = {\n useSyncExternalStore: any\n createContext: any\n useContext: any\n useEffect: any\n createElement: any\n useRef: any;\n};\n\ntype ReactPeerProvider<RemoteAPI extends BasicDescription = any> = {\n PeerProvider: FC<{ children: any }>,\n usePeerRemote:() => Description<RemoteAPI>;\n usePeer: () => Peer<RemoteAPI>;\n usePeerReady: () => boolean;\n};\n\nexport function createPeerHooks<T extends BasicDescription>(peer: Peer<T>, React: ReactShape): ReactPeerProvider<T> {\n\n const PeerContext = React.createContext(undefined as unknown as PeerContext<any>);\n\n function PeerProvider({ children }: { children: any }) {\n const remote = React.useSyncExternalStore((d: any) => peer.on('describe', d), () => peer.remote);\n const ready = React.useSyncExternalStore((d: any) => peer.on('readyStateChange', d), () => peer.readyState >= STATE_READY);\n return React.createElement(PeerContext.Provider, { value: { peer, remote, ready } }, children);\n }\n\n function usePeerRemote() {\n const { remote } = React.useContext(PeerContext);\n return remote as Description<T>;\n }\n\n function usePeer() {\n const { peer } = React.useContext(PeerContext);\n return peer as Peer<T>;\n }\n\n function usePeerReady() {\n const { ready } = React.useContext(PeerContext);\n return ready;\n }\n\n return { PeerProvider, usePeerRemote, usePeer, usePeerReady };\n}"],"mappings":"
|
|
1
|
+
{"version":3,"file":"react-hooks.mjs","names":[],"sources":["../../src/utils/react-hooks.ts"],"sourcesContent":["import { type BasicDescription, type Description, type Peer, STATE_READY } from \"../psionic\";\n\ntype PeerContext<T extends BasicDescription> = { peer: Peer<T>, remote: Peer<T>['remote'], ready: boolean };\n\ntype FC<P> = (props: P) => any | Promise<any>;\ntype ReactShape = {\n useSyncExternalStore: any\n createContext: any\n useContext: any\n useEffect: any\n createElement: any\n useRef: any;\n};\n\ntype ReactPeerProvider<RemoteAPI extends BasicDescription = any> = {\n PeerProvider: FC<{ children: any }>,\n usePeerRemote:() => Description<RemoteAPI>;\n usePeer: () => Peer<RemoteAPI>;\n usePeerReady: () => boolean;\n};\n\nexport function createPeerHooks<T extends BasicDescription>(peer: Peer<T>, React: ReactShape): ReactPeerProvider<T> {\n\n const PeerContext = React.createContext(undefined as unknown as PeerContext<any>);\n\n function PeerProvider({ children }: { children: any }) {\n const remote = React.useSyncExternalStore((d: any) => peer.on('describe', d), () => peer.remote);\n const ready = React.useSyncExternalStore((d: any) => peer.on('readyStateChange', d), () => peer.readyState >= STATE_READY);\n return React.createElement(PeerContext.Provider, { value: { peer, remote, ready } }, children);\n }\n\n function usePeerRemote() {\n const { remote } = React.useContext(PeerContext);\n return remote as Description<T>;\n }\n\n function usePeer() {\n const { peer } = React.useContext(PeerContext);\n return peer as Peer<T>;\n }\n\n function usePeerReady() {\n const { ready } = React.useContext(PeerContext);\n return ready;\n }\n\n return { PeerProvider, usePeerRemote, usePeer, usePeerReady };\n}"],"mappings":";;;AAqBA,SAAgB,gBAA4C,MAAe,OAAyC;CAEhH,MAAM,cAAc,MAAM,cAAc,OAAyC;CAEjF,SAAS,aAAa,EAAE,YAA+B;EACnD,MAAM,SAAS,MAAM,sBAAsB,MAAW,KAAK,GAAG,YAAY,EAAE,QAAQ,KAAK,OAAO;EAChG,MAAM,QAAQ,MAAM,sBAAsB,MAAW,KAAK,GAAG,oBAAoB,EAAE,QAAQ,KAAK,cAAc,YAAY;AAC1H,SAAO,MAAM,cAAc,YAAY,UAAU,EAAE,OAAO;GAAE;GAAM;GAAQ;GAAO,EAAE,EAAE,SAAS;;CAGlG,SAAS,gBAAgB;EACrB,MAAM,EAAE,WAAW,MAAM,WAAW,YAAY;AAChD,SAAO;;CAGX,SAAS,UAAU;EACf,MAAM,EAAE,SAAS,MAAM,WAAW,YAAY;AAC9C,SAAO;;CAGX,SAAS,eAAe;EACpB,MAAM,EAAE,UAAU,MAAM,WAAW,YAAY;AAC/C,SAAO;;AAGX,QAAO;EAAE;EAAc;EAAe;EAAS;EAAc"}
|