capnweb 0.0.0-952a541 → 0.0.0-9751a4e

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.
@@ -20,7 +20,8 @@ interface RpcTargetBranded {
20
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
21
  // `any` into inference.
22
22
  type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
23
- type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false; // Types that can be passed over RPC
24
25
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
26
  // composite types. This allows types defined with the "interface" keyword to pass the
26
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
@@ -39,10 +40,17 @@ interface StubBase<T = unknown> extends Disposable {
39
40
  }
40
41
  type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
41
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
42
- 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
43
- | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
43
+ type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<any> // Chunk type can be any RPC-compatible type
44
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
45
+ | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
46
+ // Arm ordering matters here:
47
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
48
+ // through the Promise arm rather than pass through as-is.
49
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
50
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
51
+ // double-wrapping them as `Stub<Stub<T>>`.
44
52
  // prettier-ignore
45
- 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.
53
+ type Stubify<T> = T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Stubable ? Stub<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.
46
54
  : T extends {
47
55
  [key: string | number]: any;
48
56
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -69,7 +77,22 @@ interface MapValuePlaceholder<T> {
69
77
  }
70
78
  type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
71
79
  // Note `unknown & T` is equivalent to `T`.
72
- type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for method return or property on an RPC interface.
80
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
81
+ // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
82
+ // instantiation: when both sides of an assignability check are the same alias applied to the
83
+ // same type arguments, the checker short-circuits on identity instead of recursing through the
84
+ // full structural comparison of these mutually-recursive types.
85
+ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
86
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
87
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
88
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
89
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
90
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
91
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
92
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
93
+ // guard an `any`-payload stub would lose its stub surface.
94
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
95
+ // Type for method return or property on an RPC interface.
73
96
  // - Stubable types are replaced by stubs.
74
97
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
75
98
  // and a top-level `Disposer`.
@@ -77,14 +100,20 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
77
100
  // Technically, we use custom thenables here, but they quack like `Promise`s.
78
101
  // Intersecting with `(Maybe)Provider` allows pipelining.
79
102
  // prettier-ignore
80
- 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;
81
- type IsAny<T> = 0 extends (1 & T) ? true : false;
82
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
103
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
104
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
105
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
106
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
107
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
108
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
109
+ // types.
110
+ : R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
111
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
83
112
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
84
113
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
85
114
  // For properties, rewrite types to be `Result`s.
86
115
  // In each case, unwrap `Promise`s.
87
- 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.
116
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
88
117
  // This is intersected with methods/properties.
89
118
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
90
119
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -102,11 +131,40 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
102
131
  };
103
132
  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.
104
133
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
134
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
135
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
136
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
105
137
  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]> } & {
106
138
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
107
139
  });
108
140
  //#endregion
109
141
  //#region src/serialize.d.ts
142
+ /**
143
+ * Encoding levels determine what representation the RPC system hands to the transport.
144
+ * Each level names what the transport can assume about message values.
145
+ *
146
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
147
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
148
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
149
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
154
+ * "string" → '["bytes","AQID"]' // JSON string with base64
155
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
156
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
157
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
158
+ * ```
159
+ */
160
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
161
+ interface RpcLimits {
162
+ maxBigIntDigits: number;
163
+ maxDepth: number;
164
+ maxMessageSize: number;
165
+ }
166
+ declare const DEFAULT_MAX_DEPTH = 256;
167
+ declare const DEFAULT_LIMITS: RpcLimits;
110
168
  /**
111
169
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
112
170
  * RPC stubs, but it will support basic data types.
@@ -119,14 +177,21 @@ declare function deserialize(value: string): unknown;
119
177
  //#endregion
120
178
  //#region src/rpc.d.ts
121
179
  /**
122
- * Interface for an RPC transport, which is a simple bidirectional message stream. Implement this
123
- * interface if the built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
180
+ * Interface for a string-based RPC transport. This is the default transport type — no
181
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
182
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
124
183
  */
