capnweb 0.11.1 → 0.13.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,6 +1,5 @@
1
1
  import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
2
  import { ServerWebSocket } from "bun";
3
-
4
3
  //#region src/types.d.ts
5
4
  // Copyright (c) 2025 Cloudflare, Inc.
6
5
  // Licensed under the MIT license found in the LICENSE.txt file or at:
@@ -21,16 +20,23 @@ interface RpcTargetBranded {
21
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
22
21
  // `any` into inference.
23
22
  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
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false;
25
+ // Types that can be passed over RPC
25
26
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
26
27
  // composite types. This allows types defined with the "interface" keyword to pass the
27
28
  // 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;
29
+ type RpcCompatible<T> =
30
+ // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
31
+ (IsUnknown<T> extends true ? unknown : never) |
32
+ // RPC-compatible base values
33
+ BaseType |
34
+ // RPC-compatible composites
35
+ 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> |
36
+ // Special types
37
+ Stub<Stubable> |
38
+ // Serialized as stubs, see `Stubify`
39
+ Stubable;
34
40
  // Base type for all RPC stubs, including common memory management methods.
35
41
  // `T` is used as a marker type for unwrapping `Stub`s later.
36
42
  interface StubBase<T = unknown> extends Disposable {
@@ -39,24 +45,35 @@ interface StubBase<T = unknown> extends Disposable {
39
45
  onRpcBroken(callback: (error: any) => void): void;
40
46
  }
41
47
  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
48
+ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array;
49
+ // This represents all the types that can be sent as-is over an RPC boundary
43
50
  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.
51
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
52
+ | URL | Request | Response | Headers;
53
+ // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
54
+ // Arm ordering matters here:
55
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
56
+ // through the Promise arm rather than pass through as-is.
57
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
58
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
59
+ // double-wrapping them as `Stub<Stub<T>>`.
46
60
  // prettier-ignore
47
- 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.
48
- : T extends {
61
+ 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 :
62
+ // When using "unknown" instead of "any", interfaces are not stubified.
63
+ T extends {
49
64
  [key: string | number]: any;
50
- } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
65
+ } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]>; } : T;
51
66
  // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
52
67
  // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
53
68
  // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
54
69
  // prettier-ignore
55
- type UnstubifyInner<T> = // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
70
+ type UnstubifyInner<T> =
71
+ // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
56
72
  // is already assignable to the value type (important for callback contextual typing).
57
73
  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 {
58
74
  [key: string | number]: unknown;
59
- } ? { [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.
75
+ } ? { [K in keyof T as K extends string | number ? K : never]: Unstubify<T[K]>; } : T;
76
+ // You can put promises anywhere in the params and they'll be resolved before delivery.
60
77
  // (This also covers RpcPromise, because it's defined as being a Promise.)
61
78
  // Map placeholders are also allowed so primitive map callback inputs can be forwarded directly
62
79
  // into RPC params.
@@ -65,18 +82,38 @@ T extends StubBase<infer V> ? (T extends V ? UnstubifyInner<V> : (T | UnstubifyI
65
82
  // Remove stub members from mixed unions so callback params don’t get both stub and unstubbed signatures.
66
83
  // Marker carried by map() callback inputs. This lets primitive placeholders flow through params.
67
84
  type Unstubify<T> = NonStubMembers<T> | UnstubifyInner<T> | Promise<UnstubifyInner<T>> | MapValuePlaceholder<UnstubifyInner<T>>;
68
- type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]> };
85
+ type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]>; };
69
86
  interface MapValuePlaceholder<T> {
70
87
  [__RPC_MAP_VALUE_BRAND]: T;
71
88
  }
72
- type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
89
+ type NonStubMembers<T> = Exclude<T, StubBase<any>>;
90
+ // Utility type for adding `Disposable`s to `object` types only.
73
91
  // Note `unknown & T` is equivalent to `T`.
74
- type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
92
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown;
93
+ // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
75
94
  // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
76
95
  // instantiation: when both sides of an assignability check are the same alias applied to the
77
96
  // same type arguments, the checker short-circuits on identity instead of recursing through the
78
97
  // full structural comparison of these mutually-recursive types.
79
98
  type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
99
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
100
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
101
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
102
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
103
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
104
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
105
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
106
+ // guard an `any`-payload stub would lose its stub surface.
107
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
108
+ // transformation so constructing from a promised stub matches the method-return type.
109
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
110
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
111
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
112
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
113
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
114
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
115
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
116
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
80
117
  // Type for method return or property on an RPC interface.
81
118
  // - Stubable types are replaced by stubs.
