capnweb 0.0.0-409821 → 0.0.0-46de5a7
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/README.md +45 -2
- package/dist/index-bun.cjs +448 -106
- package/dist/index-bun.cjs.map +1 -1
- package/dist/index-bun.d.cts +145 -17
- package/dist/index-bun.d.ts +145 -17
- package/dist/index-bun.js +446 -107
- package/dist/index-bun.js.map +1 -1
- package/dist/index-workers.cjs +448 -106
- package/dist/index-workers.cjs.map +1 -1
- package/dist/index-workers.d.cts +142 -17
- package/dist/index-workers.d.ts +142 -17
- package/dist/index-workers.js +446 -107
- package/dist/index-workers.js.map +1 -1
- package/dist/index.cjs +448 -106
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +142 -17
- package/dist/index.d.ts +142 -17
- package/dist/index.js +446 -107
- package/dist/index.js.map +1 -1
- package/package.json +6 -5
package/dist/index-bun.d.cts
CHANGED
|
@@ -21,7 +21,8 @@ interface RpcTargetBranded {
|
|
|
21
21
|
// `never[]` preserves compatibility with strongly-typed function signatures without introducing
|
|
22
22
|
// `any` into inference.
|
|
23
23
|
type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
|
|
24
|
-
|
|
24
|
+
// Note: also true for `any` (call sites that care check `IsAny` first).
|
|
25
|
+
type IsUnknown<T> = unknown extends T ? true : false; // 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.
|
|
@@ -40,10 +41,17 @@ interface StubBase<T = unknown> extends Disposable {
|
|
|
40
41
|
}
|
|
41
42
|
type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
|
|
42
43
|
type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array; // This represents all the types that can be sent as-is over an RPC boundary
|
|
43
|
-
type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<
|
|
44
|
-
|
|
|
44
|
+
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
|
|
45
|
+
| WritableStream<any> // Chunk type can be any RPC-compatible type
|
|
46
|
+
| URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
|
|
47
|
+
// Arm ordering matters here:
|
|
48
|
+
// - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
|
|
49
|
+
// through the Promise arm rather than pass through as-is.
|
|
50
|
+
// - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
|
|
51
|
+
// it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
|
|
52
|
+
// double-wrapping them as `Stub<Stub<T>>`.
|
|
45
53
|
// prettier-ignore
|
|
46
|
-
type Stubify<T> = T extends
|
|
54
|
+
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.
|
|
47
55
|
: T extends {
|
|
48
56
|
[key: string | number]: any;
|
|
49
57
|
} ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
|
|
@@ -70,7 +78,22 @@ interface MapValuePlaceholder<T> {
|
|
|
70
78
|
}
|
|
71
79
|
type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
|
|
72
80
|
// Note `unknown & T` is equivalent to `T`.
|
|
73
|
-
type MaybeDisposable<T> = T extends object ? Disposable : unknown; //
|
|
81
|
+
type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
|
|
82
|
+
// index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
|
|
83
|
+
// instantiation: when both sides of an assignability check are the same alias applied to the
|
|
84
|
+
// same type arguments, the checker short-circuits on identity instead of recursing through the
|
|
85
|
+
// full structural comparison of these mutually-recursive types.
|
|
86
|
+
type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
|
|
87
|
+
// The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
|
|
88
|
+
// payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
|
|
89
|
+
// declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
|
|
90
|
+
// Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
|
|
91
|
+
// `U extends Stubable`, so eliding those would change the awaited type from a stub to a
|
|
92
|
+
// stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
|
|
93
|
+
// `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
|
|
94
|
+
// guard an `any`-payload stub would lose its stub surface.
|
|
95
|
+
type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
|
|
96
|
+
// Type for method return or property on an RPC interface.
|
|
74
97
|
// - Stubable types are replaced by stubs.
|
|
75
98
|
// - RpcCompatible types are passed by value, with stubable types replaced by stubs
|
|
76
99
|
// and a top-level `Disposer`.
|
|
@@ -78,14 +101,20 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
|
|
|
78
101
|
// Technically, we use custom thenables here, but they quack like `Promise`s.
|
|
79
102
|
// Intersecting with `(Maybe)Provider` allows pipelining.
|
|
80
103
|
// prettier-ignore
|
|
81
|
-
type Result<R> = IsAny<R> extends true ?
|
|
82
|
-
|
|
83
|
-
|
|
104
|
+
type Result<R> = IsAny<R> extends true ? RpcPromise$2<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
|
|
105
|
+
// `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
|
|
106
|
+
: R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
|
|
107
|
+
// here: anything matching our `StubBase` was produced by machinery that already enforced
|
|
108
|
+
// the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
|
|
109
|
+
// `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
|
|
110
|
+
// types.
|
|
111
|
+
: R extends StubBase<any> ? RpcPromise$2<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
|
|
112
|
+
type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
|
|
84
113
|
// For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
|
|
85
114
|
// Unwrapping `Stub`s allows calling with `Stubable` arguments.
|
|
86
115
|
// For properties, rewrite types to be `Result`s.
|
|
87
116
|
// In each case, unwrap `Promise`s.
|
|
88
|
-
type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) =>
|
|
117
|
+
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.
|
|
89
118
|
// This is intersected with methods/properties.
|
|
90
119
|
type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
|
|
91
120
|
type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
|
|
@@ -103,6 +132,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
|
|
|
103
132
|
};
|
|
104
133
|
type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]> } & ArrayProvider<T[number]>; // Base type for all other types providing RPC-like interfaces.
|
|
105
134
|
// Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
|
|
135
|
+
// `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
|
|
136
|
+
// stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
|
|
137
|
+
// `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
|
|
106
138
|
type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : { [K in Exclude<keyof T, symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]> } & {
|
|
107
139
|
map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
|
|
108
140
|
});
|
|
@@ -171,6 +203,9 @@ declare class RpcPayload {
|
|
|
171
203
|
private deliverTo;
|
|
172
204
|
private static deliverRpcPromiseTo;
|
|
173
205
|
deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
|
|
206
|
+
deliverStreamWrite(writer: {
|
|
207
|
+
write(chunk: unknown): Promise<void>;
|
|
208
|
+
}): Promise<RpcPayload>;
|
|
174
209
|
deliverResolve(): Promise<unknown>;
|
|
175
210
|
dispose(): void;
|
|
176
211
|
private disposeImpl;
|
|
@@ -179,6 +214,32 @@ declare class RpcPayload {
|
|
|
179
214
|
}
|
|
180
215
|
//#endregion
|
|
181
216
|
//#region src/serialize.d.ts
|
|
217
|
+
/**
|
|
218
|
+
* Encoding levels determine what representation the RPC system hands to the transport.
|
|
219
|
+
* Each level names what the transport can assume about message values.
|
|
220
|
+
*
|
|
221
|
+
* - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
|
|
222
|
+
* - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
|
|
223
|
+
* - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
|
|
224
|
+
* - `"structuredClonable"`: Structured-clonable native values pass through where possible.
|
|
225
|
+
*
|
|
226
|
+
* @example
|
|
227
|
+
* ```ts
|
|
228
|
+
* // What happens to Uint8Array([1, 2, 3]) at each level:
|
|
229
|
+
* "string" → '["bytes","AQID"]' // JSON string with base64
|
|
230
|
+
* "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
|
|
231
|
+
* "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
|
|
232
|
+
* "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
|
|
233
|
+
* ```
|
|
234
|
+
*/
|
|
235
|
+
type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
|
|
236
|
+
interface RpcLimits {
|
|
237
|
+
maxBigIntDigits: number;
|
|
238
|
+
maxDepth: number;
|
|
239
|
+
maxMessageSize: number;
|
|
240
|
+
}
|
|
241
|
+
declare const DEFAULT_MAX_DEPTH = 256;
|
|
242
|
+
declare const DEFAULT_LIMITS: RpcLimits;
|
|
182
243
|
/**
|
|
183
244
|
* Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
|
|
184
245
|
* RPC stubs, but it will support basic data types.
|
|
@@ -191,14 +252,21 @@ declare function deserialize(value: string): unknown;
|
|
|
191
252
|
//#endregion
|
|
192
253
|
//#region src/rpc.d.ts
|
|
193
254
|
/**
|
|
194
|
-
* Interface for
|
|
195
|
-
*
|
|
255
|
+
* Interface for a string-based RPC transport. This is the default transport type — no
|
|
256
|
+
* `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
|
|
257
|
+
* built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
|
|
196
258
|
*/
|
|
197
259
|
interface RpcTransport {
|
|
198
260
|
/**
|
|
199
|
-
*
|
|
261
|
+
* The encoding level this transport works with. For this interface it is always "string";
|
|
262
|
+
* it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
|
|
200
263
|
*/
|
|
201
|
-
|
|
264
|
+
readonly encodingLevel?: "string";
|
|
265
|
+
/**
|
|
266
|
+
* Sends a message to the other end. May optionally return a promise; if the promise rejects,
|
|
267
|
+
* the session is aborted.
|
|
268
|
+
*/
|
|
269
|
+
send(message: string): void | Promise<void>;
|
|
202
270
|
/**
|
|
203
271
|
* Receives a message sent by the other end.
|
|
204
272
|
*
|
|
@@ -217,6 +285,45 @@ interface RpcTransport {
|
|
|
217
285
|
*/
|
|
218
286
|
abort?(reason: any): void;
|
|
219
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Interface for a transport that receives partially encoded JS values instead of JSON strings.
|
|
290
|
+
* The selected `encodingLevel` describes what the transport can assume about message values.
|
|
291
|
+
*/
|
|
292
|
+
interface RpcTransportWithCustomEncoding {
|
|
293
|
+
/**
|
|
294
|
+
* The encoding level this transport works with.
|
|
295
|
+
*
|
|
296
|
+
* - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
|
|
297
|
+
* - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
|
|
298
|
+
* - "structuredClonable": Structured-clonable native values pass through where possible.
|
|
299
|
+
*/
|
|
300
|
+
readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
|
|
301
|
+
/**
|
|
302
|
+
* Encodes and sends a message to the other end. Returns the encoded byte size if known.
|
|
303
|
+
* If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
|
|
304
|
+
* flow control. Send errors should be propagated via `receive()` rejecting.
|
|
305
|
+
*/
|
|
306
|
+
send(message: unknown): number | void;
|
|
307
|
+
/**
|
|
308
|
+
* Receives and decodes a message sent by the other end.
|
|
309
|
+
*
|
|
310
|
+
* If and when the transport becomes disconnected, this will reject. The thrown error will be
|
|
311
|
+
* propagated to all outstanding calls and future calls on any stubs associated with the session.
|
|
312
|
+
* If there are no outstanding calls (and none are made in the future), then the error does not
|
|
313
|
+
* propagate anywhere -- this is considered a "clean" shutdown.
|
|
314
|
+
*/
|
|
315
|
+
receive(): Promise<unknown>;
|
|
316
|
+
/**
|
|
317
|
+
* Indicates that the RPC system has suffered an error that prevents the session from continuing.
|
|
318
|
+
* The transport should ideally try to send any queued messages if it can, and then close the
|
|
319
|
+
* connection. (It's not strictly necessary to deliver queued messages, but the last message sent
|
|
320
|
+
* before abort() is called is often an "abort" message, which communicates the error to the
|
|
321
|
+
* peer, so if that is dropped, the peer may have less information about what happened.)
|
|
322
|
+
*/
|
|
323
|
+
abort?(reason: any): void;
|
|
324
|
+
}
|
|
325
|
+
/** Any supported transport type. */
|
|
326
|
+
type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
|
|
220
327
|
/**
|
|
221
328
|
* Options to customize behavior of an RPC session. All functions which start a session should
|
|
222
329
|
* optionally accept this.
|
|
@@ -234,6 +341,16 @@ type RpcSessionOptions = {
|
|
|
234
341
|
* to serialize the error with the stack omitted.
|
|
235
342
|
*/
|
|
236
343
|
onSendError?: (error: Error) => Error | void;
|
|
344
|
+
/**
|
|
345
|
+
* Overrides for the resource limits enforced while deserializing messages from the peer. Any
|
|
346
|
+
* field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
|
|
347
|
+
* attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
|
|
348
|
+
*
|
|
349
|
+
* Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
|
|
350
|
+
* the peer never learns these values. A message that exceeds a limit is rejected, aborting the
|
|
351
|
+
* session.
|
|
352
|
+
*/
|
|
353
|
+
limits?: Partial<RpcLimits>;
|
|
237
354
|
};
|
|
238
355
|
//#endregion
|
|
239
356
|
//#region src/websocket.d.ts
|
|
@@ -242,6 +359,17 @@ type RpcSessionOptions = {
|
|
|
242
359
|
* with the given `localMain`.
|
|
243
360
|
*/
|
|
244
361
|
declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
|
|
362
|
+
/**
|
|
363
|
+
* Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
|
|
364
|
+
* `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
|
|
365
|
+
*/
|
|
366
|
+
declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
|
|
367
|
+
#private;
|
|
368
|
+
constructor(webSocket: WebSocket);
|
|
369
|
+
send(message: T): void;
|
|
370
|
+
receive(): Promise<T>;
|
|
371
|
+
abort(reason: any): void;
|
|
372
|
+
}
|
|
245
373
|
//#endregion
|
|
246
374
|
//#region src/batch.d.ts
|
|
247
375
|
/**
|
|
@@ -300,7 +428,7 @@ declare const RpcStub: {
|
|
|
300
428
|
* if you only intend to use the promise for pipelining and you never await it, then there's no
|
|
301
429
|
* need to transmit the resolution!
|
|
302
430
|
*/
|
|
303
|
-
type RpcPromise<T extends RpcCompatible<T>> =
|
|
431
|
+
type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$2<T>;
|
|
304
432
|
declare const RpcPromise: {};
|
|
305
433
|
/**
|
|
306
434
|
* Use to construct an `RpcSession` on top of a custom `RpcTransport`.
|
|
@@ -316,7 +444,7 @@ interface RpcSession<T extends RpcCompatible<T> = undefined> {
|
|
|
316
444
|
drain(): Promise<void>;
|
|
317
445
|
}
|
|
318
446
|
declare const RpcSession: {
|
|
319
|
-
new <T extends RpcCompatible<T> = undefined>(transport:
|
|
447
|
+
new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
|
|
320
448
|
};
|
|
321
449
|
/**
|
|
322
450
|
* Classes which are intended to be passed by reference and called over RPC must extend
|
|
@@ -369,7 +497,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty$1>(por
|
|
|
369
497
|
* credentials as parameters and returns the authorized API), then cross-origin requests should
|
|
370
498
|
* be safe.
|
|
371
499
|
*/
|
|
372
|
-
declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
|
|
500
|
+
declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
|
|
373
501
|
//#endregion
|
|
374
502
|
//#region src/bun.d.ts
|
|
375
503
|
type WsData = {
|
|
@@ -420,5 +548,5 @@ declare let newBunWebSocketRpcSession: <T extends RpcCompatible<T> = Empty, D =
|
|
|
420
548
|
transport: BunWebSocketTransport<D>;
|
|
421
549
|
};
|
|
422
550
|
//#endregion
|
|
423
|
-
export { BunWebSocketTransport, type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
|
|
551
|
+
export { type AnyRpcTransport, BunWebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, type EncodingLevel, type RpcCompatible, type RpcLimits, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
|
|
424
552
|
//# sourceMappingURL=index-bun.d.cts.map
|
package/dist/index-bun.d.ts
CHANGED
|
@@ -21,7 +21,8 @@ interface RpcTargetBranded {
|
|
|
21
21
|
// `never[]` preserves compatibility with strongly-typed function signatures without introducing
|
|
22
22
|
// `any` into inference.
|
|
23
23
|
type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
|
|
24
|
-
|
|
24
|
+
// Note: also true for `any` (call sites that care check `IsAny` first).
|
|
25
|
+
type IsUnknown<T> = unknown extends T ? true : false; // 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.
|
|
@@ -40,10 +41,17 @@ interface StubBase<T = unknown> extends Disposable {
|
|
|
40
41
|
}
|
|
41
42
|
type Stub<T extends RpcCompatible<T>> = T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
|
|
42
43
|
type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array; // This represents all the types that can be sent as-is over an RPC boundary
|
|
43
|
-
type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<
|
|
44
|
-
|
|
|
44
|
+
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
|
|
45
|
+
| WritableStream<any> // Chunk type can be any RPC-compatible type
|
|
46
|
+
| URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
|
|
47
|
+
// Arm ordering matters here:
|
|
48
|
+
// - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
|
|
49
|
+
// through the Promise arm rather than pass through as-is.
|
|
50
|
+
// - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
|
|
51
|
+
// it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
|
|
52
|
+
// double-wrapping them as `Stub<Stub<T>>`.
|
|
45
53
|
// prettier-ignore
|
|
46
|
-
type Stubify<T> = T extends
|
|
54
|
+
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.
|
|
47
55
|
: T extends {
|
|
48
56
|
[key: string | number]: any;
|
|
49
57
|
} ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
|
|
@@ -70,7 +78,22 @@ interface MapValuePlaceholder<T> {
|
|
|
70
78
|
}
|
|
71
79
|
type NonStubMembers<T> = Exclude<T, StubBase<any>>; // Utility type for adding `Disposable`s to `object` types only.
|
|
72
80
|
// Note `unknown & T` is equivalent to `T`.
|
|
73
|
-
type MaybeDisposable<T> = T extends object ? Disposable : unknown; //
|
|
81
|
+
type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type behind the public `RpcPromise` (re-exported with its `RpcCompatible` constraint from
|
|
82
|
+
// index.ts). Defined here so that `Result`'s arms below resolve to the exact same alias
|
|
83
|
+
// instantiation: when both sides of an assignability check are the same alias applied to the
|
|
84
|
+
// same type arguments, the checker short-circuits on identity instead of recursing through the
|
|
85
|
+
// full structural comparison of these mutually-recursive types.
|
|
86
|
+
type RpcPromise$2<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
|
|
87
|
+
// The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
|
|
88
|
+
// payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
|
|
89
|
+
// declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
|
|
90
|
+
// Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
|
|
91
|
+
// `U extends Stubable`, so eliding those would change the awaited type from a stub to a
|
|
92
|
+
// stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
|
|
93
|
+
// `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
|
|
94
|
+
// guard an `any`-payload stub would lose its stub surface.
|
|
95
|
+
type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
|
|
96
|
+
// Type for method return or property on an RPC interface.
|
|
74
97
|
// - Stubable types are replaced by stubs.
|
|
75
98
|
// - RpcCompatible types are passed by value, with stubable types replaced by stubs
|
|
76
99
|
// and a top-level `Disposer`.
|
|
@@ -78,14 +101,20 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // Type for m
|
|
|
78
101
|
// Technically, we use custom thenables here, but they quack like `Promise`s.
|
|
79
102
|
// Intersecting with `(Maybe)Provider` allows pipelining.
|
|
80
103
|
// prettier-ignore
|
|
81
|
-
type Result<R> = IsAny<R> extends true ?
|
|
82
|
-
|
|
83
|
-
|
|
104
|
+
type Result<R> = IsAny<R> extends true ? RpcPromise$2<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
|
|
105
|
+
// `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
|
|
106
|
+
: R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
|
|
107
|
+
// here: anything matching our `StubBase` was produced by machinery that already enforced
|
|
108
|
+
// the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
|
|
109
|
+
// `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
|
|
110
|
+
// types.
|
|
111
|
+
: R extends StubBase<any> ? RpcPromise$2<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$2<R> : never;
|
|
112
|
+
type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
|
|
84
113
|
// For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
|
|
85
114
|
// Unwrapping `Stub`s allows calling with `Stubable` arguments.
|
|
86
115
|
// For properties, rewrite types to be `Result`s.
|
|
87
116
|
// In each case, unwrap `Promise`s.
|
|
88
|
-
type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) =>
|
|
117
|
+
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.
|
|
89
118
|
// This is intersected with methods/properties.
|
|
90
119
|
type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
|
|
91
120
|
type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
|
|
@@ -103,6 +132,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
|
|
|
103
132
|
};
|
|
104
133
|
type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]> } & ArrayProvider<T[number]>; // Base type for all other types providing RPC-like interfaces.
|
|
105
134
|
// Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
|
|
135
|
+
// `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
|
|
136
|
+
// stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
|
|
137
|
+
// `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
|
|
106
138
|
type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : { [K in Exclude<keyof T, symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]> } & {
|
|
107
139
|
map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
|
|
108
140
|
});
|
|
@@ -171,6 +203,9 @@ declare class RpcPayload {
|
|
|
171
203
|
private deliverTo;
|
|
172
204
|
private static deliverRpcPromiseTo;
|
|
173
205
|
deliverCall(func: Function, thisArg: object | undefined): Promise<RpcPayload>;
|
|
206
|
+
deliverStreamWrite(writer: {
|
|
207
|
+
write(chunk: unknown): Promise<void>;
|
|
208
|
+
}): Promise<RpcPayload>;
|
|
174
209
|
deliverResolve(): Promise<unknown>;
|
|
175
210
|
dispose(): void;
|
|
176
211
|
private disposeImpl;
|
|
@@ -179,6 +214,32 @@ declare class RpcPayload {
|
|
|
179
214
|
}
|
|
180
215
|
//#endregion
|
|
181
216
|
//#region src/serialize.d.ts
|
|
217
|
+
/**
|
|
218
|
+
* Encoding levels determine what representation the RPC system hands to the transport.
|
|
219
|
+
* Each level names what the transport can assume about message values.
|
|
220
|
+
*
|
|
221
|
+
* - `"string"`: JSON string. Default, used by HTTP batch and WebSocket transports.
|
|
222
|
+
* - `"jsonCompatible"`: JSON-compatible JS value tree. For custom encoders.
|
|
223
|
+
* - `"jsonCompatibleWithBytes"`: Like `"jsonCompatible"` but Uint8Array stays raw.
|
|
224
|
+
* - `"structuredClonable"`: Structured-clonable native values pass through where possible.
|
|
225
|
+
*
|
|
226
|
+
* @example
|
|
227
|
+
* ```ts
|
|
228
|
+
* // What happens to Uint8Array([1, 2, 3]) at each level:
|
|
229
|
+
* "string" → '["bytes","AQID"]' // JSON string with base64
|
|
230
|
+
* "jsonCompatible" → ["bytes", "AQID"] // JS array with base64
|
|
231
|
+
* "jsonCompatibleWithBytes" → ["bytes", Uint8Array] // JS array with raw bytes
|
|
232
|
+
* "structuredClonable" → ["bytes", Uint8Array] // + Date, BigInt stay native
|
|
233
|
+
* ```
|
|
234
|
+
*/
|
|
235
|
+
type EncodingLevel = "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
|
|
236
|
+
interface RpcLimits {
|
|
237
|
+
maxBigIntDigits: number;
|
|
238
|
+
maxDepth: number;
|
|
239
|
+
maxMessageSize: number;
|
|
240
|
+
}
|
|
241
|
+
declare const DEFAULT_MAX_DEPTH = 256;
|
|
242
|
+
declare const DEFAULT_LIMITS: RpcLimits;
|
|
182
243
|
/**
|
|
183
244
|
* Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
|
|
184
245
|
* RPC stubs, but it will support basic data types.
|
|
@@ -191,14 +252,21 @@ declare function deserialize(value: string): unknown;
|
|
|
191
252
|
//#endregion
|
|
192
253
|
//#region src/rpc.d.ts
|
|
193
254
|
/**
|
|
194
|
-
* Interface for
|
|
195
|
-
*
|
|
255
|
+
* Interface for a string-based RPC transport. This is the default transport type — no
|
|
256
|
+
* `encodingLevel` field is needed. Messages are JSON strings. Implement this interface if the
|
|
257
|
+
* built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
|
|
196
258
|
*/
|
|
197
259
|
interface RpcTransport {
|
|
198
260
|
/**
|
|
199
|
-
*
|
|
261
|
+
* The encoding level this transport works with. For this interface it is always "string";
|
|
262
|
+
* it may be omitted. (See `RpcTransportWithCustomEncoding` for the other levels.)
|
|
200
263
|
*/
|
|
201
|
-
|
|
264
|
+
readonly encodingLevel?: "string";
|
|
265
|
+
/**
|
|
266
|
+
* Sends a message to the other end. May optionally return a promise; if the promise rejects,
|
|
267
|
+
* the session is aborted.
|
|
268
|
+
*/
|
|
269
|
+
send(message: string): void | Promise<void>;
|
|
202
270
|
/**
|
|
203
271
|
* Receives a message sent by the other end.
|
|
204
272
|
*
|
|
@@ -217,6 +285,45 @@ interface RpcTransport {
|
|
|
217
285
|
*/
|
|
218
286
|
abort?(reason: any): void;
|
|
219
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Interface for a transport that receives partially encoded JS values instead of JSON strings.
|
|
290
|
+
* The selected `encodingLevel` describes what the transport can assume about message values.
|
|
291
|
+
*/
|
|
292
|
+
interface RpcTransportWithCustomEncoding {
|
|
293
|
+
/**
|
|
294
|
+
* The encoding level this transport works with.
|
|
295
|
+
*
|
|
296
|
+
* - "jsonCompatible": JSON-compatible JS value tree; transport handles final serialization.
|
|
297
|
+
* - "jsonCompatibleWithBytes": Like "jsonCompatible" but Uint8Array values are left raw.
|
|
298
|
+
* - "structuredClonable": Structured-clonable native values pass through where possible.
|
|
299
|
+
*/
|
|
300
|
+
readonly encodingLevel: "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable";
|
|
301
|
+
/**
|
|
302
|
+
* Encodes and sends a message to the other end. Returns the encoded byte size if known.
|
|
303
|
+
* If the size is unavailable, return void; Cap'n Web will estimate stream message sizes for
|
|
304
|
+
* flow control. Send errors should be propagated via `receive()` rejecting.
|
|
305
|
+
*/
|
|
306
|
+
send(message: unknown): number | void;
|
|
307
|
+
/**
|
|
308
|
+
* Receives and decodes a message sent by the other end.
|
|
309
|
+
*
|
|
310
|
+
* If and when the transport becomes disconnected, this will reject. The thrown error will be
|
|
311
|
+
* propagated to all outstanding calls and future calls on any stubs associated with the session.
|
|
312
|
+
* If there are no outstanding calls (and none are made in the future), then the error does not
|
|
313
|
+
* propagate anywhere -- this is considered a "clean" shutdown.
|
|
314
|
+
*/
|
|
315
|
+
receive(): Promise<unknown>;
|
|
316
|
+
/**
|
|
317
|
+
* Indicates that the RPC system has suffered an error that prevents the session from continuing.
|
|
318
|
+
* The transport should ideally try to send any queued messages if it can, and then close the
|
|
319
|
+
* connection. (It's not strictly necessary to deliver queued messages, but the last message sent
|
|
320
|
+
* before abort() is called is often an "abort" message, which communicates the error to the
|
|
321
|
+
* peer, so if that is dropped, the peer may have less information about what happened.)
|
|
322
|
+
*/
|
|
323
|
+
abort?(reason: any): void;
|
|
324
|
+
}
|
|
325
|
+
/** Any supported transport type. */
|
|
326
|
+
type AnyRpcTransport = RpcTransport | RpcTransportWithCustomEncoding;
|
|
220
327
|
/**
|
|
221
328
|
* Options to customize behavior of an RPC session. All functions which start a session should
|
|
222
329
|
* optionally accept this.
|
|
@@ -234,6 +341,16 @@ type RpcSessionOptions = {
|
|
|
234
341
|
* to serialize the error with the stack omitted.
|
|
235
342
|
*/
|
|
236
343
|
onSendError?: (error: Error) => Error | void;
|
|
344
|
+
/**
|
|
345
|
+
* Overrides for the resource limits enforced while deserializing messages from the peer. Any
|
|
346
|
+
* field left unset falls back to `DEFAULT_LIMITS`. These guard against resource-exhaustion
|
|
347
|
+
* attacks from untrusted peers; see `RpcLimits` for the meaning and defaults of each field.
|
|
348
|
+
*
|
|
349
|
+
* Limits are a purely local, receiver-side decision -- the protocol has no negotiation step, so
|
|
350
|
+
* the peer never learns these values. A message that exceeds a limit is rejected, aborting the
|
|
351
|
+
* session.
|
|
352
|
+
*/
|
|
353
|
+
limits?: Partial<RpcLimits>;
|
|
237
354
|
};
|
|
238
355
|
//#endregion
|
|
239
356
|
//#region src/websocket.d.ts
|
|
@@ -242,6 +359,17 @@ type RpcSessionOptions = {
|
|
|
242
359
|
* with the given `localMain`.
|
|
243
360
|
*/
|
|
244
361
|
declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
|
|
362
|
+
/**
|
|
363
|
+
* Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
|
|
364
|
+
* `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
|
|
365
|
+
*/
|
|
366
|
+
declare class WebSocketTransport<T extends string | ArrayBuffer = string> {
|
|
367
|
+
#private;
|
|
368
|
+
constructor(webSocket: WebSocket);
|
|
369
|
+
send(message: T): void;
|
|
370
|
+
receive(): Promise<T>;
|
|
371
|
+
abort(reason: any): void;
|
|
372
|
+
}
|
|
245
373
|
//#endregion
|
|
246
374
|
//#region src/batch.d.ts
|
|
247
375
|
/**
|
|
@@ -300,7 +428,7 @@ declare const RpcStub: {
|
|
|
300
428
|
* if you only intend to use the promise for pipelining and you never await it, then there's no
|
|
301
429
|
* need to transmit the resolution!
|
|
302
430
|
*/
|
|
303
|
-
type RpcPromise<T extends RpcCompatible<T>> =
|
|
431
|
+
type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$2<T>;
|
|
304
432
|
declare const RpcPromise: {};
|
|
305
433
|
/**
|
|
306
434
|
* Use to construct an `RpcSession` on top of a custom `RpcTransport`.
|
|
@@ -316,7 +444,7 @@ interface RpcSession<T extends RpcCompatible<T> = undefined> {
|
|
|
316
444
|
drain(): Promise<void>;
|
|
317
445
|
}
|
|
318
446
|
declare const RpcSession: {
|
|
319
|
-
new <T extends RpcCompatible<T> = undefined>(transport:
|
|
447
|
+
new <T extends RpcCompatible<T> = undefined>(transport: AnyRpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
|
|
320
448
|
};
|
|
321
449
|
/**
|
|
322
450
|
* Classes which are intended to be passed by reference and called over RPC must extend
|
|
@@ -369,7 +497,7 @@ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty$1>(por
|
|
|
369
497
|
* credentials as parameters and returns the authorized API), then cross-origin requests should
|
|
370
498
|
* be safe.
|
|
371
499
|
*/
|
|
372
|
-
declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
|
|
500
|
+
declare function newWorkersRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
|
|
373
501
|
//#endregion
|
|
374
502
|
//#region src/bun.d.ts
|
|
375
503
|
type WsData = {
|
|
@@ -420,5 +548,5 @@ declare let newBunWebSocketRpcSession: <T extends RpcCompatible<T> = Empty, D =
|
|
|
420
548
|
transport: BunWebSocketTransport<D>;
|
|
421
549
|
};
|
|
422
550
|
//#endregion
|
|
423
|
-
export { BunWebSocketTransport, type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
|
|
551
|
+
export { type AnyRpcTransport, BunWebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, type EncodingLevel, type RpcCompatible, type RpcLimits, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, type RpcTransportWithCustomEncoding, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
|
|
424
552
|
//# sourceMappingURL=index-bun.d.ts.map
|