capnweb 0.0.0-cfa1b95 → 0.0.0-d33df03

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,11 +1,9 @@
1
- import { IncomingMessage, ServerResponse, OutgoingHttpHeaders, OutgoingHttpHeader } from 'node:http';
2
-
1
+ import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
+ //#region src/types.d.ts
3
3
  // Copyright (c) 2025 Cloudflare, Inc.
4
4
  // Licensed under the MIT license found in the LICENSE.txt file or at:
5
5
  // https://opensource.org/license/mit
6
-
7
6
  // This file borrows heavily from `types/defines/rpc.d.ts` in workerd.
8
-
9
7
  // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
10
8
  // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
11
9
  // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
@@ -17,40 +15,27 @@ declare const __RPC_MAP_VALUE_BRAND: unique symbol;
17
15
  interface RpcTargetBranded {
18
16
  [__RPC_TARGET_BRAND]: never;
19
17
  }
20
-
21
18
  // Types that can be used through `Stub`s
22
19
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
23
20
  // `any` into inference.
24
21
  type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
25
-
26
- type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false;
27
-
22
+ // Note: also true for `any` (call sites that care check `IsAny` first).
23
+ type IsUnknown<T> = unknown extends T ? true : false;
28
24
  // Types that can be passed over RPC
29
- // The reason for using a generic type here is to build a serializable subset of structured
30
- // cloneable composite types. This allows types defined with the "interface" keyword to pass the
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
31
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
32
28
  type RpcCompatible<T> =
33
- // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
34
- | (IsUnknown<T> extends true ? unknown : never)
35
- // Structured cloneables
36
- | BaseType
37
- // Structured cloneable composites
38
- | Map<
39
- T extends Map<infer U, unknown> ? RpcCompatible<U> : never,
40
- T extends Map<unknown, infer U> ? RpcCompatible<U> : never
41
- >
42
- | Set<T extends Set<infer U> ? RpcCompatible<U> : never>
43
- | Array<T extends Array<infer U> ? RpcCompatible<U> : never>
44
- | ReadonlyArray<T extends ReadonlyArray<infer U> ? RpcCompatible<U> : never>
45
- | {
46
- [K in keyof T as K extends string | number ? K : never]: RpcCompatible<T[K]>;
47
- }
48
- | Promise<T extends Promise<infer U> ? RpcCompatible<U> : never>
49
- // Special types
50
- | Stub<Stubable>
51
- // Serialized as stubs, see `Stubify`
52
- | Stubable;
53
-
29
+ // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
30
+ (IsUnknown<T> extends true ? unknown : never) |
31
+ // RPC-compatible base values
32
+ BaseType |
33
+ // RPC-compatible composites
34
+ 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> |
35
+ // Special types
36
+ Stub<Stubable> |
37
+ // Serialized as stubs, see `Stubify`
38
+ Stubable;
54
39
  // Base type for all RPC stubs, including common memory management methods.
55
40
  // `T` is used as a marker type for unwrapping `Stub`s later.
56
41
  interface StubBase<T = unknown> extends Disposable {
@@ -58,82 +43,35 @@ interface StubBase<T = unknown> extends Disposable {
58
43
  dup(): this;
59
44
  onRpcBroken(callback: (error: any) => void): void;
60
45
  }
61
- type Stub<T extends RpcCompatible<T>> =
62
- T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
63
-
64
- type TypedArray =
65
- | Uint8Array
66
- | Uint8ClampedArray
67
- | Uint16Array
68
- | Uint32Array
69
- | Int8Array
70
- | Int16Array
71
- | Int32Array
72
- | BigUint64Array
73
- | BigInt64Array
74
- | Float32Array
75
- | Float64Array;
76
-
46
+ type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
47
+ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array;
77
48
  // This represents all the types that can be sent as-is over an RPC boundary
78
- type BaseType =
79
- | void
80
- | undefined
81
- | null
82
- | boolean
83
- | number
84
- | bigint
85
- | string
86
- | TypedArray
87
- | ArrayBuffer
88
- | DataView
89
- | Date
90
- | Error
91
- | RegExp
92
- | ReadableStream<Uint8Array>
93
- | WritableStream<any> // Chunk type can be any RPC-compatible type
94
- | Request
95
- | Response
96
- | Headers;
49
+ 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
50
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
51
+ | URL | Request | Response | Headers;
97
52
  // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
53
+ // Arm ordering matters here:
54
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
55
+ // through the Promise arm rather than pass through as-is.
56
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
57
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
58
+ // double-wrapping them as `Stub<Stub<T>>`.
98
59
  // prettier-ignore
99
- type Stubify<T> =
100
- T extends Stubable ? Stub<T>
101
- : T extends Promise<infer U> ? Stubify<U>
102
- : T extends StubBase<any> ? T
103
- : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>>
104
- : T extends Set<infer V> ? Set<Stubify<V>>
105
- : T extends [] ? []
106
- : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>]
107
- : T extends readonly [] ? readonly []
108
- : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>]
109
- : T extends Array<infer V> ? Array<Stubify<V>>
110
- : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>>
111
- : T extends BaseType ? T
112
- // When using "unknown" instead of "any", interfaces are not stubified.
113
- : T extends { [key: string | number]: any } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> }
114
- : T;
115
-
60
+ 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 :
61
+ // When using "unknown" instead of "any", interfaces are not stubified.
62
+ T extends {
63
+ [key: string | number]: any;
64
+ } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]>; } : T;
116
65
  // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