82
119
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
@@ -85,32 +122,49 @@ type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & Stu
85
122
  // Technically, we use custom thenables here, but they quack like `Promise`s.
86
123
  // Intersecting with `(Maybe)Provider` allows pipelining.
87
124
  // prettier-ignore
88
- type Result<R> = IsAny<R> extends true ? UnknownResult : IsUnknown<R> extends true ? UnknownResult : R extends Stubable ? RpcPromise$2<R> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
125
+ type Result<R> = IsAny<R> extends true ? RpcPromise$2<unknown> :
126
+ // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
127
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
128
+ R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> :
129
+ // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
130
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
131
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
132
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
133
+ // types.
134
+ R extends StubBase<any> ? RpcPromise$2<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
89
135
  type IsAny<T> = 0 extends (1 & T) ? true : false;
90
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
136
+ // Type for method or property on an RPC interface.
91
137
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
92
138
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
93
139
  // For properties, rewrite types to be `Result`s.
94
140
  // In each case, unwrap `Promise`s.
95
- 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.
141
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;
142
+ // Type for the callable part of an `Provider` if `T` is callable.
96
143
  // This is intersected with methods/properties.
97
144
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
98
145
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
99
- type MapCallbackValue<T> = // `Omit` removes call signatures, so re-intersect callable provider behavior.
146
+ type MapCallbackValue<T> =
147
+ // `Omit` removes call signatures, so re-intersect callable provider behavior.
100
148
  T extends unknown ? Omit<Result<T>, keyof Promise<unknown>> & MaybeCallableProvider<T> & MapValuePlaceholder<T> : never;
101
149
  type InvalidNativePromiseInMapResult<T, Seen = never> = T extends unknown ? InvalidNativePromiseInMapResultImpl<T, Seen> : never;
102
- type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
103
- : T extends StubBase<any> ? never // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
104
- : 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 {
150
+ type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never :
151
+ // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
152
+ T extends StubBase<any> ? never :
153
+ // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
154
+ 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 {
105
155
  [key: string | number]: unknown;
106
156
  } ? InvalidNativePromiseInMapResult<T[Extract<keyof T, string | number>], Seen | T> : never;
107
157
  type MapCallbackReturn<T> = InvalidNativePromiseInMapResult<T> extends never ? T : never;
108
- type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
158
+ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E>; } & {
109
159
  map<V>(callback: (elem: MapCallbackValue<E>) => MapCallbackReturn<V>): Result<Array<V>>;
110
160
  };
111
- 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.
161
+ type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]>; } & ArrayProvider<T[number]>;
162
+ // Base type for all other types providing RPC-like interfaces.
112
163
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
113
- 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]> } & {
164
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
165
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
166
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
167
+ 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>>> & {
114
168
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
115
169
  });
116
170
  //#endregion
@@ -147,15 +201,18 @@ declare class RpcStub$1 extends RpcTarget$1 {
147
201
  toString(): string;
148
202
  }
149
203
  declare class RpcPromise$1 extends RpcStub$1 {
150
- constructor(hook: StubHook, pathIfPromise: PropertyPath);
204
+ constructor(hook: StubHook | PromiseLike<unknown>, pathIfPromise?: PropertyPath);
151
205
  then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
152
206
  catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
153
207
  finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
154
208
  toString(): string;
155
209
  }
210
+ type PropertyName = string | number | {
211
+ mapKey: unknown;
212
+ };
156
213
  type LocatedPromise = {
157
214
  parent: object;
158
- property: string | number;
215
+ property: PropertyName;
159
216
  promise: RpcPromise$1;
160
217
  };
