capnweb 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,82 +1,456 @@
1
- import { _ as __RPC_TARGET_BRAND, R as RpcTransport, a as RpcTargetBranded, b as RpcSessionOptions, c as RpcCompatible, d as RpcStub$1 } from './index-workers-CiDKhXAE.cjs';
2
- export { e as RpcPromise, f as RpcSession, g as RpcTarget, h as deserialize, n as newHttpBatchRpcResponse, i as newHttpBatchRpcSession, j as newMessagePortRpcSession, k as newWebSocketRpcSession, l as newWorkersRpcResponse, m as newWorkersWebSocketRpcResponse, o as nodeHttpBatchRpcResponse, s as serialize } from './index-workers-CiDKhXAE.cjs';
3
- import { ServerWebSocket } from 'bun';
4
- import 'node:http';
1
+ import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
+ import { ServerWebSocket } from "bun";
5
3
 
6
- interface RpcTarget {
7
- [__RPC_TARGET_BRAND]: never;
4
+ //#region src/types.d.ts
5
+ // Copyright (c) 2025 Cloudflare, Inc.
6
+ // Licensed under the MIT license found in the LICENSE.txt file or at:
7
+ // https://opensource.org/license/mit
8
+ // This file borrows heavily from `types/defines/rpc.d.ts` in workerd.
9
+ // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
10
+ // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
11
+ // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
12
+ // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)
13
+ declare const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';
14
+ declare const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
15
+ // Distinguishes mapper placeholders from regular values so param unwrapping can accept them.
16
+ declare const __RPC_MAP_VALUE_BRAND: unique symbol;
17
+ interface RpcTargetBranded {
18
+ [__RPC_TARGET_BRAND]: never;
8
19
  }
9
- declare let RpcTarget: any;
20
+ // Types that can be used through `Stub`s
21
+ // `never[]` preserves compatibility with strongly-typed function signatures without introducing
22
+ // `any` into inference.
23
+ type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
24
+ type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
25
+ // The reason for using a generic type here is to build the serializable subset of RPC-compatible
26
+ // composite types. This allows types defined with the "interface" keyword to pass the
27
+ // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
28
+ type RpcCompatible<T> = // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
29
+ (IsUnknown<T> extends true ? unknown : never) // RPC-compatible base values
30
+ | BaseType // RPC-compatible composites
31
+ | Map<T extends Map<infer U, unknown> ? RpcCompatible<U> : never, T extends Map<unknown, infer U> ? RpcCompatible<U> : never> | Set<T extends Set<infer U> ? RpcCompatible<U> : never> | Array<T extends Array<infer U> ? RpcCompatible<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? RpcCompatible<U> : never> | { [K in keyof T as K extends string | number ? K : never]: RpcCompatible<T[K]> } | Promise<T extends Promise<infer U> ? RpcCompatible<U> : never> // Special types
32
+ | Stub<Stubable> // Serialized as stubs, see `Stubify`
33
+ | Stubable;
34
+ // Base type for all RPC stubs, including common memory management methods.
35
+ // `T` is used as a marker type for unwrapping `Stub`s later.
36
+ interface StubBase<T = unknown> extends Disposable {
37
+ [__RPC_STUB_BRAND]: T;
38
+ dup(): this;
39
+ onRpcBroken(callback: (error: any) => void): void;
40
+ }
41
+ type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
42
+ 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
43
+ type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<Uint8Array> | WritableStream<any> // Chunk type can be any RPC-compatible type
44
+ | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
45
+ // prettier-ignore
46
+ type Stubify<T> = T extends Stubable ? Stub<T> : T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>] : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified.
47
+ : T extends {
48
+ [key: string | number]: any;
49
+ } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
50
+ // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
51
+ // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
52
+ // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
53
+ // prettier-ignore
54
+ type UnstubifyInner<T> = // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
55
+ // is already assignable to the value type (important for callback contextual typing).
56
+ T extends StubBase<infer V> ? (T extends V ? UnstubifyInner<V> : (T | UnstubifyInner<V>)) : T extends Promise<infer U> ? UnstubifyInner<U> : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Unstubify<Head>, ...Unstubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Unstubify<Head>, ...Unstubify<Tail>] : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {
57
+ [key: string | number]: unknown;
58
+ } ? { [K in keyof T as K extends string | number ? K : never]: Unstubify<T[K]> } : T; // You can put promises anywhere in the params and they'll be resolved before delivery.
59
+ // (This also covers RpcPromise, because it's defined as being a Promise.)
60
+ // Map placeholders are also allowed so primitive map callback inputs can be forwarded directly
61
+ // into RPC params.
62
+ //
63
+ // Keep raw non-stub members so generic assignability still works when UnstubifyInner<T> is deferred.
64
+ // Remove stub members from mixed unions so callback params don’t get both stub and unstubbed signatures.
65
+ // Marker carried by map() callback inputs. This lets primitive placeholders flow through params.
66
+ type Unstubify<T> = NonStubMembers<T> | UnstubifyInner<T> | Promise<UnstubifyInner<T>> | MapValuePlaceholder<UnstubifyInner<T>>;
67
+ type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]> };
68
+ interface MapValuePlaceholder<T> {
69
+ [__RPC_MAP_VALUE_BRAND]: T;
70
+ }
71
+ type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
72
+ // Note `unknown & T` is equivalent to `T`.
73
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for method return or property on an RPC interface.
74
+ // - Stubable types are replaced by stubs.
75
+ // - RpcCompatible types are passed by value, with stubable types replaced by stubs
76
+ // and a top-level `Disposer`.
77
+ // Everything else can't be passed over RPC.
78
+ // Technically, we use custom thenables here, but they quack like `Promise`s.
79
+ // Intersecting with `(Maybe)Provider` allows pipelining.
80
+ // prettier-ignore
81
+ type Result<R> = IsAny<R> extends true ? UnknownResult : IsUnknown<R> extends true ? UnknownResult : R extends Stubable ? Promise<Stub<R>> & Provider<R> & StubBase<R> : R extends RpcCompatible<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & Provider<R> & StubBase<R> : never;
82
+ type IsAny<T> = 0 extends (1 & T) ? true : false;
83
+ type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
84
+ // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
85
+ // Unwrapping `Stub`s allows calling with `Stubable` arguments.
86
+ // For properties, rewrite types to be `Result`s.
87
+ // In each case, unwrap `Promise`s.
88
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => IsAny<R> extends true ? UnknownResult : Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
89
+ // This is intersected with methods/properties.
90
+ type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
91
+ type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
92
+ type MapCallbackValue<T> = // `Omit` removes call signatures, so re-intersect callable provider behavior.
93
+ T extends unknown ? Omit<Result<T>, keyof Promise<unknown>> & MaybeCallableProvider<T> & MapValuePlaceholder<T> : never;
94
+ type InvalidNativePromiseInMapResult<T, Seen = never> = T extends unknown ? InvalidNativePromiseInMapResultImpl<T, Seen> : never;
95
+ type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
96
+ : T extends StubBase<any> ? never // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
97
+ : T extends PromiseLike<unknown> ? T : T extends Map<infer K, infer V> ? InvalidNativePromiseInMapResult<K, Seen | T> | InvalidNativePromiseInMapResult<V, Seen | T> : T extends Set<infer V> ? InvalidNativePromiseInMapResult<V, Seen | T> : T extends readonly [] ? never : T extends readonly [infer Head, ...infer Tail] ? InvalidNativePromiseInMapResult<Head, Seen | T> | InvalidNativePromiseInMapResult<Tail[number], Seen | T> : T extends ReadonlyArray<infer V> ? InvalidNativePromiseInMapResult<V, Seen | T> : T extends {
98
+ [key: string | number]: unknown;
99
+ } ? InvalidNativePromiseInMapResult<T[Extract<keyof T, string | number>], Seen | T> : never;
100
+ type MapCallbackReturn<T> = InvalidNativePromiseInMapResult<T> extends never ? T : never;
101
+ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
102
+ map<V>(callback: (elem: MapCallbackValue<E>) => MapCallbackReturn<V>): Result<Array<V>>;
103
+ };
104
+ type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]> } & ArrayProvider<T[number]>; // Base type for all other types providing RPC-like interfaces.
105
+ // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
106
+ type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : { [K in Exclude<keyof T, symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]> } & {
107
+ map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
108
+ });
109
+ //#endregion
110
+ //#region src/core.d.ts
111
+ interface RpcTarget$1 {
112
+ [__RPC_TARGET_BRAND]: never;
113
+ }
114
+ declare let RpcTarget$1: any;
10
115
  type PropertyPath = (string | number)[];