117
66
  // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
118
67
  // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
119
68
  // prettier-ignore
120
69
  type UnstubifyInner<T> =
121
- // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
122
- // is already assignable to the value type (important for callback contextual typing).
123
- T extends StubBase<infer V> ? (T extends V ? UnstubifyInner<V> : (T | UnstubifyInner<V>))
124
- : T extends Promise<infer U> ? UnstubifyInner<U>
125
- : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>>
126
- : T extends Set<infer V> ? Set<Unstubify<V>>
127
- : T extends [] ? []
128
- : T extends [infer Head, ...infer Tail] ? [Unstubify<Head>, ...Unstubify<Tail>]
129
- : T extends readonly [] ? readonly []
130
- : T extends readonly [infer Head, ...infer Tail] ? readonly [Unstubify<Head>, ...Unstubify<Tail>]
131
- : T extends Array<infer V> ? Array<Unstubify<V>>
132
- : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>>
133
- : T extends BaseType ? T
134
- : T extends { [key: string | number]: unknown } ? { [K in keyof T as K extends string | number ? K : never]: Unstubify<T[K]> }
135
- : T;
136
-
70
+ // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
71
+ // is already assignable to the value type (important for callback contextual typing).
72
+ 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 {
73
+ [key: string | number]: unknown;
74
+ } ? { [K in keyof T as K extends string | number ? K : never]: Unstubify<T[K]>; } : T;
137
75
  // You can put promises anywhere in the params and they'll be resolved before delivery.
138
76
  // (This also covers RpcPromise, because it's defined as being a Promise.)
139
77
  // Map placeholders are also allowed so primitive map callback inputs can be forwarded directly
@@ -142,24 +80,39 @@ type UnstubifyInner<T> =
142
80
  // Keep raw non-stub members so generic assignability still works when UnstubifyInner<T> is deferred.
143
81
  // Remove stub members from mixed unions so callback params don’t get both stub and unstubbed signatures.
144
82
  // Marker carried by map() callback inputs. This lets primitive placeholders flow through params.
145
- type Unstubify<T> =
146
- | NonStubMembers<T>
147
- | UnstubifyInner<T>
148
- | Promise<UnstubifyInner<T>>
149
- | MapValuePlaceholder<UnstubifyInner<T>>;
150
-
151
- type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]> };
152
-
83
+ type Unstubify<T> = NonStubMembers<T> | UnstubifyInner<T> | Promise<UnstubifyInner<T>> | MapValuePlaceholder<UnstubifyInner<T>>;
84
+ type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]>; };
153
85
  interface MapValuePlaceholder<T> {
154
86
  [__RPC_MAP_VALUE_BRAND]: T;
155
87
  }
156
-
157
88
  type NonStubMembers<T> = Exclude<T, StubBase<any>>;
158
-
159
89
  // Utility type for adding `Disposable`s to `object` types only.
160
90
  // Note `unknown & T` is equivalent to `T`.
161
91
  type MaybeDisposable<T> = T extends object ? Disposable : unknown;