161
218
  declare class RpcPayload {
@@ -402,9 +459,21 @@ declare const RpcStub: {
402
459
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
403
460
  * if you only intend to use the promise for pipelining and you never await it, then there's no
404
461
  * need to transmit the resolution!
462
+ *
463
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
464
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
465
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
466
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
467
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
468
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
469
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
470
+ * with a `dup()` if you also intend to keep the stub.
405
471
  */
406
472
  type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$2<T>;
407
- declare const RpcPromise: {};
473
+ declare const RpcPromise: {
474
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$2<ElideStub<T>>;
475
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$2<ElideStub<T>>;
476
+ };
408
477
  /**
409
478
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
410
479
  *
@@ -1,6 +1,5 @@
1
1
  import { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
2
  import { ServerWebSocket } from "bun";
3
-
4
3
  //#region src/types.d.ts
5
4
  // Copyright (c) 2025 Cloudflare, Inc.
6
5
  // Licensed under the MIT license found in the LICENSE.txt file or at:
@@ -21,16 +20,23 @@ interface RpcTargetBranded {
21
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
22
21
  // `any` into inference.
23
22
  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
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false;
25
+ // Types that can be passed over RPC
25
26
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
26
27
  // composite types. This allows types defined with the "interface" keyword to pass the
27
28
  // 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;
29
+ type RpcCompatible<T> =
30
+ // Allow `unknown` as a leaf so records/interfaces with `unknown` fields remain compatible.
31
+ (IsUnknown<T> extends true ? unknown : never) |
32
+ // RPC-compatible base values
33
+ BaseType |
34
+ // RPC-compatible composites
35
+ 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> |
36
+ // Special types
37
+ Stub<Stubable> |
38
+ // Serialized as stubs, see `Stubify`
39
+ Stubable;
34
40
  // Base type for all RPC stubs, including common memory management methods.
35
41
  // `T` is used as a marker type for unwrapping `Stub`s later.
36
42
  interface StubBase<T = unknown> extends Disposable {
@@ -39,24 +45,35 @@ interface StubBase<T = unknown> extends Disposable {
39
45
  onRpcBroken(callback: (error: any) => void): void;
40
46
  }
41
47
  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
48
+ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array;
49
+ // This represents all the types that can be sent as-is over an RPC boundary
43
50
  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.
51
+ | WritableStream<any> // Chunk type can be any RPC-compatible type
52
+ | URL | Request | Response | Headers;
53
+ // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
54
+ // Arm ordering matters here:
55
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
56
+ // through the Promise arm rather than pass through as-is.
57
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
58
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
59
+ // double-wrapping them as `Stub<Stub<T>>`.
46
60
  // prettier-ignore
47
- 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.
48
- : T extends {
61
+ 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 :
62
+ // When using "unknown" instead of "any", interfaces are not stubified.
63
+ T extends {
49
64
  [key: string | number]: any;
50
- } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
65
+ } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]>; } : T;
51
66
  // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
52
67
  // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
53
68
  // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
54
69
  // prettier-ignore
55
- type UnstubifyInner<T> = // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
70
+ type UnstubifyInner<T> =
71
+ // Preserve local RpcTarget acceptance, but avoid needless `Stub | Value` unions when the stub
56
72
  // is already assignable to the value type (important for callback contextual typing).
57
73
  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 {
58
74
  [key: string | number]: unknown;
59
- } ? { [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.
75
+ } ? { [K in keyof T as K extends string | number ? K : never]: Unstubify<T[K]>; } : T;
76
+ // You can put promises anywhere in the params and they'll be resolved before delivery.
60
77
  // (This also covers RpcPromise, because it's defined as being a Promise.)
61
78
  // Map placeholders are also allowed so primitive map callback inputs can be forwarded directly
62
79
  // into RPC params.
@@ -65,18 +82,38 @@ T extends StubBase<infer V> ? (T extends V ? UnstubifyInner<V> : (T | UnstubifyI
65
82
  // Remove stub members from mixed unions so callback params don’t get both stub and unstubbed signatures.
66
83
  // Marker carried by map() callback inputs. This lets primitive placeholders flow through params.
67
84
  type Unstubify<T> = NonStubMembers<T> | UnstubifyInner<T> | Promise<UnstubifyInner<T>> | MapValuePlaceholder<UnstubifyInner<T>>;
68
- type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]> };
85
+ type UnstubifyAll<A extends readonly unknown[]> = { [I in keyof A]: Unstubify<A[I]>; };
69
86
  interface MapValuePlaceholder<T> {
70
87
  [__RPC_MAP_VALUE_BRAND]: T;
71
88
  }
72
- type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
89
+ type NonStubMembers<T> = Exclude<T, StubBase<any>>;
90
+ // Utility type for adding `Disposable`s to `object` types only.
73
91
  // Note `unknown & T` is equivalent to `T`.
74
- type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
92
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown;
93
+ // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
75
94
  // index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
76
95
  // instantiation: when both sides of an assignability check are the same alias applied to the
77
96
  // same type arguments, the checker short-circuits on identity instead of recursing through the
78
97
  // full structural comparison of these mutually-recursive types.
79
98
  type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
99
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
100
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
101
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
102
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
103
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
104
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
105
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
106
+ // guard an `any`-payload stub would lose its stub surface.
107
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
108
+ // transformation so constructing from a promised stub matches the method-return type.
109
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
110
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
111
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
112
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
113
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
114
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
115
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
116
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
80
117
  // Type for method return or property on an RPC interface.
81
118
  // - Stubable types are replaced by stubs.
82
119
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
@@ -85,32 +122,49 @@ type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & Stu
85
122
  // Technically, we use custom thenables here, but they quack like `Promise`s.
86
123
  // Intersecting with `(Maybe)Provider` allows pipelining.
87
124
  // prettier-ignore
88
- type Result<R> = IsAny<R> extends true ? UnknownResult : IsUnknown<R> extends true ? UnknownResult : R extends Stubable ? RpcPromise$2<R> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
125
+ type Result<R> = IsAny<R> extends true ? RpcPromise$2<unknown> :
126
+ // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
127
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
128
+ R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> :
129
+ // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
130
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
131
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
132
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
133
+ // types.
134
+ R extends StubBase<any> ? RpcPromise$2<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
89
135
  type IsAny<T> = 0 extends (1 & T) ? true : false;
90
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
136
+ // Type for method or property on an RPC interface.
91
137
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
92
138
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
93
139
  // For properties, rewrite types to be `Result`s.
94
140
  // In each case, unwrap `Promise`s.
95
- 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.
141
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;
142
+ // Type for the callable part of an `Provider` if `T` is callable.
96
143
  // This is intersected with methods/properties.
97
144
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
98
145
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
99
- type MapCallbackValue<T> = // `Omit` removes call signatures, so re-intersect callable provider behavior.
146
+ type MapCallbackValue<T> =
147
+ // `Omit` removes call signatures, so re-intersect callable provider behavior.
100
148
  T extends unknown ? Omit<Result<T>, keyof Promise<unknown>> & MaybeCallableProvider<T> & MapValuePlaceholder<T> : never;
101
149
  type InvalidNativePromiseInMapResult<T, Seen = never> = T extends unknown ? InvalidNativePromiseInMapResultImpl<T, Seen> : never;
102
- type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
103
- : T extends StubBase<any> ? never // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
104
- : 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 {
150
+ type InvalidNativePromiseInMapResultImpl<T, Seen> = [T] extends [Seen] ? never :
151
+ // RpcPromise is modeled as Promise & StubBase, so allow promise-like stub values.
152
+ T extends StubBase<any> ? never :
153
+ // Native thenables cannot be represented in map recordings, even when typed as PromiseLike.
154
+ 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 {
105
155
  [key: string | number]: unknown;
106
156
  } ? InvalidNativePromiseInMapResult<T[Extract<keyof T, string | number>], Seen | T> : never;
107
157
  type MapCallbackReturn<T> = InvalidNativePromiseInMapResult<T> extends never ? T : never;
108
- type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
158
+ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E>; } & {
109
159
  map<V>(callback: (elem: MapCallbackValue<E>) => MapCallbackReturn<V>): Result<Array<V>>;
110
160
  };
111
- 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.
161
+ type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]>; } & ArrayProvider<T[number]>;
162
+ // Base type for all other types providing RPC-like interfaces.
112
163
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
113
- 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]> } & {
164
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
165
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
166
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
167
+ 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>>> & {
114
168
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
115
169
  });
116
170
  //#endregion
@@ -147,15 +201,18 @@ declare class RpcStub$1 extends RpcTarget$1 {
147
201
  toString(): string;
148
202
  }
149
203
  declare class RpcPromise$1 extends RpcStub$1 {
150
- constructor(hook: StubHook, pathIfPromise: PropertyPath);
204
+ constructor(hook: StubHook | PromiseLike<unknown>, pathIfPromise?: PropertyPath);
151
205
  then(onfulfilled?: ((value: unknown) => unknown) | undefined | null, onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
152
206
  catch(onrejected?: ((reason: any) => unknown) | undefined | null): Promise<unknown>;
153
207
  finally(onfinally?: (() => void) | undefined | null): Promise<unknown>;
154
208
  toString(): string;
155
209
  }
210
+ type PropertyName = string | number | {
211
+ mapKey: unknown;
212
+ };
156
213
  type LocatedPromise = {
157
214
  parent: object;
158
- property: string | number;
215
+ property: PropertyName;
159
216
  promise: RpcPromise$1;
160
217
  };
161
218
  declare class RpcPayload {
@@ -402,9 +459,21 @@ declare const RpcStub: {
402
459
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
403
460
  * if you only intend to use the promise for pipelining and you never await it, then there's no
404
461
  * need to transmit the resolution!
462
+ *
463
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
464
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
465
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
466
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
467
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
468
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
469
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
470
+ * with a `dup()` if you also intend to keep the stub.
405
471
  */
406
472
  type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$2<T>;
407
- declare const RpcPromise: {};
473
+ declare const RpcPromise: {
474
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$2<ElideStub<T>>;
475
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$2<ElideStub<T>>;
476
+ };
408
477
  /**
409
478
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
410
479
  *