@replit/river 0.200.0-rc.2 → 0.200.0-rc.20

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 (88) hide show
  1. package/README.md +30 -29
  2. package/dist/chunk-3HI3IJTL.js +285 -0
  3. package/dist/chunk-3HI3IJTL.js.map +1 -0
  4. package/dist/chunk-5L5RNZXH.js +391 -0
  5. package/dist/chunk-5L5RNZXH.js.map +1 -0
  6. package/dist/{chunk-QMM35C3H.js → chunk-BAGOAJ3K.js} +1 -1
  7. package/dist/chunk-BAGOAJ3K.js.map +1 -0
  8. package/dist/{chunk-S5RL45KH.js → chunk-BYCR4VEM.js} +78 -54
  9. package/dist/chunk-BYCR4VEM.js.map +1 -0
  10. package/dist/chunk-DM5QR4HQ.js +60 -0
  11. package/dist/chunk-DM5QR4HQ.js.map +1 -0
  12. package/dist/chunk-OLWVR5AB.js +860 -0
  13. package/dist/chunk-OLWVR5AB.js.map +1 -0
  14. package/dist/chunk-WKBWCRGN.js +437 -0
  15. package/dist/chunk-WKBWCRGN.js.map +1 -0
  16. package/dist/chunk-YBCQVIPR.js +351 -0
  17. package/dist/chunk-YBCQVIPR.js.map +1 -0
  18. package/dist/client-75090f07.d.ts +49 -0
  19. package/dist/connection-c9f96b64.d.ts +32 -0
  20. package/dist/context-9c907028.d.ts +622 -0
  21. package/dist/logging/index.cjs.map +1 -1
  22. package/dist/logging/index.d.cts +1 -1
  23. package/dist/logging/index.d.ts +1 -1
  24. package/dist/logging/index.js +1 -1
  25. package/dist/{index-10ebd26a.d.ts → message-59fe53e1.d.ts} +34 -31
  26. package/dist/router/index.cjs +771 -1159
  27. package/dist/router/index.cjs.map +1 -1
  28. package/dist/router/index.d.cts +14 -48
  29. package/dist/router/index.d.ts +14 -48
  30. package/dist/router/index.js +1238 -15
  31. package/dist/router/index.js.map +1 -1
  32. package/dist/server-109a29e2.d.ts +69 -0
  33. package/dist/services-aa49a9fb.d.ts +811 -0
  34. package/dist/transport/impls/ws/client.cjs +1293 -1034
  35. package/dist/transport/impls/ws/client.cjs.map +1 -1
  36. package/dist/transport/impls/ws/client.d.cts +7 -5
  37. package/dist/transport/impls/ws/client.d.ts +7 -5
  38. package/dist/transport/impls/ws/client.js +11 -11
  39. package/dist/transport/impls/ws/client.js.map +1 -1
  40. package/dist/transport/impls/ws/server.cjs +1437 -1072
  41. package/dist/transport/impls/ws/server.cjs.map +1 -1
  42. package/dist/transport/impls/ws/server.d.cts +7 -5
  43. package/dist/transport/impls/ws/server.d.ts +7 -5
  44. package/dist/transport/impls/ws/server.js +20 -8
  45. package/dist/transport/impls/ws/server.js.map +1 -1
  46. package/dist/transport/index.cjs +1720 -1400
  47. package/dist/transport/index.cjs.map +1 -1
  48. package/dist/transport/index.d.cts +5 -26
  49. package/dist/transport/index.d.ts +5 -26
  50. package/dist/transport/index.js +11 -11
  51. package/dist/util/testHelpers.cjs +1164 -591
  52. package/dist/util/testHelpers.cjs.map +1 -1
  53. package/dist/util/testHelpers.d.cts +41 -38
  54. package/dist/util/testHelpers.d.ts +41 -38
  55. package/dist/util/testHelpers.js +124 -89
  56. package/dist/util/testHelpers.js.map +1 -1
  57. package/package.json +3 -3
  58. package/dist/chunk-47TFNAY2.js +0 -476
  59. package/dist/chunk-47TFNAY2.js.map +0 -1
  60. package/dist/chunk-4VNY34QG.js +0 -106
  61. package/dist/chunk-4VNY34QG.js.map +0 -1
  62. package/dist/chunk-7CKIN3JT.js +0 -2004
  63. package/dist/chunk-7CKIN3JT.js.map +0 -1
  64. package/dist/chunk-CZP4LK3F.js +0 -335
  65. package/dist/chunk-CZP4LK3F.js.map +0 -1
  66. package/dist/chunk-DJCW3SKT.js +0 -59
  67. package/dist/chunk-DJCW3SKT.js.map +0 -1
  68. package/dist/chunk-NQWDT6GS.js +0 -347
  69. package/dist/chunk-NQWDT6GS.js.map +0 -1
  70. package/dist/chunk-ONUXWVRC.js +0 -492
  71. package/dist/chunk-ONUXWVRC.js.map +0 -1
  72. package/dist/chunk-QMM35C3H.js.map +0 -1
  73. package/dist/chunk-S5RL45KH.js.map +0 -1
  74. package/dist/connection-3f117047.d.ts +0 -17
  75. package/dist/connection-f900e390.d.ts +0 -35
  76. package/dist/services-970f97bb.d.ts +0 -1372
  77. package/dist/transport/impls/uds/client.cjs +0 -1687
  78. package/dist/transport/impls/uds/client.cjs.map +0 -1
  79. package/dist/transport/impls/uds/client.d.cts +0 -17
  80. package/dist/transport/impls/uds/client.d.ts +0 -17
  81. package/dist/transport/impls/uds/client.js +0 -44
  82. package/dist/transport/impls/uds/client.js.map +0 -1
  83. package/dist/transport/impls/uds/server.cjs +0 -1522
  84. package/dist/transport/impls/uds/server.cjs.map +0 -1
  85. package/dist/transport/impls/uds/server.d.cts +0 -19
  86. package/dist/transport/impls/uds/server.d.ts +0 -19
  87. package/dist/transport/impls/uds/server.js +0 -33
  88. package/dist/transport/impls/uds/server.js.map +0 -1
