import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http"; import { ServerWebSocket } from "bun"; //#region src/types.d.ts // Copyright (c) 2025 Cloudflare, Inc. // Licensed under the MIT license found in the LICENSE.txt file or at: // https://opensource.org/license/mit // This file borrows heavily from `types/defines/rpc.d.ts` in workerd. // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) declare const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; declare const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; // Distinguishes mapper placeholders from regular values so param unwrapping can accept them. declare const __RPC_MAP_VALUE_BRAND: unique symbol; interface RpcTargetBranded { [__RPC_TARGET_BRAND]: never; } // Types that can be used through `Stub`s // `never[]` preserves compatibility with strongly-typed function signatures without introducing // `any` into inference. type Stubable = RpcTargetBranded | ((...args: never[]) => unknown); type IsUnknown = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC // The reason for using a generic type here is to build the serializable subset of RPC-compatible // composite types. This allows types defined with the "interface" keyword to pass the // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. type RpcCompatible = // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible. (IsUnknown extends true ? unknown : never) // RPC-compatible base values | BaseType // RPC-compatible composites | Map ? RpcCompatible : never, T extends Map ? RpcCompatible : never> | Set ? RpcCompatible : never> | Array ? RpcCompatible : never> | ReadonlyArray ? RpcCompatible : never> | { [K in keyof T as K extends string | number ? K : never]: RpcCompatible } | Promise ? RpcCompatible : never> // Special types | Stub // Serialized as stubs, see `Stubify` | Stubable; // Base type for all RPC stubs, including common memory management methods. // `T` is used as a marker type for unwrapping `Stub`s later. interface StubBase extends Disposable { [__RPC_STUB_BRAND]: T; dup(): this; onRpcBroken(callback: (error: any) => void): void; } type Stub> = T extends object ? Provider & StubBase : StubBase; type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array; // This represents all the types that can be sent as-is over an RPC boundary type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream // Chunk type can be any RPC-compatible type | WritableStream // Chunk type can be any RPC-compatible type | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises. // prettier-ignore type Stubify = T extends Stubable ? Stub : T extends Promise ? Stubify : T extends StubBase ? T : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify, ...Stubify] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify, ...Stubify] : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified. : T extends { [key: string | number]: any; } ? { [K in keyof T as K extends string | number ? K : never]: Stubify } : T; // Recursively rewrite all `Stub`s with the corresponding `T`s. // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. // prettier-ignore type UnstubifyInner = // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub // is already assignable to the value type (important for callback contextual typing). T extends StubBase ? (T extends V ? UnstubifyInner : (T | UnstubifyInner)) : T extends Promise ? UnstubifyInner : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Unstubify, ...Unstubify] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Unstubify, ...Unstubify] : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: unknown; } ? { [K in keyof T as K extends string | number ? K : never]: Unstubify } : T; // You can put promises anywhere in the params and they'll be resolved before delivery. // (This also covers RpcPromise, because it's defined as being a Promise.) // Map placeholders are also allowed so primitive map callback inputs can be forwarded directly // into RPC params. // // Keep raw non-stub members so generic assignability still works when UnstubifyInner is deferred. // Remove stub members from mixed unions so callback params don’t get both stub and unstubbed signatures. // Marker carried by map() callback inputs. This lets primitive placeholders flow through params. type Unstubify = NonStubMembers | UnstubifyInner | Promise> | MapValuePlaceholder>; type UnstubifyAll = { [I in keyof A]: Unstubify }; interface MapValuePlaceholder { [__RPC_MAP_VALUE_BRAND]: T; } type NonStubMembers = Exclude>; // Utility type for adding `Disposable`s to `object` types only. // Note `unknown & T` is equivalent to `T`. type MaybeDisposable = T extends object ? Disposable : unknown; // Type for method return or property on an RPC interface. // - Stubable types are replaced by stubs. // - RpcCompatible types are passed by value, with stubable types replaced by stubs // and a top-level `Disposer`. // Everything else can't be passed over RPC. // Technically, we use custom thenables here, but they quack like `Promise`s. // Intersecting with `(Maybe)Provider` allows pipelining. // prettier-ignore type Result = IsAny extends true ? UnknownResult : IsUnknown extends true ? UnknownResult : R extends Stubable ? Promise> & Provider & StubBase : R extends RpcCompatible ? Promise & MaybeDisposable> & Provider & StubBase : never; type IsAny = 0 extends (1 & T) ? true : false; type UnknownResult = Promise & Provider & StubBase; // Type for method or property on an RPC interface. // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. // Unwrapping `Stub`s allows calling with `Stubable` arguments. // For properties, rewrite types to be `Result`s. // In each case, unwrap `Promise`s. type MethodOrProperty = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll

) => IsAny extends true ? UnknownResult : Result> : Result>; // Type for the callable part of an `Provider` if `T` is callable. // This is intersected with methods/properties. type MaybeCallableProvider = T extends ((...args: any[]) => any) ? MethodOrProperty : unknown; type TupleIndexKeys> = Extract; type MapCallbackValue = // `Omit` removes call signatures, so re-intersect callable provider behavior. T extends unknown ? Omit, keyof Promise> & MaybeCallableProvider & MapValuePlaceholder : never; type InvalidNativePromiseInMapResult = T extends unknown ? InvalidNativePromiseInMapResultImpl : never; type InvalidNativePromiseInMapResultImpl = [T] extends [Seen] ? never // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values. : T extends StubBase ? never // Native thenables cannot be represented in map recordings, even when typed as PromiseLike. : T extends PromiseLike ? T : T extends Map ? InvalidNativePromiseInMapResult | InvalidNativePromiseInMapResult : T extends Set ? InvalidNativePromiseInMapResult : T extends readonly [] ? never : T extends readonly [infer Head, ...infer Tail] ? InvalidNativePromiseInMapResult | InvalidNativePromiseInMapResult : T extends ReadonlyArray ? InvalidNativePromiseInMapResult : T extends { [key: string | number]: unknown; } ? InvalidNativePromiseInMapResult], Seen | T> : never; type MapCallbackReturn = InvalidNativePromiseInMapResult extends never ? T : never; type ArrayProvider = { [K in number]: MethodOrProperty } & { map(callback: (elem: MapCallbackValue) => MapCallbackReturn): Result>; }; type TupleProvider> = { [K in TupleIndexKeys]: MethodOrProperty } & ArrayProvider; // Base type for all other types providing RPC-like interfaces. // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. // // Use `Pick<{[K in keyof T]: ...}, Exclude<...>>` rather than a direct mapped type over the // filtered keys so TypeScript keeps a named `T` in the type tree (better go-to-definition / // cmd-click through RpcStub/Provider wrappers). type Provider = MaybeCallableProvider & (T extends ReadonlyArray ? number extends T["length"] ? ArrayProvider : TupleProvider : Pick<{ [K in keyof T]: MethodOrProperty }, Exclude>> & { map(callback: (value: MapCallbackValue>) => MapCallbackReturn): Result>; }); //#endregion //#region src/core.d.ts interface RpcTarget$1 { [__RPC_TARGET_BRAND]: never; } declare let RpcTarget$1: any; type PropertyPath = (string | number)[]; /** Information about one application function invocation received over RPC. */ type RpcCallInfo = { /** The property path used to reach the function from the referenced capability. */path: PropertyPath; /** The object that owns the function, or the function itself for a callable capability. */ target: unknown; }; /** * Wraps one local application invocation. `invoke()` must be called synchronously so Cap'n Web's * e-order guarantees are preserved, but the returned promise remains pending for the full call. */ type RpcCallHandler = (info: RpcCallInfo, invoke: () => Promise) => Promise; declare abstract class StubHook { abstract call(path: PropertyPath, args: RpcPayload): StubHook; stream(path: PropertyPath, args: RpcPayload): { promise: Promise; size?: number; }; abstract map(path: PropertyPath, captures: StubHook[], instructions: unknown[]): StubHook; abstract get(path: PropertyPath): StubHook; abstract dup(): StubHook; abstract pull(): RpcPayload | Promise; abstract ignoreUnhandledRejections(): void; abstract dispose(): void; abstract onBroken(callback: (error: any) => void): void; } declare let RAW_STUB: symbol; interface RpcStub$1 extends Disposable {} declare class RpcStub$1 extends RpcTarget$1 { [RAW_STUB]: this; constructor(hook: StubHook, pathIfPromise?: PropertyPath); hook: StubHook; pathIfPromise?: PropertyPath; dup(): RpcStub$1; onRpcBroken(callback: (error: any) => void): void; map(func: (value: RpcPromise$1) => unknown): RpcPromise$1; toString(): string; } declare class RpcPromise$1 extends RpcStub$1 { constructor(hook: StubHook, pathIfPromise: PropertyPath); then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise; catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise; finally(onfinally?: (() => void) | undefined | null): Promise; toString(): string; } type LocatedPromise = { parent: object; property: string | number; promise: RpcPromise$1; }; declare class RpcPayload { value: unknown; private source; private hooks?; private promises?; callHandler?: RpcCallHandler | undefined; static fromAppParams(value: unknown): RpcPayload; static fromAppReturn(value: unknown): RpcPayload; static fromArray(array: RpcPayload[]): RpcPayload; static forEvaluate(hooks: StubHook[], promises: LocatedPromise[], callHandler?: RpcCallHandler): RpcPayload; static deepCopyFrom(value: unknown, oldParent: object | undefined, owner: RpcPayload | null): RpcPayload; private constructor(); private rpcTargets?; private getHookForReturn; getHookForRpcTarget(target: RpcTarget$1 | Function, parent: object | undefined, dupStubs?: boolean): StubHook; getHookForWritableStream(stream: WritableStream, parent: object | undefined, dupStubs?: boolean): StubHook; getHookForReadableStream(stream: ReadableStream, parent: object | undefined, dupStubs?: boolean): StubHook; private sentWebSockets?; getHookForWebSocket(webSocket: object, makeHook: () => StubHook): StubHook; getExistingHookForWebSocket(webSocket: object, dupStubs: boolean): StubHook | undefined; private deepCopy; ensureDeepCopied(): void; private deliverTo; private static deliverRpcPromiseTo; deliverCall(func: Function, thisArg: object | undefined): Promise; deliverStreamWrite(writer: { write(chunk: unknown): Promise; }): Promise; deliverResolve(): Promise; dispose(): void; private disposeImpl; ignoreUnhandledRejections(): void; private ignoreUnhandledRejectionsImpl; } //#endregion //#region src/serialize.d.ts /** * Encoding levels determine what representation the RPC system hands to the transport. * Each level names what the transport can assume about message values. * * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports. * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders. * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw. * - `"structuredClonable"`: Structured-clonable native values pass through where possible. * * @example * ```ts * // What happens to Uint8Array([1, 2, 3]) at each level: * "string" → '["bytes","AQID"]' // JSON string with base64 * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64 * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native * ``` */ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable"; interface RpcLimits { maxBigIntDigits: number; maxDepth: number; maxMessageSize: number; } declare const DEFAULT_MAX_DEPTH = 256; declare const DEFAULT_LIMITS: RpcLimits; /** * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize * RPC stubs, but it will support basic data types. */ declare function serialize(value: unknown): string; /** * Deserialize a value serialized using serialize(). */ declare function deserialize(value: string): unknown; //#endregion //#region src/rpc.d.ts /** * Interface for a string-based RPC transport. This is the default transport type — no * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs. */ interface RpcTransport { /** * The encoding level this transport works with. For this interface it is always "string"; * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.) */ readonly encodingLevel?: "string"; /** * Sends a message to the other end. May optionally return a promise; if the promise rejects, * the session is aborted. */ send(message: string): void | Promise; /** * Receives a message sent by the other end. * * If and when the transport becomes disconnected, this will reject. The thrown error will be * propagated to all outstanding calls and future calls on any stubs associated with the session. * If there are no outstanding calls (and none are made in the future), then the error does not * propagate anywhere -- this is considered a "clean" shutdown. */ receive(): Promise; /** * Indicates that the RPC system has suffered an error that prevents the session from continuing. * The transport should ideally try to send any queued messages if it can, and then close the * connection. (It's not strictly necessary to deliver queued messages, but the last message sent * before abort() is called is often an "abort" message, which communicates the error to the * peer, so if that is dropped, the peer may have less information about what happened.) */ abort?(reason: any): void; } /** * Interface for a transport that receives partially encoded JS values instead of JSON strings. * The selected `encodingLevel` describes what the transport can assume about message values. */ interface RpcTransportWithCustomEncoding { /** * The encoding level this transport works with. * * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization. * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw. * - "structuredClonable": Structured-clonable native values pass through where possible. */ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable"; /** * Encodes and sends a message to the other end. Returns the encoded byte size if known. * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for * flow control. Send errors should be propagated via `receive()` rejecting. */ send(message: unknown): number | void; /** * Receives and decodes a message sent by the other end. * * If and when the transport becomes disconnected, this will reject. The thrown error will be * propagated to all outstanding calls and future calls on any stubs associated with the session. * If there are no outstanding calls (and none are made in the future), then the error does not * propagate anywhere -- this is considered a "clean" shutdown. */ receive(): Promise; /** * Indicates that the RPC system has suffered an error that prevents the session from continuing. * The transport should ideally try to send any queued messages if it can, and then close the * connection. (It's not strictly necessary to deliver queued messages, but the last message sent * before abort() is called is often an "abort" message, which communicates the error to the * peer, so if that is dropped, the peer may have less information about what happened.) */ abort?(reason: any): void; } /** Any supported transport type. */ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding; /** * Options to customize behavior of an RPC session. All functions which start a session should * optionally accept this. */ type RpcSessionOptions = { /** * If provided, this function will be called whenever an `Error` object is serialized (for any * reason, not just because it was thrown). This can be used to log errors, and also to redact * them. * * If `onSendError` returns an Error object, than object will be substituted in place of the * original. If it has a stack property, the stack will be sent to the client. * * If `onSendError` doesn't return anything (or is not provided at all), the default behavior is * to serialize the error with the stack omitted. */ onSendError?: (error: Error) => Error | void; /** * Overrides for the resource limits enforced while deserializing messages from the peer. Any * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field. * * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so * the peer never learns these values. A message that exceeds a limit is rejected, aborting the * session. */ limits?: Partial; /** * Wrap every local application function invoked by the peer. The handler must invoke * `invoke()` synchronously to preserve e-order, and should return its promise so the wrapper * spans the full asynchronous call. The hook is propagated through promise pipelining. */ onCall?: RpcCallHandler; }; //#endregion //#region src/websocket.d.ts /** * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session * with the given `localMain`. */ declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response; /** * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports. */ declare class WebSocketTransport { #private; constructor(webSocket: WebSocket); send(message: T): void; receive(): Promise; abort(reason: any): void; } //#endregion //#region src/batch.d.ts /** * Implements the server end of an HTTP batch session, using standard Fetch API types to represent * HTTP requests and responses. * * @param request The request received from the client initiating the session. * @param localMain The main stub or RpcTarget which the server wishes to expose to the client. * @param options Optional RPC session options. * @returns The HTTP response to return to the client. Note that the returned object has mutable * headers, so you can modify them using e.g. `response.headers.set("Foo", "bar")`. */ declare function newHttpBatchRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise; /** * Implements the server end of an HTTP batch session using traditional Node.js HTTP APIs. * * @param request The request received from the client initiating the session. * @param response The response object, to which the response should be written. * @param localMain The main stub or RpcTarget which the server wishes to expose to the client. * @param options Optional RPC session options. You can also pass headers to set on the response. */ declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: ServerResponse, localMain: any, options?: RpcSessionOptions & { headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]; }): Promise; //#endregion //#region src/index.d.ts /** * Represents a reference to a remote object, on which methods may be remotely invoked via RPC. * * `RpcStub` can represent any interface (when using TypeScript, you pass the specific interface * type as `T`, but this isn't known at runtime). The way this works is, `RpcStub` is actually a * `Proxy`. It makes itself appear as if every possible method / property name is defined. You can * invoke any method name, and the invocation will be sent to the server. If it turns out that no * such method exists on the remote object, an exception is thrown back. But the client does not * actually know, until that point, what methods exist. */ type RpcStub> = Stub; declare const RpcStub: { new >(value: T): RpcStub; }; /** * Represents the result of an RPC call. * * Also used to represent properties. That is, `stub.foo` evaluates to an `RpcPromise` for the * value of `foo`. * * This isn't actually a JavaScript `Promise`. It does, however, have `then()`, `catch()`, and * `finally()` methods, like `Promise` does, and because it has a `then()` method, JavaScript will * allow you to treat it like a promise, e.g. you can `await` it. * * An `RpcPromise` is also a proxy, just like `RpcStub`, where calling methods or awaiting * properties will make a pipelined network request. * * Note that and `RpcPromise` is "lazy": the actual final result is not requested from the server * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization: * if you only intend to use the promise for pipelining and you never await it, then there's no * need to transmit the resolution! */ type RpcPromise> = Stub & Promise>; declare const RpcPromise: {}; /** * Use to construct an `RpcSession` on top of a custom `RpcTransport`. * * Most people won't use this. You only need it if you've implemented your own `RpcTransport`. */ interface RpcSession = undefined> { getRemoteMain(): RpcStub; getStats(): { imports: number; exports: number; }; drain(): Promise; } declare const RpcSession: { new = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession; }; /** * Classes which are intended to be passed by reference and called over RPC must extend * `RpcTarget`. A class which does not extend `RpcTarget` (and which doesn't have built-in support * from the RPC system) cannot be passed in an RPC message at all; an exception will be thrown. * * Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the * "cloudflare:workers" module, so they can be used interchangably. */ interface RpcTarget extends RpcTargetBranded {} declare const RpcTarget: { new (): RpcTarget; }; /** * Empty interface used as default type parameter for sessions where the other side doesn't * necessarily export a main interface. */ interface Empty$1 {} /** * Start a WebSocket session given either an already-open WebSocket or a URL. * * @param webSocket Either the `wss://` URL to connect to, or an already-open WebSocket object to * use. * @param localMain The main RPC interface to expose to the peer. Returns a stub for the main * interface exposed from the peer. */ declare let newWebSocketRpcSession: = Empty$1>(webSocket: WebSocket | string, localMain?: any, options?: RpcSessionOptions) => RpcStub; /** * Initiate an HTTP batch session from the client side. * * The parameters to this method have exactly the same signature as `fetch()`, but the return * value is an RpcStub. You can customize anything about the request except for the method * (it will always be set to POST) and the body (which the RPC system will fill in). */ declare let newHttpBatchRpcSession: >(urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub; /** * Initiate an RPC session over a MessagePort, which is particularly useful for communicating * between an iframe and its parent frame in a browser context. Each side should call this function * on its own end of the MessageChannel. */ declare let newMessagePortRpcSession: = Empty$1>(port: MessagePort, localMain?: any, options?: RpcSessionOptions) => RpcStub; /** * Implements unified handling of HTTP-batch and WebSocket responses for the Cloudflare Workers * Runtime. * * SECURITY WARNING: This function accepts cross-origin requests. If you do not want this, you * should validate the `Origin` header before calling this, or use `newHttpBatchRpcSession()` and * `newWebSocketRpcSession()` directly with appropriate security measures for each type of request. * But if your API uses in-band authorization (i.e. it has an RPC method that takes the user's * credentials as parameters and returns the authorized API), then cross-origin requests should * be safe. */ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise; //#endregion //#region src/bun.d.ts type WsData = { __capnwebTransport: BunWebSocketTransport; __capnwebStub: RpcStub$1; }; /** * Create a Bun `WebSocketHandler` object that manages RPC sessions automatically. * * The returned object can be passed directly as the `websocket` option to `Bun.serve()`. * A fresh `localMain` is created for each connection via the `createMain` callback. * The transport is stored on `ws.data.__capnwebTransport`. * * @param createMain Called once per connection to create the main RPC interface for that client. * @param options Optional RPC session options applied to every connection. */ declare function newBunWebSocketRpcHandler(createMain: () => RpcTargetBranded, options?: RpcSessionOptions): { open(ws: ServerWebSocket): void; message(ws: ServerWebSocket, message: string | Buffer): void; close(ws: ServerWebSocket, code: number, reason: string): void; error(ws: ServerWebSocket, error: Error): void; }; declare class BunWebSocketTransport implements RpcTransport { #private; constructor(ws: ServerWebSocket); send(message: string): Promise; receive(): Promise; abort?(reason: any): void; dispatchMessage(data: string | Buffer): void; dispatchClose(code: number, reason: string): void; dispatchError(error: Error): void; } //#endregion //#region src/index-bun.d.ts interface Empty {} /** * Start an RPC session over a Bun ServerWebSocket. * * Returns both the RPC stub and the transport. The transport exposes `dispatchMessage`, * `dispatchClose`, and `dispatchError` methods that must be wired to Bun's `WebSocketHandler` * callbacks. For a zero-wiring alternative, use `newBunWebSocketRpcHandler` instead. * * @param ws The Bun ServerWebSocket from the `open` callback. * @param localMain The main RPC interface to expose to the peer. */ declare let newBunWebSocketRpcSession: = Empty, D = undefined>(ws: ServerWebSocket, localMain?: any, options?: RpcSessionOptions) => { stub: RpcStub; transport: BunWebSocketTransport; }; //#endregion export { type AnyRpcTransport, BunWebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, type EncodingLevel, type RpcCallInfo, type RpcCompatible, type RpcLimits, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize }; //# sourceMappingURL=index-bun.d.ts.map