162
-
92
+ // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
93
+ // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
94
+ // instantiation: when both sides of an assignability check are the same alias applied to the
95
+ // same type arguments, the checker short-circuits on identity instead of recursing through the
96
+ // full structural comparison of these mutually-recursive types.
97
+ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
98
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
99
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
100
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
101
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
102
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
103
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
104
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
105
+ // guard an `any`-payload stub would lose its stub surface.
106
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
107
+ // transformation so constructing from a promised stub matches the method-return type.
108
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
109
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
110
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
111
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
112
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
113
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
114
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
115
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
163
116
  // Type for method return or property on an RPC interface.
164
117
  // - Stubable types are replaced by stubs.
165
118
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
@@ -168,89 +121,79 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown;
168
121
  // Technically, we use custom thenables here, but they quack like `Promise`s.
169
122
  // Intersecting with `(Maybe)Provider` allows pipelining.
170
123
  // prettier-ignore
171
- type Result<R> =
172
- IsAny<R> extends true ? UnknownResult
173
- : IsUnknown<R> extends true ? UnknownResult
174
- : R extends Stubable ? Promise<Stub<R>> & Provider<R> & StubBase<R>
175
- : R extends RpcCompatible<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & Provider<R> & StubBase<R>
176
- : never;
177
-
124
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> :
125
+ // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
126
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
127
+ R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> :
128
+ // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
129
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
130
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
131
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
132
+ // types.
133
+ R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
178
134
  type IsAny<T> = 0 extends (1 & T) ? true : false;
179
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>;
180
-
181
135
  // Type for method or property on an RPC interface.
182
136
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
183
137
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
184
138
  // For properties, rewrite types to be `Result`s.
185
139
  // In each case, unwrap `Promise`s.
186
- type MethodOrProperty<V> = V extends (...args: infer P) => infer R
187
- ? (...args: UnstubifyAll<P>) => IsAny<R> extends true ? UnknownResult : Result<Awaited<R>>
188
- : Result<Awaited<V>>;
189
-
140
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;
190
141
  // Type for the callable part of an `Provider` if `T` is callable.
191
142
  // This is intersected with methods/properties.
192
- type MaybeCallableProvider<T> = T extends (...args: any[]) => any
193
- ? MethodOrProperty<T>
194
- : unknown;
195
-
143
+ type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
196
144
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
197
145
  type MapCallbackValue<T> =
198
- // `Omit` removes call signatures, so re-intersect callable provider behavior.
199
- T extends unknown
200
- ? Omit<Result<T>, keyof Promise<unknown>> &
201
- MaybeCallableProvider<T> &
202
- MapValuePlaceholder<T>
203
- : never;
204
- type InvalidNativePromiseInMapResult<T, Seen = never> =
205
- T extends unknown ? InvalidNativePromiseInMapResultImpl<T, Seen> : never;
206
- type InvalidNativePromiseInMapResultImpl<T, Seen> =
207
- [T] extends [Seen] ? never
208
- // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
209
- : T extends StubBase<any> ? never
210
- // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
211
- : T extends PromiseLike<unknown> ? T
212
- : T extends Map<infer K, infer V>
213
- ? InvalidNativePromiseInMapResult<K, Seen | T> |
214
- InvalidNativePromiseInMapResult<V, Seen | T>
215
- : T extends Set<infer V> ? InvalidNativePromiseInMapResult<V, Seen | T>
216
- : T extends readonly [] ? never
217
- : T extends readonly [infer Head, ...infer Tail]
218
- ? InvalidNativePromiseInMapResult<Head, Seen | T> |
219
- InvalidNativePromiseInMapResult<Tail[number], Seen | T>
220
- : T extends ReadonlyArray<infer V> ? InvalidNativePromiseInMapResult<V, Seen | T>
221
- : T extends { [key: string | number]: unknown }
222
- ? InvalidNativePromiseInMapResult<
223
- T[Extract<keyof T, string | number>],
224
- Seen | T
225
- >
226
- : never;
227
- type MapCallbackReturn<T> =
228
- InvalidNativePromiseInMapResult<T> extends never ? T : never;
229
- type ArrayProvider<E> = {
230
- [K in number]: MethodOrProperty<E>;
231
- } & {
146
+ // `Omit` removes call signatures, so re-intersect callable provider behavior.
147
+ T extends unknown ? Omit<Result<T>, keyof Promise<unknown>> & MaybeCallableProvider<T> & MapValuePlaceholder<T> : never;
148
+ type InvalidNativePromiseInMapResult<T, Seen = never> = T extends unknown ? InvalidNativePromiseInMapResultImpl<T, Seen> : never;
149
+ type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never :
150
+ // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
151
+ T extends StubBase<any> ? never :
152
+ // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
153
+ 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 {
154
+ [key: string | number]: unknown;
155
+ } ? InvalidNativePromiseInMapResult<T[Extract<keyof T, string | number>], Seen | T> : never;
156
+ type MapCallbackReturn<T> = InvalidNativePromiseInMapResult<T> extends never ? T : never;
157
+ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E>; } & {
232
158
  map<V>(callback: (elem: MapCallbackValue<E>) => MapCallbackReturn<V>): Result<Array<V>>;
233
159
  };