@@ -0,0 +1,811 @@
1
+ import * as _sinclair_typebox from '@sinclair/typebox';
2
+ import { Static, TObject, TUnion, TString, TSchema, TLiteral, TNever } from '@sinclair/typebox';
3
+ import { C as Connection, p as ClientHandshakeOptions, u as ProcedureHandlerContext, o as ServiceContext } from './context-9c907028.js';
4
+ import { c as TransportClientId } from './message-59fe53e1.js';
5
+ import { C as ClientTransport } from './client-75090f07.js';
6
+
7
+ declare const ReadableBrokenError: Static<BaseErrorSchemaType>;
8
+ /**
9
+ * Similar to {@link Result} but with an extra error to handle cases where {@link Readable.break} is called
10
+ */
11
+ type ReadableResult<T, E extends Static<BaseErrorSchemaType>> = Result<T, E | typeof ReadableBrokenError>;
12
+ /**
13
+ * A simple {@link AsyncIterator} used in {@link Readable}
14
+ * that doesn't have a the extra "return" and "throw" methods, and
15
+ * the doesn't have a "done value" (TReturn).
16
+ */
17
+ interface ReadableIterator<T, E extends Static<BaseErrorSchemaType>> {
18
+ next(): Promise<{
19
+ done: false;
20
+ value: ReadableResult<T, E>;
21
+ } | {
22
+ done: true;
23
+ value: undefined;
24
+ }>;
25
+ }
26
+ /**
27
+ * A {@link Readable} is an abstraction from which data is consumed from {@link Writable} source.
28
+ *
29
+ * - On the server the argument passed the procedure handler for `upload` and `stream` implements a {@link Readable} interface
30
+ * so you can read client's request data.
31
+ * - On the client the returned value of `subscription` or `stream` invocation implements a {@link Readable} interface
32
+ * so you can read server's response data.
33
+ *
34
+ * A {@link Readable} can only have one consumer (iterator or {@link collect}) for the {@link Readable}'s
35
+ * lifetime, in essense, reading from a {@link Readable} locks it forever.
36
+ */
37
+ interface Readable<T, E extends Static<BaseErrorSchemaType>> {
38
+ /**
39
+ * {@link Readable} implements AsyncIterator API and can be consumed via
40
+ * for-await-of loops. Iteration locks the Readable. Exiting the loop
41
+ * will **not** release the lock and it'll be equivalent of calling
42
+ * {@link break}.
43
+ */
44
+ [Symbol.asyncIterator](): ReadableIterator<T, E>;
45
+ /**
46
+ * {@link collect} locks the {@link Readable} and returns a promise that resolves
47
+ * with an array of the content when the {@link Readable} is fully done. This could
48
+ * be due to the {@link Writable} end of the pipe closing cleanly, the procedure invocation
49
+ * is cancelled, or {@link break} is called.
50
+ */
51
+ collect(): Promise<Array<ReadableResult<T, E>>>;
52
+ /**
53
+ * {@link break} locks the {@link Readable} and discards any existing or future incoming data.
54
+ *
55
+ * If there is an existing reader waiting for the next value, {@link break} causes it to
56
+ * resolve with a {@link ReadableBrokenError} error.
57
+ */
58
+ break(): undefined;
59
+ /**
60
+ * {@link isReadable} returns true if it's safe to read from the {@link Readable}, either
61
+ * via iteration or {@link collect}. It returns false if the {@link Readable} is locked
62
+ * by a consumer (iterator or {@link collect}) or readable was broken via {@link break}.
63
+ */
64
+ isReadable(): boolean;
65
+ }
66
+ /**
67
+ * A {@link Writeable} is a an abstraction for a {@link Readable} destination to which data is written to.
68
+ *
69
+ * - On the server the argument passed the procedure handler for `subscription` and `stream` implements a {@link Writeable}
70
+ * so you can write server's response data.
71
+ * - On the client the returned value of `upload` or `stream` invocation implements a {@link Writeable}
72
+ * so you can write client's request data.
73
+ *
74
+ * Once closed, a {@link Writeable} can't be re-opened.` `
75
+ */
76
+ interface Writable<T> {
77
+ /**
78
+ * {@link write} writes a value to the pipe. An error is thrown if writing to a closed {@link Writable}.
79
+ */
80
+ write(value: T): undefined;
81
+ /**
82
+ * {@link close} signals the closure of the {@link Writeable}, informing the {@link Readable} end that
83
+ * all data has been transmitted and we've cleanly closed.
84
+ *
85
+ * Calling {@link close} multiple times is a no-op.
86
+ */
87
+ close(): undefined;
88
+ /**
89
+ * {@link isWritable} returns true if it's safe to call {@link write}, which
90
+ * means that the {@link Writable} hasn't been closed due to {@link close} being called
91
+ * on this {@link Writable} or the procedure invocation ending for any reason.
92
+ */
93
+ isWritable(): boolean;
94
+ }
95
+
96
+ interface CallOptions {
97
+ signal?: AbortSignal;
98
+ }
99
+ type RpcFn<Service extends AnyService, ProcName extends keyof Service['procedures']> = (reqInit: ProcInit<Service, ProcName>, options?: CallOptions) => Promise<Result<ProcResponse<Service, ProcName>, ProcErrors<Service, ProcName>>>;
100
+ type UploadFn<Service extends AnyService, ProcName extends keyof Service['procedures']> = (reqInit: ProcInit<Service, ProcName>, options?: CallOptions) => {
101
+ reqWritable: Writable<ProcRequest<Service, ProcName>>;
102
+ finalize: () => Promise<Result<ProcResponse<Service, ProcName>, ProcErrors<Service, ProcName>>>;
103
+ };
104
+ type StreamFn<Service extends AnyService, ProcName extends keyof Service['procedures']> = (reqInit: ProcInit<Service, ProcName>, options?: CallOptions) => {
105
+ reqWritable: Writable<ProcRequest<Service, ProcName>>;
106
+ resReadable: Readable<ProcResponse<Service, ProcName>, ProcErrors<Service, ProcName>>;
107
+ };
108
+ type SubscriptionFn<Service extends AnyService, ProcName extends keyof Service['procedures']> = (reqInit: ProcInit<Service, ProcName>, options?: CallOptions) => {
109
+ resReadable: Readable<ProcResponse<Service, ProcName>, ProcErrors<Service, ProcName>>;
110
+ };
111
+ /**
112
+ * A helper type to transform an actual service type into a type
113
+ * we can case to in the proxy.
114
+ * @template Service - The type of the Service.
115
+ */
116
+ type ServiceClient<Service extends AnyService> = {
117
+ [ProcName in keyof Service['procedures']]: ProcType<Service, ProcName> extends 'rpc' ? {
118
+ rpc: RpcFn<Service, ProcName>;
119
+ } : ProcType<Service, ProcName> extends 'upload' ? {
120
+ upload: UploadFn<Service, ProcName>;
121
+ } : ProcType<Service, ProcName> extends 'stream' ? {
122
+ stream: StreamFn<Service, ProcName>;
123
+ } : ProcType<Service, ProcName> extends 'subscription' ? {
124
+ subscribe: SubscriptionFn<Service, ProcName>;
125
+ } : never;
126
+ };
127
+ /**
128
+ * Defines a type that represents a client for a server with a set of services.
129
+ * @template Srv - The type of the server.
130
+ */
131
+ type Client<Services extends AnyServiceSchemaMap, IS extends InstantiatedServiceSchemaMap<Services> = InstantiatedServiceSchemaMap<Services>> = {
132
+ [SvcName in keyof IS]: ServiceClient<IS[SvcName]>;
133
+ };
134
+ interface ClientOptions {
135
+ connectOnInvoke: boolean;
136
+ eagerlyConnect: boolean;
137
+ }
138
+ /**
139
+ * Creates a client for a given server using the provided transport.
140
+ * Note that the client only needs the type of the server, not the actual
141
+ * server definition itself.
142
+ *
143
+ * This relies on a proxy to dynamically create the client, so the client
144
+ * will be typed as if it were the actual server with the appropriate services
145
+ * and procedures.
146
+ *
147
+ * @template Srv - The type of the server.
148
+ * @param {Transport} transport - The transport to use for communication.
149
+ * @param {TransportClientId} serverId - The ID of the server to connect to.
150
+ * @param {Partial<ClientOptions>} providedClientOptions - The options for the client.
151
+ * @returns The client for the server.
152
+ */
153
+ declare function createClient<ServiceSchemaMap extends AnyServiceSchemaMap>(transport: ClientTransport<Connection>, serverId: TransportClientId, providedClientOptions?: Partial<ClientOptions & {
154
+ handshakeOptions: ClientHandshakeOptions;
155
+ }>): Client<ServiceSchemaMap>;
156
+
157
+ type TLiteralString = TLiteral<string>;
158
+ type BaseErrorSchemaType = TObject<{
159
+ code: TLiteralString | TUnion<Array<TLiteralString>>;
160
+ message: TLiteralString | TString;
161
+ }> | TObject<{
162
+ code: TLiteralString | TUnion<Array<TLiteralString>>;
163
+ message: TLiteralString | TString;
164
+ extras: TSchema;
165
+ }>;
166
+ interface OkResult<T> {
167
+ ok: true;
168
+ payload: T;
169
+ }
170
+ interface ErrResult<Err extends Static<BaseErrorSchemaType>> {
171
+ ok: false;
172
+ payload: Err;
173
+ }
174
+ type Result<T, Err extends Static<BaseErrorSchemaType>> = OkResult<T> | ErrResult<Err>;
175
+ declare function Ok<const T extends Array<unknown>>(p: T): OkResult<T>;
176
+ declare function Ok<const T extends ReadonlyArray<unknown>>(p: T): OkResult<T>;
177
+ declare function Ok<const T>(payload: T): OkResult<T>;
178
+ declare function Err<const Err extends Static<BaseErrorSchemaType>>(error: Err): ErrResult<Err>;
179
+ /**
180
+ * Refine a {@link Result} type to its returned payload.
181
+ */
182
+ type ResultUnwrapOk<R> = R extends Result<infer T, infer __E> ? T : never;
183
+ /**
184
+ * Unwrap a {@link Result} type and return the payload if successful,
185
+ * otherwise throws an error.
186
+ * @param result - The result to unwrap.
187
+ * @throws Will throw an error if the result is not ok.
188
+ */
189
+ declare function unwrapOrThrow<T, Err extends Static<BaseErrorSchemaType>>(result: Result<T, Err>): T;
190
+ /**
191
+ * Refine a {@link Result} type to its error payload.
192
+ */
193
+ type ResultUnwrapErr<R> = R extends Result<infer __T, infer Err> ? Err : never;
194
+ /**
195
+ * Retrieve the response type for a procedure, represented as a {@link Result}
196
+ * type.
197
+ * Example:
198
+ * ```
199
+ * type Message = ResponseData<typeof client, 'serviceName', 'procedureName'>
200
+ * ```
201
+ */
202
+ type ResponseData<RiverClient, ServiceName extends keyof RiverClient, ProcedureName extends keyof RiverClient[ServiceName], Procedure = RiverClient[ServiceName][ProcedureName], Fn extends (...args: never) => unknown = (...args: never) => unknown> = RiverClient extends Client<infer __ServiceSchemaMap> ? Procedure extends object ? Procedure extends object & {
203
+ rpc: infer RpcFn extends Fn;
204
+ } ? Awaited<ReturnType<RpcFn>> : Procedure extends object & {
205
+ upload: infer UploadFn extends Fn;
206
+ } ? ReturnType<UploadFn> extends {
207
+ finalize: (...args: never) => Promise<infer UploadOutputMessage>;
208
+ } ? UploadOutputMessage : never : Procedure extends object & {
209
+ stream: infer StreamFn extends Fn;
210
+ } ? ReturnType<StreamFn> extends {
211
+ resReadable: Readable<infer StreamOutputMessage, Static<BaseErrorSchemaType>>;
212
+ } ? StreamOutputMessage : never : Procedure extends object & {
213
+ subscribe: infer SubscriptionFn extends Fn;
214
+ } ? Awaited<ReturnType<SubscriptionFn>> extends {
215
+ resReadable: Readable<infer SubscriptionOutputMessage, Static<BaseErrorSchemaType>>;
216
+ } ? SubscriptionOutputMessage : never : never : never : never;
217
+
218
+ /**
219
+ * Brands a type to prevent it from being directly constructed.
220
+ */
221
+ type Branded<T> = T & {
222
+ readonly __BRAND_DO_NOT_USE: unique symbol;
223
+ };
224
+ /**
225
+ * Unbrands a {@link Branded} type.
226
+ */
227
+ type Unbranded<T> = T extends Branded<infer U> ? U : never;
228
+ /**
229
+ * The valid {@link Procedure} types. The `stream` and `upload` types can optionally have a
230
+ * different type for the very first initialization message. The suffixless types correspond to
231
+ * gRPC's four combinations of stream / non-stream in each direction.
232
+ */
233
+ type ValidProcType = 'rpc' | 'upload' | 'subscription' | 'stream';
234
+ /**
235
+ * Represents the payload type for {@link Procedure}s.
236
+ */
237
+ type PayloadType = TSchema;
238
+ /**
239
+ * {@link UNCAUGHT_ERROR_CODE} is the code that is used when an error is thrown
240
+ * inside a procedure handler that's not required.
241
+ */
242
+ declare const UNCAUGHT_ERROR_CODE: "UNCAUGHT_ERROR";
243
+ /**
244
+ * {@link UNEXPECTED_DISCONNECT_CODE} is the code used the stream's session
245
+ * disconnect unexpetedly.
246
+ */
247
+ declare const UNEXPECTED_DISCONNECT_CODE: "UNEXPECTED_DISCONNECT";
248
+ /**
249
+ * {@link INVALID_REQUEST_CODE} is the code used when a client's request is invalid.
250
+ */
251
+ declare const INVALID_REQUEST_CODE: "INVALID_REQUEST";
252
+ /**
253
+ * {@link CANCEL_CODE} is the code used when either server or client cancels the stream.
254
+ */
255
+ declare const CANCEL_CODE: "CANCEL";
256
+ /**
257
+ * {@link ReaderErrorSchema} is the schema for all the built-in river errors that
258
+ * can be emitted to a reader (request reader on the server, and response reader
259
+ * on the client).
260
+ */
261
+ declare const ReaderErrorSchema: _sinclair_typebox.TObject<{
262
+ code: TUnion<[_sinclair_typebox.TLiteral<"UNCAUGHT_ERROR">, _sinclair_typebox.TLiteral<"UNEXPECTED_DISCONNECT">, _sinclair_typebox.TLiteral<"INVALID_REQUEST">, _sinclair_typebox.TLiteral<"CANCEL">]>;
263
+ message: _sinclair_typebox.TString;
264
+ }>;
265
+ type ProcedureErrorUnionSchema0 = TUnion<Array<BaseErrorSchemaType>>;
266
+ type ProcedureErrorUnionSchema1 = TUnion<Array<ProcedureErrorUnionSchema0 | BaseErrorSchemaType>>;
267
+ type ProcedureErrorUnionSchema2 = TUnion<Array<ProcedureErrorUnionSchema1 | ProcedureErrorUnionSchema0 | BaseErrorSchemaType>>;
268
+ /**
269
+ * Represents an acceptable schema to pass to a procedure.
270
+ * Just a type of a schema, not an actual schema.
271
+ */
272
+ type ProcedureErrorSchemaType = ProcedureErrorUnionSchema2 | BaseErrorSchemaType | TNever;
273
+ /**
274
+ * Procedure for a single message in both directions (1:1).
275
+ *
276
+ * @template State - The context state object.
277
+ * @template RequestInit - The TypeBox schema of the initialization object.
278
+ * @template ResponseData - The TypeBox schema of the response object.
279
+ * @template ResponseErr - The TypeBox schema of the error object.
280
+ */
281
+ interface RpcProcedure<State, RequestInit extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> {
282
+ type: 'rpc';
283
+ requestInit: RequestInit;
284
+ responseData: ResponseData;
285
+ responseError: ResponseErr;
286
+ description?: string;
287
+ handler(param: {
288
+ ctx: ProcedureHandlerContext<State>;
289
+ reqInit: Static<RequestInit>;
290
+ }): Promise<Result<Static<ResponseData>, Static<ResponseErr>>>;
291
+ }
292
+ /**
293
+ * Procedure for a client-stream (potentially preceded by an initialization message),
294
+ * single message from server (n:1).
295
+ *
296
+ * @template State - The context state object.
297
+ * @template RequestInit - The TypeBox schema of the initialization object.
298
+ * @template RequestData - The TypeBox schema of the request object.
299
+ * @template ResponseData - The TypeBox schema of the response object.
300
+ * @template ResponseErr - The TypeBox schema of the error object.
301
+ */
302
+ interface UploadProcedure<State, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> {
303
+ type: 'upload';
304
+ requestInit: RequestInit;
305
+ requestData: RequestData;
306
+ responseData: ResponseData;
307
+ responseError: ResponseErr;
308
+ description?: string;
309
+ handler(param: {
310
+ ctx: ProcedureHandlerContext<State>;
311
+ reqInit: Static<RequestInit>;
312
+ reqReadable: Readable<Static<RequestData>, Static<typeof ReaderErrorSchema>>;
313
+ }): Promise<Result<Static<ResponseData>, Static<ResponseErr>>>;
314
+ }
315
+ /**
316
+ * Procedure for a single message from client, stream from server (1:n).
317
+ *
318
+ * @template State - The context state object.
319
+ * @template RequestInit - The TypeBox schema of the initialization object.
320
+ * @template ResponseData - The TypeBox schema of the response object.
321
+ * @template ResponseErr - The TypeBox schema of the error object.
322
+ */
323
+ interface SubscriptionProcedure<State, RequestInit extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> {
324
+ type: 'subscription';
325
+ requestInit: RequestInit;
326
+ responseData: ResponseData;
327
+ responseError: ResponseErr;
328
+ description?: string;
329
+ handler(param: {
330
+ ctx: ProcedureHandlerContext<State>;
331
+ reqInit: Static<RequestInit>;
332
+ resWritable: Writable<Result<Static<ResponseData>, Static<ResponseErr>>>;
333
+ }): Promise<void | undefined>;
334
+ }
335
+ /**
336
+ * Procedure for a bidirectional stream (potentially preceded by an initialization message),
337
+ * (n:n).
338
+ *
339
+ * @template State - The context state object.
340
+ * @template RequestInit - The TypeBox schema of the initialization object.
341
+ * @template RequestData - The TypeBox schema of the request object.
342
+ * @template ResponseData - The TypeBox schema of the response object.
343
+ * @template ResponseErr - The TypeBox schema of the error object.
344
+ */
345
+ interface StreamProcedure<State, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> {
346
+ type: 'stream';
347
+ requestInit: RequestInit;
348
+ requestData: RequestData;
349
+ responseData: ResponseData;
350
+ responseError: ResponseErr;
351
+ description?: string;
352
+ handler(param: {
353
+ ctx: ProcedureHandlerContext<State>;
354
+ reqInit: Static<RequestInit>;
355
+ reqReadable: Readable<Static<RequestData>, Static<typeof ReaderErrorSchema>>;
356
+ resWritable: Writable<Result<Static<ResponseData>, Static<ResponseErr>>>;
357
+ }): Promise<void | undefined>;
358
+ }
359
+ /**
360
+ * Represents any {@link Procedure} type.
361
+ *
362
+ * @template State - The context state object. You can provide this to constrain
363
+ * the type of procedures.
364
+ */
365
+ type AnyProcedure<State = object> = Procedure<State, ValidProcType, PayloadType, PayloadType | null, PayloadType, ProcedureErrorSchemaType>;
366
+ /**
367
+ * Represents a map of {@link Procedure}s.
368
+ *
369
+ * @template State - The context state object. You can provide this to constrain
370
+ * the type of procedures.
371
+ */
372
+ type ProcedureMap<State = object> = Record<string, AnyProcedure<State>>;
373
+ /**
374
+ * Creates an {@link RpcProcedure}.
375
+ */
376
+ declare function rpc<State, RequestInit extends PayloadType, ResponseData extends PayloadType>(def: {
377
+ requestInit: RequestInit;
378
+ responseData: ResponseData;
379
+ responseError?: never;
380
+ description?: string;
381
+ handler: RpcProcedure<State, RequestInit, ResponseData, TNever>['handler'];
382
+ }): Branded<RpcProcedure<State, RequestInit, ResponseData, TNever>>;
383
+ declare function rpc<State, RequestInit extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType>(def: {
384
+ requestInit: RequestInit;
385
+ responseData: ResponseData;
386
+ responseError: ResponseErr;
387
+ description?: string;
388
+ handler: RpcProcedure<State, RequestInit, ResponseData, ResponseErr>['handler'];
389
+ }): Branded<RpcProcedure<State, RequestInit, ResponseData, ResponseErr>>;
390
+ /**
391
+ * Creates an {@link UploadProcedure}, optionally with an initialization message.
392
+ */
393
+ declare function upload<State, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType>(def: {
394
+ requestInit: RequestInit;
395
+ requestData: RequestData;
396
+ responseData: ResponseData;
397
+ responseError?: never;
398
+ description?: string;
399
+ handler: UploadProcedure<State, RequestInit, RequestData, ResponseData, TNever>['handler'];
400
+ }): Branded<UploadProcedure<State, RequestInit, RequestData, ResponseData, TNever>>;
401
+ declare function upload<State, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType>(def: {
402
+ requestInit: RequestInit;
403
+ requestData: RequestData;
404
+ responseData: ResponseData;
405
+ responseError: ResponseErr;
406
+ description?: string;
407
+ handler: UploadProcedure<State, RequestInit, RequestData, ResponseData, ResponseErr>['handler'];
408
+ }): Branded<UploadProcedure<State, RequestInit, RequestData, ResponseData, ResponseErr>>;
409
+ /**
410
+ * Creates a {@link SubscriptionProcedure}.
411
+ */
412
+ declare function subscription<State, RequestInit extends PayloadType, ResponseData extends PayloadType>(def: {
413
+ requestInit: RequestInit;
414
+ responseData: ResponseData;
415
+ responseError?: never;
416
+ description?: string;
417
+ handler: SubscriptionProcedure<State, RequestInit, ResponseData, TNever>['handler'];
418
+ }): Branded<SubscriptionProcedure<State, RequestInit, ResponseData, TNever>>;
419
+ declare function subscription<State, RequestInit extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType>(def: {
420
+ requestInit: RequestInit;
421
+ responseData: ResponseData;
422
+ responseError: ResponseErr;
423
+ description?: string;
424
+ handler: SubscriptionProcedure<State, RequestInit, ResponseData, ResponseErr>['handler'];
425
+ }): Branded<SubscriptionProcedure<State, RequestInit, ResponseData, ResponseErr>>;
426
+ /**
427
+ * Creates a {@link StreamProcedure}, optionally with an initialization message.
428
+ */
429
+ declare function stream<State, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType>(def: {
430
+ requestInit: RequestInit;
431
+ requestData: RequestData;
432
+ responseData: ResponseData;
433
+ responseError?: never;
434
+ description?: string;
435
+ handler: StreamProcedure<State, RequestInit, RequestData, ResponseData, TNever>['handler'];
436
+ }): Branded<StreamProcedure<State, RequestInit, RequestData, ResponseData, TNever>>;
437
+ declare function stream<State, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType>(def: {
438
+ requestInit: RequestInit;
439
+ requestData: RequestData;
440
+ responseData: ResponseData;
441
+ responseError: ResponseErr;
442
+ description?: string;
443
+ handler: StreamProcedure<State, RequestInit, RequestData, ResponseData, ResponseErr>['handler'];
444
+ }): Branded<StreamProcedure<State, RequestInit, RequestData, ResponseData, ResponseErr>>;
445
+ /**
446
+ * Defines a Procedure type that can be a:
447
+ * - {@link RpcProcedure} for a single message in both directions (1:1)
448
+ * - {@link UploadProcedure} for a client-stream (potentially preceded by an
449
+ * initialization message)
450
+ * - {@link SubscriptionProcedure} for a single message from client, stream from server (1:n)
451
+ * - {@link StreamProcedure} for a bidirectional stream (potentially preceded by an
452
+ * initialization message)
453
+ *
454
+ * @template State - The TypeBox schema of the state object.
455
+ * @template Ty - The type of the procedure.
456
+ * @template RequestData - The TypeBox schema of the request object.
457
+ * @template RequestInit - The TypeBox schema of the request initialization object, if any.
458
+ * @template ResponseData - The TypeBox schema of the response object.
459
+ */
460
+ type Procedure<State, Ty extends ValidProcType, RequestInit extends PayloadType, RequestData extends PayloadType | null, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> = {
461
+ type: Ty;
462
+ } & (RequestData extends PayloadType ? Ty extends 'upload' ? UploadProcedure<State, RequestInit, RequestData, ResponseData, ResponseErr> : Ty extends 'stream' ? StreamProcedure<State, RequestInit, RequestData, ResponseData, ResponseErr> : never : Ty extends 'rpc' ? RpcProcedure<State, RequestInit, ResponseData, ResponseErr> : Ty extends 'subscription' ? SubscriptionProcedure<State, RequestInit, ResponseData, ResponseErr> : never);
463
+ /**
464
+ * Holds the {@link Procedure} creation functions. Use these to create
465
+ * procedures for services. You aren't allowed to create procedures directly.
466
+ */
467
+ declare const Procedure: {
468
+ rpc: typeof rpc;
469
+ upload: typeof upload;
470
+ subscription: typeof subscription;
471
+ stream: typeof stream;
472
+ };
473
+
474
+ /**
475
+ * An instantiated service, probably from a {@link ServiceSchema}.
476
+ *
477
+ * You shouldn't construct these directly, use {@link ServiceSchema} instead.
478
+ */
479
+ interface Service<State extends object, Procs extends ProcedureMap<State>> {
480
+ readonly state: State;
481
+ readonly procedures: Procs;
482
+ }
483
+ /**
484
+ * Represents any {@link Service} object.
485
+ */
486
+ type AnyService = Service<object, ProcedureMap>;
487
+ /**
488
+ * Represents any {@link ServiceSchema} object.
489
+ */
490
+ type AnyServiceSchema = ServiceSchema<object, ProcedureMap>;
491
+ /**
492
+ * A dictionary of {@link ServiceSchema}s, where the key is the service name.
493
+ */
494
+ type AnyServiceSchemaMap = Record<string, AnyServiceSchema>;
495
+ /**
496
+ * Takes a {@link AnyServiceSchemaMap} and returns a dictionary of instantiated
497
+ * services.
498
+ */
499
+ type InstantiatedServiceSchemaMap<T extends AnyServiceSchemaMap> = {
500
+ [K in keyof T]: T[K] extends ServiceSchema<infer S, infer P> ? Service<S, P> : never;
501
+ };
502
+ /**
503
+ * Helper to get the type definition for a specific handler of a procedure in a service.
504
+ * @template S - The service.
505
+ * @template ProcName - The name of the procedure.
506
+ */
507
+ type ProcHandler<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName]['handler'];
508
+ /**
509
+ * Helper to get the type definition for the procedure init type of a service.
510
+ * @template S - The service.
511
+ * @template ProcName - The name of the procedure.
512
+ */
513
+ type ProcInit<S extends AnyService, ProcName extends keyof S['procedures']> = Static<S['procedures'][ProcName]['requestInit']>;
514
+ /**
515
+ * Helper to get the type definition for the procedure request of a service.
516
+ * @template S - The service.
517
+ * @template ProcName - The name of the procedure.
518
+ */
519
+ type ProcRequest<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName] extends {
520
+ requestData: PayloadType;
521
+ } ? Static<S['procedures'][ProcName]['requestData']> : never;
522
+ /**
523
+ * Helper to get the type definition for the procedure response of a service.
524
+ * @template S - The service.
525
+ * @template ProcName - The name of the procedure.
526
+ */
527
+ type ProcResponse<S extends AnyService, ProcName extends keyof S['procedures']> = Static<S['procedures'][ProcName]['responseData']>;
528
+ /**
529
+ * Helper to get the type definition for the procedure errors of a service.
530
+ * @template S - The service.
531
+ * @template ProcName - The name of the procedure.
532
+ */
533
+ type ProcErrors<S extends AnyService, ProcName extends keyof S['procedures']> = Static<S['procedures'][ProcName]['responseError']> | Static<typeof ReaderErrorSchema>;
534
+ /**
535
+ * Helper to get the type of procedure in a service.
536
+ * @template S - The service.
537
+ * @template ProcName - The name of the procedure.
538
+ */
539
+ type ProcType<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName]['type'];
540
+ /**
541
+ * A list of procedures where every procedure is "branded", as-in the procedure
542
+ * was created via the {@link Procedure} constructors.
543
+ */
544
+ type BrandedProcedureMap<State> = Record<string, Branded<AnyProcedure<State>>>;
545
+ /**
546
+ * The configuration for a service.
547
+ */
548
+ interface ServiceConfiguration<State extends object> {
549
+ /**
550
+ * A factory function for creating a fresh state.
551
+ */
552
+ initializeState: (extendedContext: ServiceContext) => State;
553
+ }
554
+ interface SerializedProcedureSchemaProtocolv1 {
555
+ init?: PayloadType;
556
+ input: PayloadType;
557
+ output: PayloadType;
558
+ errors?: ProcedureErrorSchemaType;
559
+ type: 'rpc' | 'subscription' | 'upload' | 'stream';
560
+ }
561
+ interface SerializedServiceSchemaProtocolv1 {
562
+ procedures: Record<string, SerializedProcedureSchemaProtocolv1>;
563
+ }
564
+ interface SerializedServerSchemaProtocolv1 {
565
+ handshakeSchema?: TSchema;
566
+ services: Record<string, SerializedServiceSchemaProtocolv1>;
567
+ }
568
+ /**
569
+ * Same as {@link serializeSchema} but with a format that is compatible with
570
+ * protocolv1. This is useful to be able to continue to generate schemas for older
571
+ * clients as they are still supported.
572
+ */
573
+ declare function serializeSchemaV1Compat(services: AnyServiceSchemaMap, handshakeSchema?: TSchema): SerializedServerSchemaProtocolv1;
574
+ interface SerializedProcedureSchema {
575
+ init: PayloadType;
576
+ input?: PayloadType;
577
+ output: PayloadType;
578
+ errors?: ProcedureErrorSchemaType;
579
+ type: 'rpc' | 'subscription' | 'upload' | 'stream';
580
+ }
581
+ interface SerializedServiceSchema {
582
+ procedures: Record<string, SerializedProcedureSchema>;
583
+ }
584
+ interface SerializedServerSchema {
585
+ handshakeSchema?: TSchema;
586
+ services: Record<string, SerializedServiceSchema>;
587
+ }
588
+ /**
589
+ * Serializes a server schema into a plain object that is JSON compatible.
590
+ */
591
+ declare function serializeSchema(services: AnyServiceSchemaMap, handshakeSchema?: TSchema): SerializedServerSchema;
592
+ /**
593
+ * The schema for a {@link Service}. This is used to define a service, specifically
594
+ * its initial state and procedures.
595
+ *
596
+ * There are two ways to define a service:
597
+ * 1. the {@link ServiceSchema.define} static method, which takes a configuration and
598
+ * a list of procedures directly. Use this to ergonomically define a service schema
599
+ * in one go. Good for smaller services, especially if they're stateless.
600
+ * 2. the {@link ServiceSchema.scaffold} static method, which creates a scaffold that
601
+ * can be used to define procedures separately from the configuration. Use this to
602
+ * better organize your service's definition, especially if it's a large service.
603
+ * You can also use it in a builder pattern to define the service in a more
604
+ * fluent way.
605
+ *
606
+ * See the static methods for more information and examples.
607
+ *
608
+ * When defining procedures, use the {@link Procedure} constructors to create them.
609
+ */
610
+ declare class ServiceSchema<State extends object, Procedures extends ProcedureMap<State>> {
611
+ /**
612
+ * Factory function for creating a fresh state.
613
+ */
614
+ protected readonly initializeState: (extendedContext: ServiceContext) => State;
615
+ /**
616
+ * The procedures for this service.
617
+ */
618
+ readonly procedures: Procedures;
619
+ /**
620
+ * @param config - The configuration for this service.
621
+ * @param procedures - The procedures for this service.
622
+ */
623
+ protected constructor(config: ServiceConfiguration<State>, procedures: Procedures);
624
+ /**
625
+ * Creates a {@link ServiceScaffold}, which can be used to define procedures
626
+ * that can then be merged into a {@link ServiceSchema}, via the scaffold's
627
+ * `finalize` method.
628
+ *
629
+ * There are two patterns that work well with this method. The first is using
630
+ * it to separate the definition of procedures from the definition of the
631
+ * service's configuration:
632
+ * ```ts
633
+ * const MyServiceScaffold = ServiceSchema.scaffold({
634
+ * initializeState: () => ({ count: 0 }),
635
+ * });
636
+ *
637
+ * const incrementProcedures = MyServiceScaffold.procedures({
638
+ * increment: Procedure.rpc({
639
+ * requestInit: Type.Object({ amount: Type.Number() }),
640
+ * responseData: Type.Object({ current: Type.Number() }),
641
+ * async handler(ctx, init) {
642
+ * ctx.state.count += init.amount;
643
+ * return Ok({ current: ctx.state.count });
644
+ * }
645
+ * }),
646
+ * })
647
+ *
648
+ * const MyService = MyServiceScaffold.finalize({
649
+ * ...incrementProcedures,
650
+ * // you can also directly define procedures here
651
+ * });
652
+ * ```
653
+ * This might be really handy if you have a very large service and you're
654
+ * wanting to split it over multiple files. You can define the scaffold
655
+ * in one file, and then import that scaffold in other files where you
656
+ * define procedures - and then finally import the scaffolds and your
657
+ * procedure objects in a final file where you finalize the scaffold into
658
+ * a service schema.
659
+ *
660
+ * The other way is to use it like in a builder pattern:
661
+ * ```ts
662
+ * const MyService = ServiceSchema
663
+ * .scaffold({ initializeState: () => ({ count: 0 }) })
664
+ * .finalize({
665
+ * increment: Procedure.rpc({
666
+ * requestInit: Type.Object({ amount: Type.Number() }),
667
+ * responseData: Type.Object({ current: Type.Number() }),
668
+ * async handler(ctx, init) {
669
+ * ctx.state.count += init.amount;
670
+ * return Ok({ current: ctx.state.count });
671
+ * }
672
+ * }),
673
+ * })
674
+ * ```
675
+ * Depending on your preferences, this may be a more appealing way to define
676
+ * a schema versus using the {@link ServiceSchema.define} method.
677
+ */
678
+ static scaffold<State extends object>(config: ServiceConfiguration<State>): ServiceScaffold<State>;
679
+ /**
680
+ * Creates a new {@link ServiceSchema} with the given configuration and procedures.
681
+ *
682
+ * All procedures must be created with the {@link Procedure} constructors.
683
+ *
684
+ * NOTE: There is an overload that lets you just provide the procedures alone if your
685
+ * service has no state.
686
+ *
687
+ * @param config - The configuration for this service.
688
+ * @param procedures - The procedures for this service.
689
+ *
690
+ * @example
691
+ * ```
692
+ * const service = ServiceSchema.define(
693
+ * { initializeState: () => ({ count: 0 }) },
694
+ * {
695
+ * increment: Procedure.rpc({
696
+ * requestInit: Type.Object({ amount: Type.Number() }),
697
+ * responseData: Type.Object({ current: Type.Number() }),
698
+ * async handler(ctx, init) {
699
+ * ctx.state.count += init.amount;
700
+ * return Ok({ current: ctx.state.count });
701
+ * }
702
+ * }),
703
+ * },
704
+ * );
705
+ * ```
706
+ */
707
+ static define<State extends object, Procedures extends BrandedProcedureMap<State>>(config: ServiceConfiguration<State>, procedures: Procedures): ServiceSchema<State, {
708
+ [K in keyof Procedures]: Unbranded<Procedures[K]>;
709
+ }>;
710
+ /**
711
+ * Creates a new {@link ServiceSchema} with the given procedures.
712
+ *
713
+ * All procedures must be created with the {@link Procedure} constructors.
714
+ *
715
+ * NOTE: There is an overload that lets you provide configuration as well,
716
+ * if your service has extra configuration like a state.
717
+ *
718
+ * @param procedures - The procedures for this service.
719
+ *
720
+ * @example
721
+ * ```
722
+ * const service = ServiceSchema.define({
723
+ * add: Procedure.rpc({
724
+ * requestInit: Type.Object({ a: Type.Number(), b: Type.Number() }),
725
+ * responseData: Type.Object({ result: Type.Number() }),
726
+ * async handler(ctx, init) {
727
+ * return Ok({ result: init.a + init.b });
728
+ * }
729
+ * }),
730
+ * });
731
+ */
732
+ static define<Procedures extends BrandedProcedureMap<Record<string, never>>>(procedures: Procedures): ServiceSchema<Record<string, never>, {
733
+ [K in keyof Procedures]: Unbranded<Procedures[K]>;
734
+ }>;
735
+ /**
736
+ * Serializes this schema's procedures into a plain object that is JSON compatible.
737
+ */
738
+ serialize(): SerializedServiceSchema;
739
+ /**
740
+ * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with
741
+ * protocol v1. This is useful to be able to continue to generate schemas for older
742
+ * clients as they are still supported.
743
+ */
744
+ serializeV1Compat(): SerializedServiceSchemaProtocolv1;
745
+ /**
746
+ * Instantiates this schema into a {@link Service} object.
747
+ *
748
+ * You probably don't need this, usually the River server will handle this
749
+ * for you.
750
+ */
751
+ instantiate(extendedContext: ServiceContext): Service<State, Procedures>;
752
+ }
753
+ /**
754
+ * A scaffold for defining a service's procedures.
755
+ *
756
+ * @see {@link ServiceSchema.scaffold}
757
+ */
758
+ declare class ServiceScaffold<State extends object> {
759
+ /**
760
+ * The configuration for this service.
761
+ */
762
+ protected readonly config: ServiceConfiguration<State>;
763
+ /**
764
+ * @param config - The configuration for this service.
765
+ */
766
+ constructor(config: ServiceConfiguration<State>);
767
+ /**
768
+ * Define procedures for this service. Use the {@link Procedure} constructors
769
+ * to create them. This returns the procedures object, which can then be
770
+ * passed to {@link ServiceSchema.finalize} to create a {@link ServiceSchema}.
771
+ *
772
+ * @example
773
+ * ```
774
+ * const myProcedures = MyServiceScaffold.procedures({
775
+ * myRPC: Procedure.rpc({
776
+ * // ...
777
+ * }),
778
+ * });
779
+ *
780
+ * const MyService = MyServiceScaffold.finalize({
781
+ * ...myProcedures,
782
+ * });
783
+ * ```
784
+ *
785
+ * @param procedures - The procedures for this service.
786
+ */
787
+ procedures<T extends BrandedProcedureMap<State>>(procedures: T): T;
788
+ /**
789
+ * Finalizes the scaffold into a {@link ServiceSchema}. This is where you
790
+ * provide the service's procedures and get a {@link ServiceSchema} in return.
791
+ *
792
+ * You can directly define procedures here, or you can define them separately
793
+ * with the {@link ServiceScaffold.procedures} method, and then pass them here.
794
+ *
795
+ * @example
796
+ * ```
797
+ * const MyService = MyServiceScaffold.finalize({
798
+ * myRPC: Procedure.rpc({
799
+ * // ...
800
+ * }),
801
+ * // e.g. from the procedures method
802
+ * ...myOtherProcedures,
803
+ * });
804
+ * ```
805
+ */
806
+ finalize<T extends BrandedProcedureMap<State>>(procedures: T): ServiceSchema<State, {
807
+ [K in keyof T]: Unbranded<T[K]>;
808
+ }>;
809
+ }
810
+
811
+ export { AnyServiceSchemaMap as A, BaseErrorSchemaType as B, UNCAUGHT_ERROR_CODE as C, UNEXPECTED_DISCONNECT_CODE as D, INVALID_REQUEST_CODE as E, CANCEL_CODE as F, createClient as G, Client as H, InstantiatedServiceSchemaMap as I, Err as J, unwrapOrThrow as K, ErrResult as L, OkResult as M, ResultUnwrapOk as N, Ok as O, PayloadType as P, ResultUnwrapErr as Q, Readable as R, Service as S, ResponseData as T, UploadProcedure as U, ValidProcType as V, Writable as W, ReadableIterator as a, ReadableResult as b, ProcedureErrorSchemaType as c, Procedure as d, Result as e, ReaderErrorSchema as f, ServiceConfiguration as g, ProcHandler as h, ProcInit as i, ProcRequest as j, ProcResponse as k, ProcErrors as l, ProcType as m, ServiceSchema as n, SerializedServerSchema as o, SerializedServiceSchema as p, SerializedProcedureSchema as q, serializeSchemaV1Compat as r, serializeSchema as s, SerializedServerSchemaProtocolv1 as t, SerializedServiceSchemaProtocolv1 as u, SerializedProcedureSchemaProtocolv1 as v, ProcedureMap as w, RpcProcedure as x, SubscriptionProcedure as y, StreamProcedure as z };