@trevrpc/trevrpc-js 0.2.3 → 1.1.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.
Files changed (47) hide show
  1. package/README.md +127 -46
  2. package/package.json +12 -45
  3. package/src/bytes.js +10 -0
  4. package/src/call.js +520 -0
  5. package/src/channel.js +258 -288
  6. package/src/client.js +543 -1254
  7. package/src/datagram.js +336 -0
  8. package/src/framing.js +151 -548
  9. package/src/generator.js +66 -109
  10. package/src/index.d.ts +235 -463
  11. package/src/index.js +4 -3
  12. package/src/qmux/frames.js +262 -0
  13. package/src/qmux/params.js +104 -0
  14. package/src/qmux/session.js +739 -0
  15. package/src/race.js +90 -0
  16. package/src/status.js +24 -70
  17. package/src/varint.js +73 -0
  18. package/src/wire.js +21 -89
  19. package/examples/greeter/README.md +0 -35
  20. package/examples/greeter/client.js +0 -172
  21. package/examples/greeter/greeter.node.trevrpc.d.ts +0 -53
  22. package/examples/greeter/greeter.node.trevrpc.js +0 -9
  23. package/examples/greeter/greeter.proto +0 -18
  24. package/examples/greeter/greeter.trevrpc.d.ts +0 -55
  25. package/examples/greeter/greeter.trevrpc.js +0 -103
  26. package/examples/greeter/index.html +0 -140
  27. package/examples/greeter/static-server.js +0 -168
  28. package/src/advanced.d.ts +0 -29
  29. package/src/advanced.js +0 -1
  30. package/src/browser-channel.js +0 -49
  31. package/src/connect.js +0 -6
  32. package/src/connect.node.js +0 -6
  33. package/src/index.node.d.ts +0 -10
  34. package/src/index.node.js +0 -3
  35. package/src/native-loader.js +0 -118
  36. package/src/node-advanced.d.ts +0 -27
  37. package/src/node-advanced.js +0 -1
  38. package/src/node-generated.d.ts +0 -24
  39. package/src/node-generated.js +0 -126
  40. package/src/node-index.d.ts +0 -1
  41. package/src/node-index.js +0 -7
  42. package/src/node.d.ts +0 -298
  43. package/src/node.js +0 -1456
  44. package/src/runtime.js +0 -66
  45. package/src/server-response.js +0 -49
  46. package/src/timer.js +0 -29
  47. package/src/webtransport.js +0 -639
package/src/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
- import type { Long, Message, Root, Type } from "protobufjs";
1
+ import type { INamespace, Root } from "protobufjs";
2
2
 
3
3
  export const protobuf: typeof import("protobufjs");
4
4
 