125
184
  interface RpcTransport {
126
185
  /**
127
- * Sends a message to the other end.
186
+ * The encoding level this transport works with. For this interface it is always "string";
187
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
128
188
  */
129
- send(message: string): Promise<void>;
189
+ readonly encodingLevel?: "string";
190
+ /**
191
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
192
+ * the session is aborted.
193
+ */
194
+ send(message: string): void | Promise<void>;
130
195
  /**
131
196
  * Receives a message sent by the other end.
132
197
  *
@@ -145,6 +210,45 @@ interface RpcTransport {
145
210
  */
146
211
  abort?(reason: any): void;
147
212
  }
213
+ /**
214
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
215
+ * The selected `encodingLevel` describes what the transport can assume about message values.
216
+ */
217
+ interface RpcTransportWithCustomEncoding {
218
+ /**
219
+ * The encoding level this transport works with.
220
+ *
221
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
222
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
223
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
224
+ */
225
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
226
+ /**
227
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
228
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
229
+ * flow control. Send errors should be propagated via `receive()` rejecting.
230
+ */
231
+ send(message: unknown): number | void;
232
+ /**
233
+ * Receives and decodes a message sent by the other end.
234
+ *
235
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
236
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
237
+ * If there are no outstanding calls (and none are made in the future), then the error does not
238
+ * propagate anywhere -- this is considered a "clean" shutdown.
239
+ */
240
+ receive(): Promise<unknown>;
241
+ /**
242
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
243
+ * The transport should ideally try to send any queued messages if it can, and then close the
244
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
245
+ * before abort() is called is often an "abort" message, which communicates the error to the
246
+ * peer, so if that is dropped, the peer may have less information about what happened.)
247
+ */
248
+ abort?(reason: any): void;
249
+ }
250
+ /** Any supported transport type. */
251
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
148
252
  /**
149
253
  * Options to customize behavior of an RPC session. All functions which start a session should
150
254
  * optionally accept this.
@@ -162,6 +266,16 @@ type RpcSessionOptions = {
162
266
  * to serialize the error with the stack omitted.
163
267
  */
164
268
  onSendError?: (error: Error) => Error | void;
269
+ /**
270
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
271
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
272
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
273
+ *
274
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
275
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
276
+ * session.
277
+ */
278
+ limits?: Partial<RpcLimits>;
165
279
  };
166
280
  //#endregion
167
281
  //#region src/websocket.d.ts
@@ -170,6 +284,17 @@ type RpcSessionOptions = {
170
284
  * with the given `localMain`.
171
285
  */
172
286
  declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
287
+ /**
288
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
289
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
290
+ */
291
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
292
+ #private;
293
+ constructor(webSocket: WebSocket);
294
+ send(message: T): void;
295
+ receive(): Promise<T>;
296
+ abort(reason: any): void;
297
+ }
173
298
  //#endregion
174
299
  //#region src/batch.d.ts
175
300
  /**
@@ -227,9 +352,20 @@ declare const RpcStub: {
227
352
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
228
353
  * if you only intend to use the promise for pipelining and you never await it, then there's no
229
354
  * need to transmit the resolution!
355
+ *
356
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
357
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
358
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
359
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
360
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
361
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
362
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
363
+ * with a `dup()` if you also intend to keep the stub.
230
364
  */
231
- type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
232
- declare const RpcPromise: {};
365
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
366
+ declare const RpcPromise: {
367
+ new <T extends RpcCompatible<T>>(value: Promise<T | Stub<T>>): RpcPromise<T>;
368
+ };
233
369
  /**
234
370
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
235
371
  *
@@ -244,7 +380,7 @@ interface RpcSession<T extends RpcCompatible<T> = undefined> {
244
380
  drain(): Promise<void>;
245
381
  }
246
382
  declare const RpcSession: {
247
- new <T extends RpcCompatible<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
383
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
248
384
  };
249
385
  /**
250
386
  * Classes which are intended to be passed by reference and called over RPC must extend
@@ -297,7 +433,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty>(port:
297
433
  * credentials as parameters and returns the authorized API), then cross-origin requests should
298
434
  * be safe.
299
435
  */
300
- declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
436
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
301
437
  //#endregion