234
- type TupleProvider<T extends ReadonlyArray<unknown>> = {
235
- [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]>;
236
- } & ArrayProvider<T[number]>;
237
-
160
+ type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]>; } & ArrayProvider<T[number]>;
238
161
  // Base type for all other types providing RPC-like interfaces.
239
162
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
240
- type Provider<T> = MaybeCallableProvider<T> &
241
- (T extends ReadonlyArray<unknown>
242
- ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T>
243
- : {
244
- [K in Exclude<
245
- keyof T,
246
- symbol | keyof StubBase<never>
247
- >]: MethodOrProperty<T[K]>;
248
- } & {
249
- map<V>(
250
- callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>
251
- ): Result<Array<V>>;
252
- });
253
-
163
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
164
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
165
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
166
+ type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : Pick<{ [K in keyof T]: MethodOrProperty<T[K]>; }, Exclude<keyof T, symbol | keyof StubBase<never>>> & {
167
+ map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
168
+ });
169
+ //#endregion
170
+ //#region src/serialize.d.ts
171
+ /**
172
+ * Encoding levels determine what representation the RPC system hands to the transport.
173
+ * Each level names what the transport can assume about message values.
174
+ *
175
+ * - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
176
+ * - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
177
+ * - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
178
+ * - `"structuredClonable"`: Structured-clonable native values pass through where possible.
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * // What happens to Uint8Array([1, 2, 3]) at each level:
183
+ * "string" → '["bytes","AQID"]' // JSON string with base64
184
+ * "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
185
+ * "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
186
+ * "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
187
+ * ```
188
+ */
189
+ type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
190
+ interface RpcLimits {
191
+ maxBigIntDigits: number;
192
+ maxDepth: number;
193
+ maxMessageSize: number;
194
+ }
195
+ declare const DEFAULT_MAX_DEPTH = 256;
196
+ declare const DEFAULT_LIMITS: RpcLimits;
254
197
  /**
255
198
  * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
256
199
  * RPC stubs, but it will support basic data types.
@@ -260,59 +203,129 @@ declare function serialize(value: unknown): string;
260
203
  * Deserialize a value serialized using serialize().
261
204
  */
262
205
  declare function deserialize(value: string): unknown;
263
-
206
+ //#endregion
207
+ //#region src/rpc.d.ts
264
208
  /**
265
- * Interface for an RPC transport, which is a simple bidirectional message stream. Implement this
266
- * interface if the built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
209
+ * Interface for a string-based RPC transport. This is the default transport type — no
210
+ * `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
211
+ * built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
267
212
  */