11
116
  declare abstract class StubHook {
12
- abstract call(path: PropertyPath, args: RpcPayload): StubHook;
13
- stream(path: PropertyPath, args: RpcPayload): {
14
- promise: Promise<void>;
15
- size?: number;
16
- };
17
- abstract map(path: PropertyPath, captures: StubHook[], instructions: unknown[]): StubHook;
18
- abstract get(path: PropertyPath): StubHook;
19
- abstract dup(): StubHook;
20
- abstract pull(): RpcPayload | Promise<RpcPayload>;
21
- abstract ignoreUnhandledRejections(): void;
22
- abstract dispose(): void;
23
- abstract onBroken(callback: (error: any) => void): void;
117
+ abstract call(path: PropertyPath, args: RpcPayload): StubHook;
118
+ stream(path: PropertyPath, args: RpcPayload): {
119
+ promise: Promise<void>;
120
+ size?: number;
121
+ };
122
+ abstract map(path: PropertyPath, captures: StubHook[], instructions: unknown[]): StubHook;
123
+ abstract get(path: PropertyPath): StubHook;
124
+ abstract dup(): StubHook;
125
+ abstract pull(): RpcPayload | Promise<RpcPayload>;
126
+ abstract ignoreUnhandledRejections(): void;
127
+ abstract dispose(): void;
128
+ abstract onBroken(callback: (error: any) => void): void;
24
129
  }