5
+ /** Creates a protobuf root from a JSON namespace definition. */
6
+ export function createRoot(json: INamespace): Root;
7
+
5
8
  export const Code: Readonly<{
6
9
  Ok: 0;
7
10
  Cancelled: 1;
@@ -24,343 +27,214 @@ export const Code: Readonly<{
24
27
 
25
28
  export type StatusCode = (typeof Code)[keyof typeof Code];
26
29
 
27
- export interface TrevRpcErrorOptions extends ErrorOptions {
28
- nativeCode?: number;
29
- }
30
+ /** Returns the canonical status code name, such as "NotFound". */
31
+ export function codeName(code: number): string;
32
+
33
+ export type MetadataValue = string | Uint8Array | ArrayBuffer | ArrayBufferView | readonly number[];
34
+ export type MetadataInput = Record<string, MetadataValue> | ReadonlyMap<string, MetadataValue>;
35
+ export type Metadata = Record<string, Uint8Array>;
30
36
 
31
37
  /** Error carrying a TrevRPC status code, message, and metadata. */
32
38
  export class TrevRpcError extends Error {
33
39
  readonly code: StatusCode;
34
40
  readonly statusMessage: string;
35
41
  readonly metadata: Metadata;
36
- readonly nativeCode?: number;
37
- override readonly cause?: unknown;
38
42
 
39
- /** Creates a TrevRPC status error. */
40
- constructor(code: number, message?: string, metadata?: Metadata, options?: TrevRpcErrorOptions);
43
+ constructor(code: number, message?: string, metadata?: Metadata, options?: ErrorOptions);
41
44
  }
42
45
 
43
- /** Resource-exhausted status reported when a frame exceeds the configured size limit. */
44
- export class FrameTooLargeError extends TrevRpcError {
45
- length: number;
46
- max: number;
47
-
48
- /** Creates a frame size error. */
49
- constructor(length: number, max: number);
46
+ export interface CallOptions {
47
+ /** Deadline for the whole call, from the start of the request to its final status. */
48
+ timeoutMs?: number;
49
+ /** Largest frame accepted or sent, in bytes. Defaults to 4 MiB. */
50
+ maxFrameSize?: number;
51
+ /** Request metadata. Keys are lowercase ASCII; the `trevrpc-` prefix is reserved. */
52
+ metadata?: MetadataInput;
53
+ /** Cancels the call. */
54
+ signal?: AbortSignal;
55
+ /**
56
+ * Called with the response headers, empty when the server sent none, as soon as the first
57
+ * response frame arrives. A callback that throws fails the call.
58
+ */
59
+ onResponseHeaders?(headers: Metadata): void;
60
+ /**
61
+ * Called with the trailing metadata of the final status when the call succeeds, before its
62
+ * result is returned or its response stream ends. A failed call reports its metadata on the
63
+ * TrevRpcError instead. A callback that throws fails the call.
64
+ */
65
+ onResponseMetadata?(metadata: Metadata): void;
66
+ }
67
+
68
+ export interface TransportStream {
69
+ readable: ReadableStream<Uint8Array>;
70
+ writable: WritableStream<Uint8Array>;
50
71
  }
51
72
 
52
- /** Converts a number into a known status code, defaulting unknown values to Unknown. */
53
- export function codeFromNumber(code: number): StatusCode;
54
- /** Returns the canonical status code name. */
55
- export function codeName(code: number): string;
56
- /** Creates a TrevRPC status error. */
57
- export function statusError(code: number, message?: string, metadata?: Metadata): TrevRpcError;
58
- /** Builds a status error from an RPC response. */
59
- export function statusFromResponse(response?: RpcResponseMessage | null): TrevRpcError;
60
- /** Reports whether a status-like value is OK. */
61
- export function isOkStatus(status?: { code?: number } | null): boolean;
62
- /** Creates an internal error status. */
63
- export function internal(message: string): TrevRpcError;
64
- /** Creates an invalid-argument status. */
65
- export function invalidArgument(message: string): TrevRpcError;
66
- /** Creates a deadline-exceeded status. */
67
- export function deadlineExceeded(message: string): TrevRpcError;
68
- /** Creates an unavailable status. */
69
- export function unavailable(message: string): TrevRpcError;
70
- /** Creates a resource-exhausted status. */
71
- export function resourceExhausted(message: string): TrevRpcError;
72
- /** Creates a cancelled status. */
73
- export function cancelled(message: string): TrevRpcError;
74
-
75
- export const MaxMetadataEntries: 64;
76
- export const MaxMetadataKeyLen: 128;
77
- export const MaxMetadataValueLen: number;
78
- export const MaxMetadataTotalSize: number;
79
- export const ReservedMetadataPrefix: "trevrpc-";
80
-
81
- export type MetadataValue = string | Uint8Array | ArrayBuffer | ArrayBufferView | readonly number[];
82
- export type MetadataInput = Record<string, MetadataValue> | ReadonlyMap<string, MetadataValue>;
83
- export type Metadata = Record<string, Uint8Array>;
84
-
85
- /** Converts a metadata value into bytes. */
86
- export function metadataValueToBytes(value: MetadataValue): Uint8Array;
87
- /** Normalizes a metadata key to lowercase ASCII. */
88
- export function normalizeMetadataKey(key: string): string;
89
- /** Normalizes metadata keys and converts metadata values to bytes. */
90
- export function normalizeMetadata(metadata?: MetadataInput): Metadata;
91
- /** Validates metadata key syntax, value sizes, and total metadata limits. */
92
- export function validateMetadata(metadata?: MetadataInput): void;
73
+ /**
74
+ * The datagram side of a WebTransport session (`WebTransport.datagrams`). TrevRPC needs only
75
+ * `readable`; sending also needs `createWritable()` (or the older `writable`), and
76
+ * `maxDatagramSize` bounds what is sent as a datagram (1100 bytes if it is missing).
77
+ */
78
+ export interface DatagramTransport {
79
+ readonly readable: ReadableStream<Uint8Array>;
80
+ readonly maxDatagramSize?: number;
81
+ createWritable?(): WritableStream<Uint8Array>;
82
+ readonly writable?: WritableStream<Uint8Array>;
83
+ }
93
84
 
94
- export const WireVersion: 1;
95
- export const RpcKind: Readonly<{
96
- Unary: 0;
97
- ClientStreaming: 1;
98
- ServerStreaming: 2;
99
- BidirectionalStreaming: 3;
100
- }>;
101
- export const RpcStreamFrameKind: Readonly<{
102
- Message: 0;
103
- Status: 1;
104
- }>;
85
+ /**
86
+ * Anything that opens a bidirectional byte stream per call, such as a Channel or WebTransport.
87
+ * Calls to methods that mark a direction unreliable use the `datagrams` of the session that opens
88
+ * their stream, when it has them.
89
+ */
90
+ export interface Transport {
91
+ createBidirectionalStream(): Promise<TransportStream>;
92
+ /** Datagrams of the session that the next stream opens on; absent without datagrams. */
93
+ readonly datagrams?: DatagramTransport;
94
+ /**
95
+ * Like `createBidirectionalStream()`, but also returns the datagrams of the session that opened
96
+ * the stream. Transports whose session can change, such as a Channel, implement it so a call
97
+ * never mixes the stream of one session with the datagrams of another.
98
+ */
99
+ createBidirectionalStreamWithDatagrams?(): Promise<{
100
+ stream: TransportStream;
101
+ datagrams?: DatagramTransport;
102
+ }>;
103
+ }
105
104
 
106
- export type RpcKindValue = (typeof RpcKind)[keyof typeof RpcKind];
107
- export type RpcStreamFrameKindValue = (typeof RpcStreamFrameKind)[keyof typeof RpcStreamFrameKind];
108
105
  export type RpcMethodKind =
109
106
  | "unary"
110
107
  | "clientStreaming"
111
108
  | "serverStreaming"
112
109
  | "bidirectionalStreaming";
113
110
 
114
- export interface RpcRequestMessage {
115
- service: string;
116
- method: string;
117
- body: Uint8Array;
118
- metadata: Metadata;
119
- kind: RpcKindValue;
120
- version: number;
121
- timeoutNanos?: number | string | Long;
122
- }
123
-
124
- export interface RpcResponseMessage {
125
- status?: number;
126
- message?: string;
127
- body?: Uint8Array;
128
- metadata?: Metadata;
129
- }
130
-
131
- export interface RpcStreamFrameMessage {
132
- kind: RpcStreamFrameKindValue;
133
- status?: number;
134
- message?: string;
135
- body?: Uint8Array;
136
- metadata?: Metadata;
137
- }
138
-
139
111
  export interface RpcMethodDescriptor {
140
112
  name: string;
141
113
  kind: RpcMethodKind;
142
114
  inputType: string;
143
115
  outputType: string;
144
- }
145
-
146
- export interface RpcServiceDescriptor<
147
- TMethods extends Record<string, RpcMethodDescriptor> = Record<string, RpcMethodDescriptor>,
148
- > {
116
+ /**
117
+ * The method marks its streamed request messages unreliable (`unreliable_requests` in the
118
+ * `trevrpc.method` option). They are sent as WebTransport datagrams when they fit and the
119
+ * session has datagrams, and may be lost or reordered; otherwise they travel on the stream.
120
+ */
121
+ unreliableRequests?: boolean;
122
+ /**
123
+ * The method marks its streamed response messages unreliable (`unreliable_responses`). The
124
+ * client accepts them as datagrams on any session that has them.
125
+ */
126
+ unreliableResponses?: boolean;
127
+ }
128
+
129
+ export interface RpcServiceDescriptor {
149
130
  name: string;
150
131
  fullName: string;
151
132
  exportName: string;
152
- methods: TMethods;
153
- }
154
-
155
- export const wireRoot: Root;
156
- export const RpcRequest: Type;
157
- export const RpcResponse: Type;
158
- export const RpcStreamFrame: Type;
159
-
160
- /** Creates a protobuf root from a JSON namespace definition. */
161
- export function createRoot(json: import("protobufjs").INamespace): Root;
162
- /** Creates a stream message frame carrying a protobuf body. */
163
- export function messageFrame(body: Uint8Array): RpcStreamFrameMessage;
164
-
165
- export const DefaultMaxFrameSize: number;
166
-
167
- /** Encodes a protobuf message body. */
168
- export function marshalMessage<TRequest extends object>(
169
- messageType: Type,
170
- message: TRequest,
171
- ): Uint8Array;
172
- /** Decodes a protobuf message body. */
173
- export function unmarshalMessage<TResponse = Message<Record<string, unknown>>>(
174
- messageType: Type,
175
- body: Uint8Array,
176
- ): TResponse;
177
- /** Encodes a protobuf message into a length-prefixed TrevRPC frame. */
178
- export function encodeFrame<TMessage extends object>(
179
- messageType: Type,
180
- message: TMessage,
181
- maxFrameSize?: number,
182
- ): Uint8Array;
183
- /** Encodes one streaming message frame carrying an already-encoded protobuf body. */
184
- export function encodeMessageStreamFrame(body: Uint8Array, maxFrameSize?: number): Uint8Array;
185
- /** Encodes multiple streaming message frames into one contiguous write buffer. */
186
- export function encodeMessageStreamFrames(
187
- bodies: Iterable<Uint8Array>,
188
- maxFrameSize?: number,
189
- ): Uint8Array;
190
- /** Decodes a protobuf message from a TrevRPC frame body. */
191
- export function decodeFrame<TMessage = Message<Record<string, unknown>>>(
192
- messageType: Type,
193
- body: Uint8Array,
194
- ): TMessage;
195
- /** Decodes a streaming RPC frame body. */
196
- export function decodeStreamFrameBody(body: Uint8Array): RpcStreamFrameMessage;
197
- /** Writes one length-prefixed protobuf frame. */
198
- export function writeFrame<TMessage extends object>(
199
- writer: WritableStreamDefaultWriter<Uint8Array>,
200
- messageType: Type,
201
- message: TMessage,
202
- maxFrameSize?: number,
203
- ): Promise<void>;
204
- /** Writes multiple streaming message frames in one write. */
205
- export function writeMessageStreamFrames(
206
- writer: WritableStreamDefaultWriter<Uint8Array>,
207
- bodies: Iterable<Uint8Array>,
208
- maxFrameSize?: number,
209
- ): Promise<void>;
210
- /** Decodes and validates the body length stored in a TrevRPC frame header. */
211
- export function frameBodyLength(header: Uint8Array, maxFrameSize?: number): number;
212
-
213
- /** Reads length-prefixed protobuf frames from a byte stream reader. */
214
- export class FrameReader {
215
- /** Creates a frame reader over a stream reader. */
216
- constructor(reader: ReadableStreamDefaultReader<Uint8Array>);
217
-
218
- /** Reads and decodes one frame. */
219
- readFrame<TMessage = Message<Record<string, unknown>>>(
220
- messageType: Type,
221
- maxFrameSize?: number,
222
- ): Promise<TMessage>;
223
- /** Reads and decodes one frame, or returns null when already at EOF. */
224
- readFrameOrEOF<TMessage = Message<Record<string, unknown>>>(
225
- messageType: Type,
226
- maxFrameSize?: number,
227
- ): Promise<TMessage | null>;
228
- /** Reads and decodes one streaming RPC frame, or returns null when already at EOF. */
229
- readStreamFrameOrEOF(maxFrameSize?: number): Promise<RpcStreamFrameMessage | null>;
230
- /** Reads one streaming RPC frame, then drains complete frames already buffered. */
231
- readStreamFrameBatchOrEOF(
232
- maxBatch?: number,
233
- maxFrameSize?: number,
234
- ): Promise<RpcStreamFrameMessage[] | null>;
235
- /** Reads stream message body batches, with at most one terminal status. */
236
- readStreamMessageBodyBatchOrEOF(
237
- maxBatch?: number,
238
- maxFrameSize?: number,
239
- ): Promise<{ bodies: Uint8Array[]; status: RpcStreamFrameMessage | null } | null>;
240
- /** Reads one raw frame body, or returns null when already at EOF. */
241
- readRawFrameBodyOrEOF(maxFrameSize?: number): Promise<Uint8Array | null>;
242
- /** Reads exactly size bytes from the underlying reader. */
243
- readExact(size: number, allowEofAtStart: boolean): Promise<Uint8Array | null>;
244
- /** Reads a complete buffered frame body without waiting, or undefined. */
245
- tryReadFrameBody(maxFrameSize?: number): Uint8Array | undefined;
246
- /** Removes size bytes from the buffered data. */
247
- consume(size: number): Uint8Array;
248
- /** Copies size bytes from the buffered data without removing them. */
249
- peek(size: number): Uint8Array;
250
- }
251
-
252
- export interface CallOptions {
253
- timeoutMs?: number;
254
- maxFrameSize?: number;
255
- maxResponseBodySize?: number;
256
- maxResponseMessages?: number;
257
- maxResponseStreamBodySize?: number;
258
- streamIdleTimeoutMs?: number;
259
- metadata?: MetadataInput;
260
- signal?: AbortSignal;
261
- }
262
-
263
- export interface ResolvedCallOptions {
264
- timeoutMs?: number;
265
- maxFrameSize?: number;
266
- maxResponseBodySize: number;
267
- maxResponseMessages: number;
268
- maxResponseStreamBodySize: number;
269
- streamIdleTimeoutMs: number;
270
- metadata: Metadata;
271
- signal?: AbortSignal;
272
- }
273
-
274
- export interface Transport {
275
- /** Sends a unary RPC request and returns its response. */
276
- call(request: RpcRequestMessage, options?: ResolvedCallOptions): Promise<RpcResponseMessage>;
277
- /** Sends a streaming RPC request and returns response frames. */
278
- streamingCall(
279
- request: RpcRequestMessage,
280
- requestBody: AsyncIterable<Uint8Array>,
281
- options?: ResolvedCallOptions,
282
- ): Promise<AsyncIterable<RpcStreamFrameMessage>>;
283
- }
284
-
285
- export interface UnaryResponse<TResponse> {
286
- readonly message: TResponse;
287
- readonly metadata: Metadata;
133
+ methods: Record<string, RpcMethodDescriptor>;
288
134
  }
289
135
 
136
+ /** The final status of a call that ended with OK. */
290
137
  export interface StreamStatus {
291
138
  readonly code: StatusCode;
292
139
  readonly message: string;
293
140
  readonly metadata: Metadata;
294
141
  }
295
142
 
296
- export interface ResponseAsyncIterable<TResponse> extends AsyncIterable<TResponse> {
143
+ /**
144
+ * Responses of a server-streaming call. Iteration ends after the final OK status and throws a
145
+ * TrevRpcError for any other outcome. Leaving the loop early cancels the call.
146
+ */
147
+ export interface ResponseStream<TResponse> extends AsyncIterable<TResponse> {
148
+ /** Settles with the final status, or rejects with the error that ended the call. */
297
149
  readonly status: Promise<StreamStatus>;
150
+ /**
151
+ * The response headers, empty when the server sent none. Settles when the first response frame
152
+ * arrives, before the first message is received, or rejects with the error that ended the call.
153
+ */
154
+ readonly headers: Promise<Metadata>;
155
+ /** Cancels the call unless it already finished. */
298
156
  close(reason?: unknown): Promise<void>;
299
157
  }
300
158
 
301
- declare const unaryServerResponseBrand: unique symbol;
302
- declare const streamingServerResponseBrand: unique symbol;
303
-
304
- export interface UnaryServerResponse<T> {
305
- /** Opaque brand; construct responses with createUnaryResponse(). */
306
- readonly [unaryServerResponseBrand]: true;
307
- readonly message: T;
308
- readonly metadata: Metadata;
309
- }
310
-
311
- export interface StreamingServerResponse<T> {
312
- /** Opaque brand; construct responses with createStreamingResponse(). */
313
- readonly [streamingServerResponseBrand]: true;
314
- readonly messages: Iterable<T> | AsyncIterable<T>;
315
- readonly status: StreamStatus;
316
- }
317
-
318
- /** Creates an opaque unary generated-server response envelope. */
319
- export function createUnaryResponse<T>(
320
- message: T,
321
- metadata?: MetadataInput,
322
- ): UnaryServerResponse<T>;
323
-
324
- /** Creates an opaque streaming generated-server response envelope. */
325
- export function createStreamingResponse<T>(
326
- messages: Iterable<T> | AsyncIterable<T>,
327
- status?: {
328
- code?: StatusCode;
329
- message?: string;
330
- metadata?: MetadataInput;
331
- },
332
- ): StreamingServerResponse<T>;
333
-
334
- export interface ClientStreamingCall<TRequest extends object, TResponse> {
335
- /** Sends one request message. */
159
+ export interface ClientStreamingCall<TRequest, TResponse> {
160
+ /**
161
+ * Sends one request message; the promise settles when the transport accepted it, which applies
162
+ * backpressure.
163
+ *
164
+ * Rejects as soon as the server ends the call before the upload is done: with the server's
165
+ * `TrevRpcError` if its final status is not OK, even if the server never reads the rest of the
166
+ * request, and with `Code.Cancelled` if the status is OK (the call succeeded without the rest
167
+ * of the upload; `closeAndRecv()` returns its response). A response that fails after the
168
+ * upload stopped, such as a lost connection, is reported instead of a generic closed-stream
169
+ * error. A failed send is not retried or reported twice: later sends fail the same way, and
170
+ * `closeAndRecv()` returns the call's outcome.
171
+ *
172
+ * Pending sends are rejected too when the call is cancelled or its deadline expires.
173
+ */
336
174
  send(request: TRequest): Promise<void>;
337
- /** Sends multiple request messages. */
338
- sendMany(requests: Iterable<TRequest>): Promise<void>;
339
- /** Closes the request stream. */
340
- closeSend(): Promise<void>;
175
+ /**
176
+ * Sends every message of `requests`, then closes the request stream. If the server ends the
177
+ * call first, the rest is not sent and the promise resolves; `closeAndRecv()` reports the
178
+ * outcome. A send that fails otherwise rejects as `send()` does, and requests that throw cancel
179
+ * the call and reject with what they threw.
180
+ */
181
+ sendAll(requests: Iterable<TRequest> | AsyncIterable<TRequest>): Promise<void>;
341
182
  /** Closes the request stream and returns the final response. */
342
183
  closeAndRecv(): Promise<TResponse>;
343
- /** Closes the request stream and returns the final response envelope. */
344
- closeAndRecvWithResponse(): Promise<UnaryResponse<TResponse>>;
345
- /** Releases call resources without waiting for the response. */
184
+ /** Cancels the call unless it already finished. */
346
185
  close(reason?: unknown): Promise<void>;
347
186
  }
348
187
 
349
- export interface BidirectionalStreamingCall<
350
- TRequest extends object,
351
- TResponse,
352
- > extends AsyncIterable<TResponse> {
353
- /** Resolves to the terminal stream status after completion. */
354
- status: Promise<StreamStatus>;
355
- /** Sends one request message. */
188
+ /**
189
+ * On a method that marks a direction unreliable (`RpcMethodDescriptor.unreliableRequests` or
190
+ * `unreliableResponses`), a call on a session with datagrams may send its request messages, and
191
+ * receive its response messages, as datagrams: they can be lost or reordered, never duplicated.
192
+ * Response datagrams are delivered after the response headers, merged with the stream's messages
193
+ * in arrival order, and dropped when the call's queue is full (32 messages or 1 MiB) or the call
194
+ * has ended. Without datagrams, such as over WebSocket, everything stays on the stream.
195
+ */
196
+ export interface BidirectionalStreamingCall<TRequest, TResponse> extends AsyncIterable<TResponse> {
197
+ /** Settles with the final status, or rejects with the error that ended the call. */
198
+ readonly status: Promise<StreamStatus>;
199
+ /**
200
+ * The response headers, empty when the server sent none. Settles when the first response frame
201
+ * arrives, before the first message is received, or rejects with the error that ended the call.
202
+ */
203
+ readonly headers: Promise<Metadata>;
204
+ /**
205
+ * Sends one request message; the promise settles when the transport accepted it, which applies
206
+ * backpressure.
207
+ *
208
+ * Rejects as soon as the server ends the call before the upload is done, even if nobody is
209
+ * calling `recv()` and the server never reads the rest of the request: with the server's
210
+ * `TrevRpcError` if its final status is not OK, and with `Code.Cancelled` if the status is OK
211
+ * (`recv()` then returns `undefined` after the responses that were sent). A response that
212
+ * fails after the upload stopped, such as a lost connection, is reported instead of a generic
213
+ * closed-stream error. Later sends fail the same way, `closeSend()` resolves, and `recv()` and
214
+ * `status` report the call's outcome.
215
+ *
216
+ * While the request side is open the response is read ahead of `recv()` to find the final
217
+ * status: at most 32 frames or 1 MiB (plus one frame of at most `maxFrameSize`), after which
218
+ * reading pauses until `recv()` takes messages. Responses read ahead are delivered in order.
219
+ *
220
+ * Pending sends are rejected too when the call is cancelled or its deadline expires.
221
+ */
356
222
  send(request: TRequest): Promise<void>;
357
- /** Sends multiple request messages. */
358
- sendMany(requests: Iterable<TRequest>): Promise<void>;
359
- /** Receives one response message, or undefined after the response stream completes. */
223
+ /**
224
+ * Sends every message of `requests`, then closes the request stream. If the server ends the
225
+ * call first, the rest is not sent and the promise resolves; `recv()` and `status` report the
226
+ * outcome. A send that fails otherwise rejects as `send()` does, and requests that throw cancel
227
+ * the call and reject with what they threw.
228
+ */
229
+ sendAll(requests: Iterable<TRequest> | AsyncIterable<TRequest>): Promise<void>;
230
+ /** Receives the next response message, or undefined after the final OK status. */
360
231
  recv(): Promise<TResponse | undefined>;
361
- /** Closes the request stream while keeping the response stream readable. */
232
+ /**
233
+ * Closes the request stream while keeping the response stream readable. Resolves if the server
234
+ * already ended the call; its final status is reported by `recv()` and `status`.
235
+ */
362
236
  closeSend(): Promise<void>;
363
- /** Releases call resources without waiting for more responses. */
237
+ /** Cancels the call unless it already finished. */
364
238
  close(reason?: unknown): Promise<void>;
365
239
  }
366
240
 
@@ -369,73 +243,6 @@ export type ServiceClient = Record<
369
243
  (requestOrOptions?: unknown, options?: CallOptions) => Promise<unknown>
370
244
  >;
371
245
 
372
- /** Returns the default client call options. */
373
- export function defaultCallOptions(): ResolvedCallOptions;
374
- /** Merges call options and normalizes metadata. */
375
- export function mergeCallOptions(base?: CallOptions, override?: CallOptions): ResolvedCallOptions;
376
- /** Calls a unary RPC and decodes the protobuf response. */
377
- export function unary<
378
- TRequest extends object = Record<string, unknown>,
379
- TResponse = Message<Record<string, unknown>>,
380
- >(
381
- transport: Transport,
382
- service: string,
383
- method: string,
384
- requestType: Type,
385
- responseType: Type,
386
- request: TRequest,
387
- options?: CallOptions,
388
- ): Promise<TResponse>;
389
- /** Calls a unary RPC and returns the decoded response envelope. */
390
- export function unaryWithResponse<
391
- TRequest extends object = Record<string, unknown>,
392
- TResponse = Message<Record<string, unknown>>,
393
- >(
394
- transport: Transport,
395
- service: string,
396
- method: string,
397
- requestType: Type,
398
- responseType: Type,
399
- request: TRequest,
400
- options?: CallOptions,
401
- ): Promise<UnaryResponse<TResponse>>;
402
- /** Calls a server-streaming RPC and returns a decoded response stream. */
403
- export function serverStreaming<
404
- TRequest extends object = Record<string, unknown>,
405
- TResponse = Message<Record<string, unknown>>,
406
- >(
407
- transport: Transport,
408
- service: string,
409
- method: string,
410
- requestType: Type,
411
- responseType: Type,
412
- request: TRequest,
413
- options?: CallOptions,
414
- ): Promise<ResponseAsyncIterable<TResponse>>;
415
- /** Calls a client-streaming RPC and returns a sendable call object. */
416
- export function clientStreaming<
417
- TRequest extends object = Record<string, unknown>,
418
- TResponse = Message<Record<string, unknown>>,
419
- >(
420
- transport: Transport,
421
- service: string,
422
- method: string,
423
- requestType: Type,
424
- responseType: Type,
425
- options?: CallOptions,
426
- ): Promise<ClientStreamingCall<TRequest, TResponse>>;
427
- /** Calls a bidirectional-streaming RPC and returns a sendable call object. */
428
- export function bidirectionalStreaming<
429
- TRequest extends object = Record<string, unknown>,
430
- TResponse = Message<Record<string, unknown>>,
431
- >(
432
- transport: Transport,
433
- service: string,
434
- method: string,
435
- requestType: Type,
436
- responseType: Type,
437
- options?: CallOptions,
438
- ): Promise<BidirectionalStreamingCall<TRequest, TResponse>>;
439
246
  /** Creates a service client from a generated service descriptor. */
440
247
  export function createServiceClient<TClient extends ServiceClient = ServiceClient>(
441
248
  transport: Transport,
@@ -444,134 +251,99 @@ export function createServiceClient<TClient extends ServiceClient = ServiceClien
444
251
  options?: CallOptions,
445
252
  ): TClient;
446
253
 
447
- export interface WebTransportCloseInfoLike {
448
- closeCode?: number;
449
- reason?: string;
450
- }
451
-
452
- export interface WebTransportBidirectionalStreamLike {
453
- readable: ReadableStream<Uint8Array>;
454
- writable: WritableStream<Uint8Array>;
455
- }
456
-
457
- export interface WebTransportSessionLike {
458
- ready: Promise<void>;
459
- closed?: Promise<WebTransportCloseInfoLike>;
460
- close?(closeInfo?: WebTransportCloseInfoLike): void;
461
- createBidirectionalStream?(): Promise<WebTransportBidirectionalStreamLike>;
462
- }
463
-
464
- export interface WebTransportConstructorLike {
465
- new (url: string | URL, options?: BrowserWebTransportOptions): WebTransportSessionLike;
466
- }
467
-
468
254
  export interface WebTransportCertificateHash {
469
255
  algorithm: string;
470
256
  value: ArrayBuffer | ArrayBufferView;
471
257
  }
472
258
 
473
- export interface BrowserWebTransportOptions {
259
+ export interface WebTransportSessionLike extends Transport {
260
+ readonly ready: Promise<unknown>;
261
+ /**
262
+ * The WebTransport protocol the server selected. An empty or missing value means wire version 1.
263
+ * Any other value than "trevrpc-1" fails the connection attempt with FailedPrecondition.
264
+ */
265
+ readonly protocol?: string;
266
+ readonly closed: Promise<unknown>;
267
+ close(closeInfo?: { closeCode?: number; reason?: string }): void;
268
+ }
269
+
270
+ /** How a channel reaches the server: WebTransport, or QMux over WebSocket as the fallback. */
271
+ export type TransportKind = "webtransport" | "websocket";
272
+
273
+ export interface ConnectOptions {
274
+ /**
275
+ * Transports to use, in order of preference. The default, `["webtransport", "websocket"]`,
276
+ * starts QMux over WebSocket once WebTransport fails or has not connected within
277
+ * `fallbackDelayMs`, and uses whichever is ready first.
278
+ */
279
+ transports?: readonly TransportKind[];
280
+ /** The `wss://` URL of the server's TCP listener. Defaults to `url` with a `wss:` scheme. */
281
+ webSocketUrl?: string | URL;
282
+ /** How long WebTransport may take before the WebSocket fallback starts. Defaults to 300. */
283
+ fallbackDelayMs?: number;
284
+ /** How long reconnects keep using WebSocket after it won, before trying WebTransport again. */
285
+ reprobeIntervalMs?: number;
286
+ /** WebSocket implementation to use instead of the global one. */
287
+ WebSocket?: new (url: string | URL, protocols?: string | string[]) => WebSocket;
474
288
  allowPooling?: boolean;
475
289
  congestionControl?: "default" | "low-latency" | "throughput";
476
290
  requireUnreliable?: boolean;
291
+ /**
292
+ * Trusts a self-signed ECDSA certificate (at most 14 days old) by its SHA-256 hash. WebTransport
293
+ * only: the WebSocket fallback needs a certificate the browser trusts.
294
+ */
477
295
  serverCertificateHashes?: readonly WebTransportCertificateHash[];
296
+ /**
297
+ * WebTransport implementation to use instead of the global one. It is constructed with
298
+ * `protocols: ["trevrpc-1"]`, the wire version, which cannot be changed.
299
+ */
300
+ WebTransport?: new (url: string | URL, options?: object) => WebTransportSessionLike;
301
+ /** Cancels the initial connection attempt only. */
302
+ signal?: AbortSignal;
303
+ /** Receives channel state transitions. */
304
+ onStateChange?(change: ChannelStateChange): void;
478
305
  }
479
306
 
480
- export interface WebTransportOptions extends BrowserWebTransportOptions {
481
- WebTransport?: WebTransportConstructorLike;
482
- maxFrameSize?: number;
483
- }
484
-
485
- export type ChannelState = "connecting" | "ready" | "reconnecting" | "closed";
307
+ export type ChannelState = "ready" | "reconnecting" | "closed";
486
308
 
487
- export interface ChannelLifecycle {
309
+ export interface ChannelStateChange {
488
310
  state: ChannelState;
489
311
  previousState: ChannelState;
490
- generation: number;
312
+ /** Reconnect attempt number while reconnecting, starting at one. */
491
313
  attempt?: number;
314
+ /** Delay before the reconnect attempt. */
492
315
  delayMs?: number;
316
+ /** Why the session was lost or the previous attempt failed. */
493
317
  error?: unknown;
318
+ /** The transport of the new session, when it becomes ready. */
319
+ transport?: TransportKind;
494
320
  }
495
321
 
496
- export type ChannelLifecycleEvent = Event & {
497
- readonly detail: ChannelLifecycle;
498
- };
322
+ /** Opens a channel to a TrevRPC server and waits for its session to be ready. */
323
+ export function connect(url: string | URL, options?: ConnectOptions): Promise<Channel>;
499
324
 
500
- export interface ChannelLifecycleOptions {
501
- /** Receives channel lifecycle transitions. */
502
- onStateChange?(event: ChannelLifecycle): void;
503
- }
325
+ /**
326
+ * A session that reconnects in the background after it is lost: WebTransport, or QMux over
327
+ * WebSocket when WebTransport is unavailable or blocked. Calls fail fast with Unavailable while it
328
+ * reconnects and are never replayed.
329
+ */
330
+ export class Channel implements Transport {
331
+ private constructor();
504
332
 
505
- type TrevRpcEventListener = ((event: Event) => void) | { handleEvent(event: Event): void };
506
- interface TrevRpcEventListenerOptions {
507
- capture?: boolean;
508
- }
509
- interface TrevRpcAddEventListenerOptions extends TrevRpcEventListenerOptions {
510
- once?: boolean;
511
- passive?: boolean;
512
- signal?: AbortSignal;
513
- }
333
+ /** Opens a channel to a TrevRPC server and waits for its session to be ready. */
334
+ static connect(url: string | URL, options?: ConnectOptions): Promise<Channel>;
514
335
 
515
- export interface RpcChannel extends Transport, EventTarget {
516
- readonly ready: boolean;
517
336
  readonly state: ChannelState;
518
- readonly generation: number;
519
- waitUntilReady(): Promise<void>;
520
- close(closeInfo?: WebTransportCloseInfoLike): void;
521
- }
522
-
523
- export interface BrowserChannelOptions extends WebTransportOptions, ChannelLifecycleOptions {
524
- /** Bounds initial readiness only. Later reconnects continue until close(). */
525
- timeoutMs?: number;
526
- /** Cancels initial readiness only. Later reconnects continue until close(). */
527
- signal?: AbortSignal;
528
- }
529
-
530
- /** Opens a browser channel and waits for its first ready generation. */
531
- export function connect(url: string | URL, options?: BrowserChannelOptions): Promise<Channel>;
532
-
533
- /** Application channel with background connection reconnection. */
534
- export class Channel extends EventTarget implements RpcChannel {
535
- readonly url: string | URL;
536
- readonly options: Readonly<BrowserChannelOptions>;
537
- readonly ready: boolean;
538
- readonly state: ChannelState;
539
- readonly generation: number;
540
-
541
- constructor(url: string | URL, options?: BrowserChannelOptions);
542
-
543
- /** Creates a channel and waits for its first ready generation. */
544
- static connect(url: string | URL, options?: BrowserChannelOptions): Promise<Channel>;
545
- /** Waits for the current or next connection generation to become ready. */
337
+ /** The transport of the current or last session. */
338
+ readonly transport: TransportKind;
339
+ createBidirectionalStream(): Promise<TransportStream>;
340
+ /** Opens a stream together with the datagrams of the session that carries it, if any. */
341
+ createBidirectionalStreamWithDatagrams(): Promise<{
342
+ stream: TransportStream;
343
+ datagrams?: DatagramTransport;
344
+ }>;
345
+ /** Resolves once the channel is ready, immediately if it already is. */
546
346
  waitUntilReady(): Promise<void>;
547
- /** Sends a unary call on the current generation without replaying it. */
548
- call(request: RpcRequestMessage, options?: ResolvedCallOptions): Promise<RpcResponseMessage>;
549
- /** Starts a streaming call on the current generation without resuming it later. */
550
- streamingCall(
551
- request: RpcRequestMessage,
552
- requestBody: AsyncIterable<Uint8Array>,
553
- options?: ResolvedCallOptions,
554
- ): Promise<AsyncIterableIterator<RpcStreamFrameMessage>>;
555
- /** Stops reconnecting and closes the current generation. */
556
- close(closeInfo?: WebTransportCloseInfoLike): void;
557
- addEventListener(
558
- type: "statechange" | ChannelState,
559
- callback: (event: ChannelLifecycleEvent) => void,
560
- options?: boolean | TrevRpcAddEventListenerOptions,
561
- ): void;
562
- addEventListener(
563
- type: string,
564
- callback: TrevRpcEventListener | null,
565
- options?: boolean | TrevRpcAddEventListenerOptions,
566
- ): void;
567
- removeEventListener(
568
- type: "statechange" | ChannelState,
569
- callback: (event: ChannelLifecycleEvent) => void,
570
- options?: boolean | TrevRpcEventListenerOptions,
571
- ): void;
572
- removeEventListener(
573
- type: string,
574
- callback: TrevRpcEventListener | null,
575
- options?: boolean | TrevRpcEventListenerOptions,
576
- ): void;
347
+ /** Stops reconnecting and closes the current session. */
348
+ close(closeInfo?: { closeCode?: number; reason?: string }): void;
577
349
  }