268
213
  interface RpcTransport {
269
- /**
270
- * Sends a message to the other end.
271
- */
272
- send(message: string): Promise<void>;
273
- /**
274
- * Receives a message sent by the other end.
275
- *
276
- * If and when the transport becomes disconnected, this will reject. The thrown error will be
277
- * propagated to all outstanding calls and future calls on any stubs associated with the session.
278
- * If there are no outstanding calls (and none are made in the future), then the error does not
279
- * propagate anywhere -- this is considered a "clean" shutdown.
280
- */
281
- receive(): Promise<string>;
282
- /**
283
- * Indicates that the RPC system has suffered an error that prevents the session from continuing.
284
- * The transport should ideally try to send any queued messages if it can, and then close the
285
- * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
286
- * before abort() is called is often an "abort" message, which communicates the error to the
287
- * peer, so if that is dropped, the peer may have less information about what happened.)
288
- */
289
- abort?(reason: any): void;
214
+ /**
215
+ * The encoding level this transport works with. For this interface it is always "string";
216
+ * it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
217
+ */
218
+ readonly encodingLevel?: "string";
219
+ /**
220
+ * Sends a message to the other end. May optionally return a promise; if the promise rejects,
221
+ * the session is aborted.
222
+ */
223
+ send(message: string): void | Promise<void>;
224
+ /**
225
+ * Receives a message sent by the other end.
226
+ *
227
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
228
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
229
+ * If there are no outstanding calls (and none are made in the future), then the error does not
230
+ * propagate anywhere -- this is considered a "clean" shutdown.
231
+ */
232
+ receive(): Promise<string>;
233
+ /**
234
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
235
+ * The transport should ideally try to send any queued messages if it can, and then close the
236
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
237
+ * before abort() is called is often an "abort" message, which communicates the error to the
238
+ * peer, so if that is dropped, the peer may have less information about what happened.)
239
+ */
240
+ abort?(reason: any): void;
241
+ }
242
+ /**
243
+ * Interface for a transport that receives partially encoded JS values instead of JSON strings.
244
+ * The selected `encodingLevel` describes what the transport can assume about message values.
245
+ */
246
+ interface RpcTransportWithCustomEncoding {
247
+ /**
248
+ * The encoding level this transport works with.
249
+ *
250
+ * - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
251
+ * - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
252
+ * - "structuredClonable": Structured-clonable native values pass through where possible.
253
+ */
254
+ readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
255
+ /**
256
+ * Encodes and sends a message to the other end. Returns the encoded byte size if known.
257
+ * If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
258
+ * flow control. Send errors should be propagated via `receive()` rejecting.
259
+ */
260
+ send(message: unknown): number | void;
261
+ /**
262
+ * Receives and decodes a message sent by the other end.
263
+ *
264
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
265
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
266
+ * If there are no outstanding calls (and none are made in the future), then the error does not
267
+ * propagate anywhere -- this is considered a "clean" shutdown.
268
+ */
269
+ receive(): Promise<unknown>;
270
+ /**
271
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
272
+ * The transport should ideally try to send any queued messages if it can, and then close the
273
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
274
+ * before abort() is called is often an "abort" message, which communicates the error to the
275
+ * peer, so if that is dropped, the peer may have less information about what happened.)
276
+ */
277
+ abort?(reason: any): void;
290
278
  }
279
+ /** Any supported transport type. */
280
+ type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
291
281
  /**
292
282
  * Options to customize behavior of an RPC session. All functions which start a session should
293
283
  * optionally accept this.
294
284
  */
295
285
  type RpcSessionOptions = {
296
- /**
297
- * If provided, this function will be called whenever an `Error` object is serialized (for any
298
- * reason, not just because it was thrown). This can be used to log errors, and also to redact
299
- * them.
300
- *
301
- * If `onSendError` returns an Error object, than object will be substituted in place of the
302
- * original. If it has a stack property, the stack will be sent to the client.
303
- *
304
- * If `onSendError` doesn't return anything (or is not provided at all), the default behavior is
305
- * to serialize the error with the stack omitted.
306
- */
307
- onSendError?: (error: Error) => Error | void;
286
+ /**
287
+ * If provided, this function will be called whenever an `Error` object is serialized (for any
288
+ * reason, not just because it was thrown). This can be used to log errors, and also to redact
289
+ * them.
290
+ *
291
+ * If `onSendError` returns an Error object, than object will be substituted in place of the
292
+ * original. If it has a stack property, the stack will be sent to the client.
293
+ *
294
+ * If `onSendError` doesn't return anything (or is not provided at all), the default behavior is
295
+ * to serialize the error with the stack omitted.
296
+ */
297
+ onSendError?: (error: Error) => Error | void;
298
+ /**
299
+ * Overrides for the resource limits enforced while deserializing messages from the peer. Any
300
+ * field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
301
+ * attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
302
+ *
303
+ * Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
304
+ * the peer never learns these values. A message that exceeds a limit is rejected, aborting the
305
+ * session.
306
+ */
307
+ limits?: Partial<RpcLimits>;
308
308
  };