25
130
  declare let RAW_STUB: symbol;
26
- interface RpcStub extends Disposable {
27
- }
28
- declare class RpcStub extends RpcTarget {
29
- [RAW_STUB]: this;
30
- constructor(hook: StubHook, pathIfPromise?: PropertyPath);
31
- hook: StubHook;
32
- pathIfPromise?: PropertyPath;
33
- dup(): RpcStub;
34
- onRpcBroken(callback: (error: any) => void): void;
35
- map(func: (value: RpcPromise) => unknown): RpcPromise;
36
- toString(): string;
131
+ interface RpcStub$1 extends Disposable {}
132
+ declare class RpcStub$1 extends RpcTarget$1 {
133
+ [RAW_STUB]: this;
134
+ constructor(hook: StubHook, pathIfPromise?: PropertyPath);
135
+ hook: StubHook;
136
+ pathIfPromise?: PropertyPath;
137
+ dup(): RpcStub$1;
138
+ onRpcBroken(callback: (error: any) => void): void;
139
+ map(func: (value: RpcPromise$1) => unknown): RpcPromise$1;
140
+ toString(): string;
37
141
  }
38
- declare class RpcPromise extends RpcStub {
39
- constructor(hook: StubHook, pathIfPromise: PropertyPath);
40
- then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
41
- catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
42
- finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
43
- toString(): string;
142
+ declare class RpcPromise$1 extends RpcStub$1 {
143
+ constructor(hook: StubHook, pathIfPromise: PropertyPath);
144
+ then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
145
+ catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
146
+ finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
147
+ toString(): string;
44
148
  }
45
149
  type LocatedPromise = {
46
- parent: object;
47
- property: string | number;
48
- promise: RpcPromise;
150
+ parent: object;
151
+ property: string | number;
152
+ promise: RpcPromise$1;
49
153
  };
50
154
  declare class RpcPayload {
51
- value: unknown;
52
- private source;
53
- private hooks?;
54
- private promises?;
55
- static fromAppParams(value: unknown): RpcPayload;
56
- static fromAppReturn(value: unknown): RpcPayload;
57
- static fromArray(array: RpcPayload[]): RpcPayload;
58
- static forEvaluate(hooks: StubHook[], promises: LocatedPromise[]): RpcPayload;
59
- static deepCopyFrom(value: unknown, oldParent: object | undefined, owner: RpcPayload | null): RpcPayload;
60
- private constructor();
61
- private rpcTargets?;
62
- getHookForRpcTarget(target: RpcTarget | Function, parent: object | undefined, dupStubs?: boolean): StubHook;
63
- getHookForWritableStream(stream: WritableStream, parent: object | undefined, dupStubs?: boolean): StubHook;
64
- getHookForReadableStream(stream: ReadableStream, parent: object | undefined, dupStubs?: boolean): StubHook;
65
- private deepCopy;
66
- ensureDeepCopied(): void;
67
- private deliverTo;
68
- private static deliverRpcPromiseTo;
69
- deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
70
- deliverResolve(): Promise<unknown>;
71
- dispose(): void;
72
- private disposeImpl;
73
- ignoreUnhandledRejections(): void;
74
- private ignoreUnhandledRejectionsImpl;
155
+ value: unknown;
156
+ private source;
157
+ private hooks?;
158
+ private promises?;
159
+ static fromAppParams(value: unknown): RpcPayload;
160
+ static fromAppReturn(value: unknown): RpcPayload;
161
+ static fromArray(array: RpcPayload[]): RpcPayload;
162
+ static forEvaluate(hooks: StubHook[], promises: LocatedPromise[]): RpcPayload;
163
+ static deepCopyFrom(value: unknown, oldParent: object | undefined, owner: RpcPayload | null): RpcPayload;
164
+ private constructor();
165
+ private rpcTargets?;
166
+ getHookForRpcTarget(target: RpcTarget$1 | Function, parent: object | undefined, dupStubs?: boolean): StubHook;
167
+ getHookForWritableStream(stream: WritableStream, parent: object | undefined, dupStubs?: boolean): StubHook;
168
+ getHookForReadableStream(stream: ReadableStream, parent: object | undefined, dupStubs?: boolean): StubHook;
169
+ private deepCopy;
170
+ ensureDeepCopied(): void;
171
+ private deliverTo;
172
+ private static deliverRpcPromiseTo;
173
+ deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
174
+ deliverResolve(): Promise<unknown>;
175
+ dispose(): void;
176
+ private disposeImpl;
177
+ ignoreUnhandledRejections(): void;
178
+ private ignoreUnhandledRejectionsImpl;
75
179
  }
76
-
180
+ //#endregion
181
+ //#region src/serialize.d.ts
182
+ /**
183
+ * Encoding levels determine what representation the RPC system hands to the transport.
184
+ * Each level names what the transport can assume about message values.
185
+ *
186
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
187
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
188
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
189
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
194
+ * "string" → '["bytes","AQID"]' // JSON string with base64
195
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
196
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
197
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
198
+ * ```
199
+ */
200
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
201
+ /**
202
+ * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
203
+ * RPC stubs, but it will support basic data types.
204
+ */
205
+ declare function serialize(value: unknown): string;
206
+ /**
207
+ * Deserialize a value serialized using serialize().
208
+ */
209
+ declare function deserialize(value: string): unknown;
210
+ //#endregion
211
+ //#region src/rpc.d.ts
212
+ /**
213
+ * Interface for a string-based RPC transport. This is the default transport type — no
214
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
215
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
216
+ */
217
+ interface RpcTransport {
218
+ /**
219
+ * The encoding level this transport works with. For this interface it is always "string";
220
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
221
+ */
222
+ readonly encodingLevel?: "string";
223
+ /**
224
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
225
+ * the session is aborted.
226
+ */
227
+ send(message: string): void | Promise<void>;
228
+ /**
229
+ * Receives a message sent by the other end.
230
+ *
231
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
232
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
233
+ * If there are no outstanding calls (and none are made in the future), then the error does not
234
+ * propagate anywhere -- this is considered a "clean" shutdown.
235
+ */
236
+ receive(): Promise<string>;
237
+ /**
238
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
239
+ * The transport should ideally try to send any queued messages if it can, and then close the
240
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
241
+ * before abort() is called is often an "abort" message, which communicates the error to the
242
+ * peer, so if that is dropped, the peer may have less information about what happened.)
243
+ */
244
+ abort?(reason: any): void;
245
+ }
246
+ /**
247
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
248
+ * The selected `encodingLevel` describes what the transport can assume about message values.
249
+ */
250
+ interface RpcTransportWithCustomEncoding {
251
+ /**
252
+ * The encoding level this transport works with.
253
+ *
254
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
255
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
256
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
257
+ */
258
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
259
+ /**
260
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
261
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
262
+ * flow control. Send errors should be propagated via `receive()` rejecting.
263
+ */
264
+ send(message: unknown): number | void;
265
+ /**
266
+ * Receives and decodes a message sent by the other end.
267
+ *
268
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
269
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
270
+ * If there are no outstanding calls (and none are made in the future), then the error does not
271
+ * propagate anywhere -- this is considered a "clean" shutdown.
272
+ */
273
+ receive(): Promise<unknown>;
274
+ /**
275
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
276
+ * The transport should ideally try to send any queued messages if it can, and then close the
277
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
278
+ * before abort() is called is often an "abort" message, which communicates the error to the
279
+ * peer, so if that is dropped, the peer may have less information about what happened.)
280
+ */
281
+ abort?(reason: any): void;
282
+ }
283
+ /** Any supported transport type. */
284
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
285
+ /**
286
+ * Options to customize behavior of an RPC session. All functions which start a session should
287
+ * optionally accept this.
288
+ */
289
+ type RpcSessionOptions = {
290
+ /**
291
+ * If provided, this function will be called whenever an `Error` object is serialized (for any
292
+ * reason, not just because it was thrown). This can be used to log errors, and also to redact
293
+ * them.
294
+ *
295
+ * If `onSendError` returns an Error object, than object will be substituted in place of the
296
+ * original. If it has a stack property, the stack will be sent to the client.
297
+ *
298
+ * If `onSendError` doesn't return anything (or is not provided at all), the default behavior is
299
+ * to serialize the error with the stack omitted.
300
+ */
301
+ onSendError?: (error: Error) => Error | void;
302
+ };
303
+ //#endregion
304
+ //#region src/websocket.d.ts
305
+ /**
306
+ * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
307
+ * with the given `localMain`.
308
+ */
309
+ declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
310
+ /**
311
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
312
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
313
+ */
314
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
315
+ #private;
316
+ constructor(webSocket: WebSocket);
317
+ send(message: T): void;
318
+ receive(): Promise<T>;
319
+ abort(reason: any): void;
320
+ }
321
+ //#endregion
322
+ //#region src/batch.d.ts
323
+ /**
324
+ * Implements the server end of an HTTP batch session, using standard Fetch API types to represent
325
+ * HTTP requests and responses.
326
+ *
327
+ * @param request The request received from the client initiating the session.
328
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
329
+ * @param options Optional RPC session options.
330
+ * @returns The HTTP response to return to the client. Note that the returned object has mutable
331
+ * headers, so you can modify them using e.g. `response.headers.set("Foo", "bar")`.
332
+ */
333
+ declare function newHttpBatchRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
334
+ /**
335
+ * Implements the server end of an HTTP batch session using traditional Node.js HTTP APIs.
336
+ *
337
+ * @param request The request received from the client initiating the session.
338
+ * @param response The response object, to which the response should be written.
339
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
340
+ * @param options Optional RPC session options. You can also pass headers to set on the response.
341
+ */
342
+ declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: ServerResponse, localMain: any, options?: RpcSessionOptions & {
343
+ headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
344
+ }): Promise<void>;
345
+ //#endregion
346
+ //#region src/index.d.ts
347
+ /**
348
+ * Represents a reference to a remote object, on which methods may be remotely invoked via RPC.
349
+ *
350
+ * `RpcStub` can represent any interface (when using TypeScript, you pass the specific interface
351
+ * type as `T`, but this isn't known at runtime). The way this works is, `RpcStub` is actually a
352
+ * `Proxy`. It makes itself appear as if every possible method / property name is defined. You can
353
+ * invoke any method name, and the invocation will be sent to the server. If it turns out that no
354
+ * such method exists on the remote object, an exception is thrown back. But the client does not
355
+ * actually know, until that point, what methods exist.
356
+ */
357
+ type RpcStub<T extends RpcCompatible<T>> = Stub<T>;
358
+ declare const RpcStub: {
359
+ new <T extends RpcCompatible<T>>(value: T): RpcStub<T>;
360
+ };
361
+ /**
362
+ * Represents the result of an RPC call.
363
+ *
364
+ * Also used to represent properties. That is, `stub.foo` evaluates to an `RpcPromise` for the
365
+ * value of `foo`.
366
+ *
367
+ * This isn't actually a JavaScript `Promise`. It does, however, have `then()`, `catch()`, and
368
+ * `finally()` methods, like `Promise` does, and because it has a `then()` method, JavaScript will
369
+ * allow you to treat it like a promise, e.g. you can `await` it.
370
+ *
371
+ * An `RpcPromise` is also a proxy, just like `RpcStub`, where calling methods or awaiting
372
+ * properties will make a pipelined network request.
373
+ *
374
+ * Note that and `RpcPromise` is "lazy": the actual final result is not requested from the server
375
+ * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
376
+ * if you only intend to use the promise for pipelining and you never await it, then there's no
377
+ * need to transmit the resolution!
378
+ */
379
+ type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
380
+ declare const RpcPromise: {};
381
+ /**
382
+ * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
383
+ *
384
+ * Most people won't use this. You only need it if you've implemented your own `RpcTransport`.
385
+ */
386
+ interface RpcSession<T extends RpcCompatible<T> = undefined> {
387
+ getRemoteMain(): RpcStub<T>;
388
+ getStats(): {
389
+ imports: number;
390
+ exports: number;
391
+ };
392
+ drain(): Promise<void>;
393
+ }
394
+ declare const RpcSession: {
395
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
396
+ };
397
+ /**
398
+ * Classes which are intended to be passed by reference and called over RPC must extend
399
+ * `RpcTarget`. A class which does not extend `RpcTarget` (and which doesn't have built-in support
400
+ * from the RPC system) cannot be passed in an RPC message at all; an exception will be thrown.
401
+ *
402
+ * Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the
403
+ * "cloudflare:workers" module, so they can be used interchangably.
404
+ */
405
+ interface RpcTarget extends RpcTargetBranded {}
406
+ declare const RpcTarget: {
407
+ new (): RpcTarget;
408
+ };
409
+ /**
410
+ * Empty interface used as default type parameter for sessions where the other side doesn't
411
+ * necessarily export a main interface.
412
+ */
413
+ interface Empty$1 {}
414
+ /**
415
+ * Start a WebSocket session given either an already-open WebSocket or a URL.
416
+ *
417
+ * @param webSocket Either the `wss://` URL to connect to, or an already-open WebSocket object to
418
+ * use.
419
+ * @param localMain The main RPC interface to expose to the peer. Returns a stub for the main
420
+ * interface exposed from the peer.
421
+ */
422
+ declare let newWebSocketRpcSession: <T extends RpcCompatible<T> = Empty$1>(webSocket: WebSocket | string, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
423
+ /**
424
+ * Initiate an HTTP batch session from the client side.
425
+ *
426
+ * The parameters to this method have exactly the same signature as `fetch()`, but the return
427
+ * value is an RpcStub. You can customize anything about the request except for the method
428
+ * (it will always be set to POST) and the body (which the RPC system will fill in).
429
+ */
430
+ declare let newHttpBatchRpcSession: <T extends RpcCompatible<T>>(urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub<T>;
431
+ /**
432
+ * Initiate an RPC session over a MessagePort, which is particularly useful for communicating
433
+ * between an iframe and its parent frame in a browser context. Each side should call this function
434
+ * on its own end of the MessageChannel.
435
+ */
436
+ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty$1>(port: MessagePort, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
437
+ /**
438
+ * Implements unified handling of HTTP-batch and WebSocket responses for the Cloudflare Workers
439
+ * Runtime.
440
+ *
441
+ * SECURITY WARNING: This function accepts cross-origin requests. If you do not want this, you
442
+ * should validate the `Origin` header before calling this, or use `newHttpBatchRpcSession()` and
443
+ * `newWebSocketRpcSession()` directly with appropriate security measures for each type of request.
444
+ * But if your API uses in-band authorization (i.e. it has an RPC method that takes the user's
445
+ * credentials as parameters and returns the authorized API), then cross-origin requests should
446
+ * be safe.
447
+ */
448
+ declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
449
+ //#endregion
450
+ //#region src/bun.d.ts
77
451
  type WsData = {
78
- __capnwebTransport: BunWebSocketTransport<WsData>;
79
- __capnwebStub: RpcStub;
452
+ __capnwebTransport: BunWebSocketTransport<WsData>;
453
+ __capnwebStub: RpcStub$1;
80
454
  };
81
455
  /**
82
456
  * Create a Bun `WebSocketHandler` object that manages RPC sessions automatically.
@@ -89,24 +463,24 @@ type WsData = {
89
463
  * @param options Optional RPC session options applied to every connection.
90
464
  */
91
465
  declare function newBunWebSocketRpcHandler(createMain: () => RpcTargetBranded, options?: RpcSessionOptions): {
92
- open(ws: ServerWebSocket<WsData>): void;
93
- message(ws: ServerWebSocket<WsData>, message: string | Buffer): void;
94
- close(ws: ServerWebSocket<WsData>, code: number, reason: string): void;
95
- error(ws: ServerWebSocket<WsData>, error: Error): void;
466
+ open(ws: ServerWebSocket<WsData>): void;
467
+ message(ws: ServerWebSocket<WsData>, message: string | Buffer): void;
468
+ close(ws: ServerWebSocket<WsData>, code: number, reason: string): void;
469
+ error(ws: ServerWebSocket<WsData>, error: Error): void;
96
470
  };
97
471
  declare class BunWebSocketTransport<T = undefined> implements RpcTransport {
98
- #private;
99
- constructor(ws: ServerWebSocket<T>);
100
- send(message: string): Promise<void>;
101
- receive(): Promise<string>;
102
- abort?(reason: any): void;
103
- dispatchMessage(data: string | Buffer): void;
104
- dispatchClose(code: number, reason: string): void;
105
- dispatchError(error: Error): void;
106
- }
107
-
108
- interface Empty {
472
+ #private;
473
+ constructor(ws: ServerWebSocket<T>);
474
+ send(message: string): Promise<void>;
475
+ receive(): Promise<string>;
476
+ abort?(reason: any): void;
477
+ dispatchMessage(data: string | Buffer): void;
478
+ dispatchClose(code: number, reason: string): void;
479
+ dispatchError(error: Error): void;
109
480
  }
481
+ //#endregion
482
+ //#region src/index-bun.d.ts
483
+ interface Empty {}
110
484
  /**
111
485
  * Start an RPC session over a Bun ServerWebSocket.
112
486
  *
@@ -118,8 +492,9 @@ interface Empty {
118
492
  * @param localMain The main RPC interface to expose to the peer.
119
493
  */
120
494
  declare let newBunWebSocketRpcSession: <T extends RpcCompatible<T> = Empty, D = undefined>(ws: ServerWebSocket<D>, localMain?: any, options?: RpcSessionOptions) => {
121
- stub: RpcStub$1<T>;
122
- transport: BunWebSocketTransport<D>;
495
+ stub: RpcStub<T>;
496
+ transport: BunWebSocketTransport<D>;
123
497
  };
124
-
125
- export { BunWebSocketTransport, RpcCompatible, RpcSessionOptions, RpcStub$1 as RpcStub, RpcTransport, newBunWebSocketRpcHandler, newBunWebSocketRpcSession };
498
+ //#endregion
499
+ export { type AnyRpcTransport, BunWebSocketTransport, type EncodingLevel, type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
500
+ //# sourceMappingURL=index-bun.d.cts.map