302
- export { type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
438
+ export { type AnyRpcTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, type EncodingLevel, type RpcCompatible, type RpcLimits, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
303
439
  //# sourceMappingURL=index-workers.d.cts.map
@@ -20,7 +20,8 @@ interface RpcTargetBranded {
20
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
21
  // `any` into inference.
22
22
  type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
23
- type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false; // Types that can be passed over RPC
24
25
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
26
  // composite types. This allows types defined with the "interface" keyword to pass the
26
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
@@ -39,10 +40,17 @@ interface StubBase<T = unknown> extends Disposable {
39
40
  }
40
41
  type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
41
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
42
- 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
43
- | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
43
+ type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<any> // Chunk type can be any RPC-compatible type
44
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
45
+ | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
46
+ // Arm ordering matters here:
47
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
48
+ // through the Promise arm rather than pass through as-is.
49
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
50
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
51
+ // double-wrapping them as `Stub<Stub<T>>`.
44
52
  // prettier-ignore
45
- 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.
53
+ type Stubify<T> = T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Stubable ? Stub<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.
46
54
  : T extends {
47
55
  [key: string | number]: any;
48
56
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -69,7 +77,22 @@ interface MapValuePlaceholder<T> {
69
77
  }
70
78
  type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
71
79
  // Note `unknown & T` is equivalent to `T`.
72
- type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for method return or property on an RPC interface.
80
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
81
+ // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
82
+ // instantiation: when both sides of an assignability check are the same alias applied to the
83
+ // same type arguments, the checker short-circuits on identity instead of recursing through the
84
+ // full structural comparison of these mutually-recursive types.
85
+ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
86
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
87
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
88
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
89
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
90
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
91
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
92
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
93
+ // guard an `any`-payload stub would lose its stub surface.
94
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
95
+ // Type for method return or property on an RPC interface.
73
96
  // - Stubable types are replaced by stubs.
74
97
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
75
98
  // and a top-level `Disposer`.
@@ -77,14 +100,20 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
77
100
  // Technically, we use custom thenables here, but they quack like `Promise`s.
78
101
  // Intersecting with `(Maybe)Provider` allows pipelining.
79
102
  // prettier-ignore
80
- 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;
81
- type IsAny<T> = 0 extends (1 & T) ? true : false;
82
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
103
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
104
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
105
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
106
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
107
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
108
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
109
+ // types.
110
+ : R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
111
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
83
112
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
84
113
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
85
114
  // For properties, rewrite types to be `Result`s.
86
115
  // In each case, unwrap `Promise`s.
87
- 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.
116
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
88
117
  // This is intersected with methods/properties.
89
118
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
90
119
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -102,11 +131,40 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
102
131
  };
103
132
  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.
104
133
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
134
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
135
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
136
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
105
137
  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]> } & {
106
138
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
107
139
  });
108
140
  //#endregion
109
141
  //#region src/serialize.d.ts
142
+ /**
143
+ * Encoding levels determine what representation the RPC system hands to the transport.
144
+ * Each level names what the transport can assume about message values.
145
+ *
146
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
147
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
148
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
149
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
154
+ * "string" → '["bytes","AQID"]' // JSON string with base64
155
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
156
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
157
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
158
+ * ```
159
+ */
160
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
161
+ interface RpcLimits {
162
+ maxBigIntDigits: number;
163
+ maxDepth: number;
164
+ maxMessageSize: number;
165
+ }
166
+ declare const DEFAULT_MAX_DEPTH = 256;
167
+ declare const DEFAULT_LIMITS: RpcLimits;
110
168
  /**
111
169
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
112
170
  * RPC stubs, but it will support basic data types.
@@ -119,14 +177,21 @@ declare function deserialize(value: string): unknown;
119
177
  //#endregion
120
178
  //#region src/rpc.d.ts
121
179
  /**
122
- * Interface for an RPC transport, which is a simple bidirectional message stream. Implement this
123
- * interface if the built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
180
+ * Interface for a string-based RPC transport. This is the default transport type — no
181
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
182
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
124
183
  */
