capnweb 0.8.0 → 0.9.1

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