309
-
309
+ //#endregion
310
+ //#region src/websocket.d.ts
310
311
  /**
311
312
  * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
312
313
  * with the given `localMain`.
313
314
  */
314
315
  declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
315
-
316
+ /**
317
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
318
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
319
+ */
320
+ declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
321
+ #private;
322
+ constructor(webSocket: WebSocket);
323
+ send(message: T): void;
324
+ receive(): Promise<T>;
325
+ abort(reason: any): void;
326
+ }
327
+ //#endregion
328
+ //#region src/batch.d.ts
316
329
  /**
317
330
  * Implements the server end of an HTTP batch session, using standard Fetch API types to represent
318
331
  * HTTP requests and responses.
@@ -333,9 +346,10 @@ declare function newHttpBatchRpcResponse(request: Request, localMain: any, optio
333
346
  * @param options Optional RPC session options. You can also pass headers to set on the response.
334
347
  */
335
348
  declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: ServerResponse, localMain: any, options?: RpcSessionOptions & {
336
- headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
349
+ headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
337
350
  }): Promise<void>;
338
-
351
+ //#endregion
352
+ //#region src/index.d.ts
339
353
  /**
340
354
  * Represents a reference to a remote object, on which methods may be remotely invoked via RPC.
341
355
  *
@@ -348,7 +362,7 @@ declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: Se
348
362
  */
349
363
  type RpcStub<T extends RpcCompatible<T>> = Stub<T>;
350
364
  declare const RpcStub: {
351
- new <T extends RpcCompatible<T>>(value: T): RpcStub<T>;
365
+ new <T extends RpcCompatible<T>>(value: T): RpcStub<T>;
352
366
  };
353
367
  /**
354
368
  * Represents the result of an RPC call.
@@ -367,24 +381,36 @@ declare const RpcStub: {
367
381
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
368
382
  * if you only intend to use the promise for pipelining and you never await it, then there's no
369
383
  * need to transmit the resolution!
384
+ *
385
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
386
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
387
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
388
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
389
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
390
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
391
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
392
+ * with a `dup()` if you also intend to keep the stub.
370
393
  */
371
- type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
372
- declare const RpcPromise: {};
394
+ type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
395
+ declare const RpcPromise: {
396
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$1<ElideStub<T>>;
397
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$1<ElideStub<T>>;
398
+ };
373
399
  /**
374
400
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
375
401
  *
376
402
  * Most people won't use this. You only need it if you've implemented your own `RpcTransport`.
377
403
  */
378
404
  interface RpcSession<T extends RpcCompatible<T> = undefined> {
379
- getRemoteMain(): RpcStub<T>;
380
- getStats(): {
381
- imports: number;
382
- exports: number;
383
- };
384
- drain(): Promise<void>;
405
+ getRemoteMain(): RpcStub<T>;
406
+ getStats(): {
407
+ imports: number;
408
+ exports: number;
409
+ };
410
+ drain(): Promise<void>;
385
411
  }
386
412
  declare const RpcSession: {
387
- new <T extends RpcCompatible<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
413
+ new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
388
414
  };
389
415
  /**
390
416
  * Classes which are intended to be passed by reference and called over RPC must extend
@@ -394,17 +420,15 @@ declare const RpcSession: {
394
420
  * Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the
395
421
  * "cloudflare:workers" module, so they can be used interchangably.
396
422
  */
397
- interface RpcTarget extends RpcTargetBranded {
398
- }
423
+ interface RpcTarget extends RpcTargetBranded {}
399
424
  declare const RpcTarget: {
400
- new (): RpcTarget;
425
+ new (): RpcTarget;
401
426
  };
402
427
  /**
403
428
  * Empty interface used as default type parameter for sessions where the other side doesn't
404
429
  * necessarily export a main interface.
405
430
  */
406
- interface Empty {
407
- }
431
+ interface Empty {}
408
432
  /**
409
433
  * Start a WebSocket session given either an already-open WebSocket or a URL.
410
434
  *
@@ -439,6 +463,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty>(port:
439
463
  * credentials as parameters and returns the authorized API), then cross-origin requests should
440
464
  * be safe.
441
465
  */
442
- declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
443
-
444
- export { type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
466
+ declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
467
+ //#endregion
468
+ 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 };
469
+ //# sourceMappingURL=index.d.cts.map