125
184
  interface RpcTransport {
126
185
  /**
127
- * Sends a message to the other end.
186
+ * The encoding level this transport works with. For this interface it is always "string";
187
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
128
188
  */
129
- send(message: string): Promise<void>;
189
+ readonly encodingLevel?: "string";
190
+ /**
191
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
192
+ * the session is aborted.
193
+ */
194
+ send(message: string): void | Promise<void>;
130
195
  /**
131
196
  * Receives a message sent by the other end.
132
197
  *
@@ -145,6 +210,45 @@ interface RpcTransport {
145
210
  */
146
211
  abort?(reason: any): void;
147
212
  }
213
+ /**
214
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
215
+ * The selected `encodingLevel` describes what the transport can assume about message values.
216
+ */
217
+ interface RpcTransportWithCustomEncoding {
218
+ /**
219
+ * The encoding level this transport works with.
220
+ *
221
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
222
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
223
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
224
+ */
225
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
226
+ /**
227
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
228
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
229
+ * flow control. Send errors should be propagated via `receive()` rejecting.
230
+ */
231
+ send(message: unknown): number | void;
232
+ /**
233
+ * Receives and decodes a message sent by the other end.
234
+ *
235
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
236
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
237
+ * If there are no outstanding calls (and none are made in the future), then the error does not
238
+ * propagate anywhere -- this is considered a "clean" shutdown.
239
+ */
240
+ receive(): Promise<unknown>;
241
+ /**
242
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
243
+ * The transport should ideally try to send any queued messages if it can, and then close the
244
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
245
+ * before abort() is called is often an "abort" message, which communicates the error to the
246
+ * peer, so if that is dropped, the peer may have less information about what happened.)
247
+ */
248
+ abort?(reason: any): void;
249
+ }
250
+ /** Any supported transport type. */
251
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
148
252
  /**
149
253
  * Options to customize behavior of an RPC session. All functions which start a session should
150
254
  * optionally accept this.
@@ -162,6 +266,16 @@ type RpcSessionOptions = {
162
266
  * to serialize the error with the stack omitted.
163
267
  */
164
268
  onSendError?: (error: Error) => Error | void;
269
+ /**
270
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
271
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
272
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
273
+ *
274
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
275
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
276
+ * session.
277
+ */
278
+ limits?: Partial<RpcLimits>;
165
279
  };
166
280
  //#endregion
167
281
  //#region src/websocket.d.ts
@@ -170,6 +284,17 @@ type RpcSessionOptions = {
170
284
  * with the given `localMain`.
171
285
  */
172
286
  declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
287
+ /**
288
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
289
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
290
+ */
291
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
292
+ #private;
293
+ constructor(webSocket: WebSocket);
294
+ send(message: T): void;
295
+ receive(): Promise<T>;
296
+ abort(reason: any): void;
297
+ }
173
298
  //#endregion
174
299
  //#region src/batch.d.ts
175
300
  /**
@@ -227,9 +352,20 @@ declare const RpcStub: {
227
352
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
228
353
  * if you only intend to use the promise for pipelining and you never await it, then there's no
229
354
  * need to transmit the resolution!
355
+ *
356
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
357
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
358
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
359
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
360
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
361
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
362
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
363
+ * with a `dup()` if you also intend to keep the stub.
230
364
  */
231
- type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
232
- declare const RpcPromise: {};
365
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
366
+ declare const RpcPromise: {
367
+ new <T extends RpcCompatible<T>>(value: Promise<T | Stub<T>>): RpcPromise<T>;
368
+ };
233
369
  /**
234
370
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
235
371
  *
@@ -244,7 +380,7 @@ interface RpcSession<T extends RpcCompatible<T> = undefined> {
244
380
  drain(): Promise<void>;
245
381
  }
246
382
  declare const RpcSession: {
247
- new <T extends RpcCompatible<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
383
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
248
384
  };
249
385
  /**
250
386
  * Classes which are intended to be passed by reference and called over RPC must extend
@@ -297,7 +433,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty>(port:
297
433
  * credentials as parameters and returns the authorized API), then cross-origin requests should
298
434
  * be safe.
299
435
  */
300
- declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
436
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
301
437
  //#endregion
302
- export { type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
438
+ export { type AnyRpcTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, type EncodingLevel, type RpcCompatible, type RpcLimits, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
303
439
  //# sourceMappingURL=index-workers.d.ts.map