@replit/river 0.216.1 → 0.217.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.
Files changed (76) hide show
  1. package/README.md +2 -2
  2. package/dist/{adapter-BXCk-dmy.d.ts → adapter-Dl5Mewp3.d.ts} +1 -1
  3. package/dist/{chunk-C4EPHIKQ.js → chunk-JFFRB3SS.js} +48 -26
  4. package/dist/chunk-JFFRB3SS.js.map +1 -0
  5. package/dist/{chunk-62BM2WOT.js → chunk-VK3VJZGG.js} +19 -18
  6. package/dist/chunk-VK3VJZGG.js.map +1 -0
  7. package/dist/chunk-WMPWPIA4.js +72 -0
  8. package/dist/chunk-WMPWPIA4.js.map +1 -0
  9. package/dist/{client-BNc5Pj_4.d.ts → client-YP9bECp8.d.ts} +2 -2
  10. package/dist/codec/index.d.ts +3 -3
  11. package/dist/codec/index.js +2 -2
  12. package/dist/{connection-ou9w2dSY.d.ts → connection-D_HE_YQB.d.ts} +3 -3
  13. package/dist/customSchemas/index.d.ts +34 -0
  14. package/dist/customSchemas/index.js +9 -0
  15. package/dist/customSchemas/index.js.map +1 -0
  16. package/dist/{index-ZWkoesQD.d.ts → index-DgUMnNOi.d.ts} +1 -1
  17. package/dist/logging/index.d.ts +3 -3
  18. package/dist/{message-CpXWqmJw.d.ts → message-DxS8db8A.d.ts} +30 -31
  19. package/dist/protobuf/index.d.ts +11 -15
  20. package/dist/protobuf/index.js +7 -5
  21. package/dist/protobuf/index.js.map +1 -1
  22. package/dist/router/index.d.ts +11 -11
  23. package/dist/router/index.js +1 -1
  24. package/dist/{server-BPu7Td80.d.ts → server-BfM3_JLq.d.ts} +5 -5
  25. package/dist/{services-DpT2yNtt.d.ts → services-CL6k3HMH.d.ts} +8 -9
  26. package/dist/testUtil/index.d.ts +8 -8
  27. package/dist/testUtil/index.js +2 -2
  28. package/dist/testUtil/index.js.map +1 -1
  29. package/dist/transport/impls/ws/client.d.ts +7 -7
  30. package/dist/transport/impls/ws/client.js +2 -2
  31. package/dist/transport/impls/ws/server.d.ts +7 -7
  32. package/dist/transport/impls/ws/server.js +2 -2
  33. package/dist/transport/impls/ws/server.js.map +1 -1
  34. package/dist/transport/index.d.ts +8 -8
  35. package/dist/transport/index.js +2 -2
  36. package/dist/{transport-B1MUtXL7.d.ts → transport-CUpXnch7.d.ts} +4 -4
  37. package/package.json +14 -39
  38. package/dist/adapter-D5X11kmP.d.cts +0 -29
  39. package/dist/chunk-62BM2WOT.js.map +0 -1
  40. package/dist/chunk-C4EPHIKQ.js.map +0 -1
  41. package/dist/client-BZUvFL6B.d.cts +0 -54
  42. package/dist/codec/index.cjs +0 -268
  43. package/dist/codec/index.cjs.map +0 -1
  44. package/dist/codec/index.d.cts +0 -19
  45. package/dist/connection-xxgJHs2o.d.cts +0 -40
  46. package/dist/index-BAGGleT3.d.cts +0 -37
  47. package/dist/logging/index.cjs +0 -55
  48. package/dist/logging/index.cjs.map +0 -1
  49. package/dist/logging/index.d.cts +0 -4
  50. package/dist/message-CpXWqmJw.d.cts +0 -119
  51. package/dist/protobuf/codec.cjs +0 -107
  52. package/dist/protobuf/codec.cjs.map +0 -1
  53. package/dist/protobuf/codec.d.cts +0 -13
  54. package/dist/protobuf/index.cjs +0 -1877
  55. package/dist/protobuf/index.cjs.map +0 -1
  56. package/dist/protobuf/index.d.cts +0 -488
  57. package/dist/router/index.cjs +0 -2043
  58. package/dist/router/index.cjs.map +0 -1
  59. package/dist/router/index.d.cts +0 -80
  60. package/dist/server-JdnoVO11.d.cts +0 -72
  61. package/dist/services-CjigASqe.d.cts +0 -1135
  62. package/dist/testUtil/index.cjs +0 -3051
  63. package/dist/testUtil/index.cjs.map +0 -1
  64. package/dist/testUtil/index.d.cts +0 -122
  65. package/dist/transport/impls/ws/client.cjs +0 -2308
  66. package/dist/transport/impls/ws/client.cjs.map +0 -1
  67. package/dist/transport/impls/ws/client.d.cts +0 -33
  68. package/dist/transport/impls/ws/server.cjs +0 -2179
  69. package/dist/transport/impls/ws/server.cjs.map +0 -1
  70. package/dist/transport/impls/ws/server.d.cts +0 -21
  71. package/dist/transport/index.cjs +0 -2727
  72. package/dist/transport/index.cjs.map +0 -1
  73. package/dist/transport/index.d.cts +0 -11
  74. package/dist/transport-BnU3Zb0Q.d.cts +0 -590
  75. package/dist/types-BGGvYIJM.d.cts +0 -20
  76. package/dist/wslike-Dng9H1C7.d.cts +0 -40
@@ -1,2043 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // router/index.ts
21
- var router_exports = {};
22
- __export(router_exports, {
23
- CANCEL_CODE: () => CANCEL_CODE,
24
- Err: () => Err,
25
- INVALID_REQUEST_CODE: () => INVALID_REQUEST_CODE,
26
- Ok: () => Ok,
27
- Procedure: () => Procedure,
28
- RIVER_VERSION: () => version,
29
- RawReadable: () => ReadableImpl,
30
- ReadableBrokenError: () => ReadableBrokenError,
31
- ReaderErrorSchema: () => ReaderErrorSchema,
32
- UNCAUGHT_ERROR_CODE: () => UNCAUGHT_ERROR_CODE,
33
- UNEXPECTED_DISCONNECT_CODE: () => UNEXPECTED_DISCONNECT_CODE,
34
- createClient: () => createClient,
35
- createClientHandshakeOptions: () => createClientHandshakeOptions,
36
- createServer: () => createServer,
37
- createServerHandshakeOptions: () => createServerHandshakeOptions,
38
- createServiceSchema: () => createServiceSchema,
39
- flattenErrorType: () => flattenErrorType,
40
- serializeSchema: () => serializeSchema,
41
- serializeSchemaV1Compat: () => serializeSchemaV1Compat
42
- });
43
- module.exports = __toCommonJS(router_exports);
44
-
45
- // router/services.ts
46
- var import_typebox2 = require("@sinclair/typebox");
47
-
48
- // router/errors.ts
49
- var import_typebox = require("@sinclair/typebox");
50
- var UNCAUGHT_ERROR_CODE = "UNCAUGHT_ERROR";
51
- var UNEXPECTED_DISCONNECT_CODE = "UNEXPECTED_DISCONNECT";
52
- var INVALID_REQUEST_CODE = "INVALID_REQUEST";
53
- var CANCEL_CODE = "CANCEL";
54
- var ErrResultSchema = (t) => import_typebox.Type.Object({
55
- ok: import_typebox.Type.Literal(false),
56
- payload: t
57
- });
58
- var ValidationErrorDetails = import_typebox.Type.Object({
59
- path: import_typebox.Type.String(),
60
- message: import_typebox.Type.String()
61
- });
62
- var ValidationErrors = import_typebox.Type.Array(ValidationErrorDetails);
63
- function castTypeboxValueErrors(errors) {
64
- const result = [];
65
- for (const error of errors) {
66
- result.push({
67
- path: error.path,
68
- message: error.message
69
- });
70
- }
71
- return result;
72
- }
73
- var CancelErrorSchema = import_typebox.Type.Object({
74
- code: import_typebox.Type.Literal(CANCEL_CODE),
75
- message: import_typebox.Type.String()
76
- });
77
- var CancelResultSchema = ErrResultSchema(CancelErrorSchema);
78
- var ReaderErrorSchema = import_typebox.Type.Union([
79
- import_typebox.Type.Object({
80
- code: import_typebox.Type.Literal(UNCAUGHT_ERROR_CODE),
81
- message: import_typebox.Type.String()
82
- }),
83
- import_typebox.Type.Object({
84
- code: import_typebox.Type.Literal(UNEXPECTED_DISCONNECT_CODE),
85
- message: import_typebox.Type.String()
86
- }),
87
- import_typebox.Type.Object({
88
- code: import_typebox.Type.Literal(INVALID_REQUEST_CODE),
89
- message: import_typebox.Type.String(),
90
- extras: import_typebox.Type.Optional(
91
- import_typebox.Type.Object({
92
- firstValidationErrors: import_typebox.Type.Array(ValidationErrorDetails),
93
- totalErrors: import_typebox.Type.Number()
94
- })
95
- )
96
- }),
97
- CancelErrorSchema
98
- ]);
99
- var ReaderErrorResultSchema = ErrResultSchema(ReaderErrorSchema);
100
- function isUnion(schema) {
101
- return schema[import_typebox.Kind] === "Union";
102
- }
103
- function flattenErrorType(errType) {
104
- if (!isUnion(errType)) {
105
- return errType;
106
- }
107
- const flattenedTypes = [];
108
- function flatten(type) {
109
- if (isUnion(type)) {
110
- for (const t of type.anyOf) {
111
- flatten(t);
112
- }
113
- } else {
114
- flattenedTypes.push(type);
115
- }
116
- }
117
- flatten(errType);
118
- return import_typebox.Type.Union(flattenedTypes);
119
- }
120
-
121
- // router/services.ts
122
- function Strict(schema) {
123
- return JSON.parse(JSON.stringify(schema));
124
- }
125
- function serializeSchemaV1Compat(services, handshakeSchema) {
126
- const serializedServiceObject = Object.entries(services).reduce((acc, [name, value]) => {
127
- acc[name] = value.serializeV1Compat();
128
- return acc;
129
- }, {});
130
- const schema = {
131
- services: serializedServiceObject
132
- };
133
- if (handshakeSchema) {
134
- schema.handshakeSchema = Strict(handshakeSchema);
135
- }
136
- return schema;
137
- }
138
- function serializeSchema(services, handshakeSchema) {
139
- const serializedServiceObject = Object.entries(services).reduce((acc, [name, value]) => {
140
- acc[name] = value.serialize();
141
- return acc;
142
- }, {});
143
- const schema = {
144
- services: serializedServiceObject
145
- };
146
- if (handshakeSchema) {
147
- schema.handshakeSchema = Strict(handshakeSchema);
148
- }
149
- return schema;
150
- }
151
- function createServiceSchema() {
152
- return class ServiceSchema {
153
- /**
154
- * Factory function for creating a fresh state.
155
- */
156
- initializeState;
157
- /**
158
- * The procedures for this service.
159
- */
160
- procedures;
161
- /**
162
- * @param config - The configuration for this service.
163
- * @param procedures - The procedures for this service.
164
- */
165
- constructor(config, procedures) {
166
- this.initializeState = config.initializeState;
167
- this.procedures = procedures;
168
- }
169
- /**
170
- * Creates a {@link ServiceScaffold}, which can be used to define procedures
171
- * that can then be merged into a {@link ServiceSchema}, via the scaffold's
172
- * `finalize` method.
173
- *
174
- * There are two patterns that work well with this method. The first is using
175
- * it to separate the definition of procedures from the definition of the
176
- * service's configuration:
177
- * ```ts
178
- * const MyServiceScaffold = ServiceSchema.scaffold({
179
- * initializeState: () => ({ count: 0 }),
180
- * });
181
- *
182
- * const incrementProcedures = MyServiceScaffold.procedures({
183
- * increment: Procedure.rpc({
184
- * requestInit: Type.Object({ amount: Type.Number() }),
185
- * responseData: Type.Object({ current: Type.Number() }),
186
- * async handler(ctx, init) {
187
- * ctx.state.count += init.amount;
188
- * return Ok({ current: ctx.state.count });
189
- * }
190
- * }),
191
- * })
192
- *
193
- * const MyService = MyServiceScaffold.finalize({
194
- * ...incrementProcedures,
195
- * // you can also directly define procedures here
196
- * });
197
- * ```
198
- * This might be really handy if you have a very large service and you're
199
- * wanting to split it over multiple files. You can define the scaffold
200
- * in one file, and then import that scaffold in other files where you
201
- * define procedures - and then finally import the scaffolds and your
202
- * procedure objects in a final file where you finalize the scaffold into
203
- * a service schema.
204
- *
205
- * The other way is to use it like in a builder pattern:
206
- * ```ts
207
- * const MyService = ServiceSchema
208
- * .scaffold({ initializeState: () => ({ count: 0 }) })
209
- * .finalize({
210
- * increment: Procedure.rpc({
211
- * requestInit: Type.Object({ amount: Type.Number() }),
212
- * responseData: Type.Object({ current: Type.Number() }),
213
- * async handler(ctx, init) {
214
- * ctx.state.count += init.amount;
215
- * return Ok({ current: ctx.state.count });
216
- * }
217
- * }),
218
- * })
219
- * ```
220
- * Depending on your preferences, this may be a more appealing way to define
221
- * a schema versus using the {@link ServiceSchema.define} method.
222
- */
223
- static scaffold(config) {
224
- return new ServiceScaffold(config);
225
- }
226
- // actual implementation
227
- static define(configOrProcedures, maybeProcedures) {
228
- let config;
229
- let procedures;
230
- if ("initializeState" in configOrProcedures && typeof configOrProcedures.initializeState === "function") {
231
- if (!maybeProcedures) {
232
- throw new Error("Expected procedures to be defined");
233
- }
234
- config = configOrProcedures;
235
- procedures = maybeProcedures;
236
- } else {
237
- config = { initializeState: () => ({}) };
238
- procedures = configOrProcedures;
239
- }
240
- return new ServiceSchema(config, procedures);
241
- }
242
- /**
243
- * Serializes this schema's procedures into a plain object that is JSON compatible.
244
- */
245
- serialize() {
246
- return {
247
- procedures: Object.fromEntries(
248
- Object.entries(this.procedures).map(([procName, procDef]) => [
249
- procName,
250
- {
251
- init: Strict(procDef.requestInit),
252
- output: Strict(procDef.responseData),
253
- errors: getSerializedProcErrors(procDef),
254
- // Only add `description` field if the type declares it.
255
- ..."description" in procDef ? { description: procDef.description } : {},
256
- type: procDef.type,
257
- // Only add the `input` field if the type declares it.
258
- ..."requestData" in procDef ? {
259
- input: Strict(procDef.requestData)
260
- } : {}
261
- }
262
- ])
263
- )
264
- };
265
- }
266
- // TODO remove once clients migrate to v2
267
- /**
268
- * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with
269
- * protocol v1. This is useful to be able to continue to generate schemas for older
270
- * clients as they are still supported.
271
- */
272
- serializeV1Compat() {
273
- return {
274
- procedures: Object.fromEntries(
275
- Object.entries(this.procedures).map(
276
- ([procName, procDef]) => {
277
- if (procDef.type === "rpc" || procDef.type === "subscription") {
278
- return [
279
- procName,
280
- {
281
- // BACKWARDS COMPAT: map init to input for protocolv1
282
- // this is the only change needed to make it compatible.
283
- input: Strict(procDef.requestInit),
284
- output: Strict(procDef.responseData),
285
- errors: getSerializedProcErrors(procDef),
286
- // Only add `description` field if the type declares it.
287
- ..."description" in procDef ? { description: procDef.description } : {},
288
- type: procDef.type
289
- }
290
- ];
291
- }
292
- return [
293
- procName,
294
- {
295
- init: Strict(procDef.requestInit),
296
- output: Strict(procDef.responseData),
297
- errors: getSerializedProcErrors(procDef),
298
- // Only add `description` field if the type declares it.
299
- ..."description" in procDef ? { description: procDef.description } : {},
300
- type: procDef.type,
301
- input: Strict(procDef.requestData)
302
- }
303
- ];
304
- }
305
- )
306
- )
307
- };
308
- }
309
- /**
310
- * Instantiates this schema into a {@link Service} object.
311
- *
312
- * You probably don't need this, usually the River server will handle this
313
- * for you.
314
- */
315
- instantiate(extendedContext) {
316
- const state = this.initializeState(extendedContext);
317
- const dispose = async () => {
318
- await state[Symbol.asyncDispose]?.();
319
- state[Symbol.dispose]?.();
320
- };
321
- return Object.freeze({
322
- state,
323
- procedures: this.procedures,
324
- [Symbol.asyncDispose]: dispose
325
- });
326
- }
327
- };
328
- }
329
- function getSerializedProcErrors(procDef) {
330
- if (!("responseError" in procDef) || procDef.responseError[import_typebox2.Kind] === "Never") {
331
- return Strict(ReaderErrorSchema);
332
- }
333
- const withProtocolErrors = flattenErrorType(
334
- import_typebox2.Type.Union([procDef.responseError, ReaderErrorSchema])
335
- );
336
- return Strict(withProtocolErrors);
337
- }
338
- var ServiceScaffold = class {
339
- /**
340
- * The configuration for this service.
341
- */
342
- config;
343
- /**
344
- * @param config - The configuration for this service.
345
- */
346
- constructor(config) {
347
- this.config = config;
348
- }
349
- /**
350
- * Define procedures for this service. Use the {@link Procedure} constructors
351
- * to create them. This returns the procedures object, which can then be
352
- * passed to {@link ServiceSchema.finalize} to create a {@link ServiceSchema}.
353
- *
354
- * @example
355
- * ```
356
- * const myProcedures = MyServiceScaffold.procedures({
357
- * myRPC: Procedure.rpc({
358
- * // ...
359
- * }),
360
- * });
361
- *
362
- * const MyService = MyServiceScaffold.finalize({
363
- * ...myProcedures,
364
- * });
365
- * ```
366
- *
367
- * @param procedures - The procedures for this service.
368
- */
369
- procedures(procedures) {
370
- return procedures;
371
- }
372
- /**
373
- * Finalizes the scaffold into a {@link ServiceSchema}. This is where you
374
- * provide the service's procedures and get a {@link ServiceSchema} in return.
375
- *
376
- * You can directly define procedures here, or you can define them separately
377
- * with the {@link ServiceScaffold.procedures} method, and then pass them here.
378
- *
379
- * @example
380
- * ```
381
- * const MyService = MyServiceScaffold.finalize({
382
- * myRPC: Procedure.rpc({
383
- * // ...
384
- * }),
385
- * // e.g. from the procedures method
386
- * ...myOtherProcedures,
387
- * });
388
- * ```
389
- */
390
- finalize(procedures) {
391
- return createServiceSchema().define(
392
- this.config,
393
- procedures
394
- );
395
- }
396
- };
397
-
398
- // router/result.ts
399
- var import_typebox3 = require("@sinclair/typebox");
400
- var AnyResultSchema = import_typebox3.Type.Union([
401
- import_typebox3.Type.Object({
402
- ok: import_typebox3.Type.Literal(false),
403
- payload: import_typebox3.Type.Object({
404
- code: import_typebox3.Type.String(),
405
- message: import_typebox3.Type.String(),
406
- extras: import_typebox3.Type.Optional(import_typebox3.Type.Unknown())
407
- })
408
- }),
409
- import_typebox3.Type.Object({
410
- ok: import_typebox3.Type.Literal(true),
411
- payload: import_typebox3.Type.Unknown()
412
- })
413
- ]);
414
- function Ok(payload) {
415
- return {
416
- ok: true,
417
- payload
418
- };
419
- }
420
- function Err(error) {
421
- return {
422
- ok: false,
423
- payload: error
424
- };
425
- }
426
-
427
- // router/streams.ts
428
- var ReadableBrokenError = {
429
- code: "READABLE_BROKEN",
430
- message: "Readable was broken before it is fully consumed"
431
- };
432
- function createPromiseWithResolvers() {
433
- let resolve;
434
- let reject;
435
- const promise = new Promise((res, rej) => {
436
- resolve = res;
437
- reject = rej;
438
- });
439
- return {
440
- promise,
441
- // @ts-expect-error promise callbacks are sync
442
- resolve,
443
- // @ts-expect-error promise callbacks are sync
444
- reject
445
- };
446
- }
447
- var ReadableImpl = class {
448
- /**
449
- * Whether the {@link Readable} is closed.
450
- *
451
- * Closed {@link Readable}s are done receiving values, but that doesn't affect
452
- * any other aspect of the {@link Readable} such as it's consumability.
453
- */
454
- closed = false;
455
- /**
456
- * Whether the {@link Readable} is locked.
457
- *
458
- * @see {@link Readable}'s typedoc to understand locking
459
- */
460
- locked = false;
461
- /**
462
- * Whether {@link break} was called.
463
- *
464
- * @see {@link break} for more information
465
- */
466
- broken = false;
467
- /**
468
- * This flag allows us to avoid emitting a {@link ReadableBrokenError} after {@link break} was called
469
- * in cases where the {@link queue} is fully consumed and {@link ReadableImpl} is {@link closed}. This is just an
470
- * ergonomic feature to avoid emitting an error in our iteration when we don't have to.
471
- */
472
- brokenWithValuesLeftToRead = false;
473
- /**
474
- * A list of values that have been pushed to the {@link ReadableImpl} but not yet emitted to the user.
475
- */
476
- queue = [];
477
- /**
478
- * Used by methods in the class to signal to the iterator that it
479
- * should check for the next value.
480
- */
481
- next = null;
482
- /**
483
- * Consumes the {@link Readable} and returns an {@link AsyncIterator} that can be used
484
- * to iterate over the values in the {@link Readable}.
485
- */
486
- [Symbol.asyncIterator]() {
487
- if (this.locked) {
488
- throw new TypeError("Readable is already locked");
489
- }
490
- this.locked = true;
491
- let didSignalBreak = false;
492
- return {
493
- next: async () => {
494
- if (didSignalBreak) {
495
- return {
496
- done: true,
497
- value: void 0
498
- };
499
- }
500
- while (this.queue.length === 0) {
501
- if (this.closed && !this.brokenWithValuesLeftToRead) {
502
- return {
503
- done: true,
504
- value: void 0
505
- };
506
- }
507
- if (this.broken) {
508
- didSignalBreak = true;
509
- return {
510
- done: false,
511
- value: Err(ReadableBrokenError)
512
- };
513
- }
514
- if (!this.next) {
515
- this.next = createPromiseWithResolvers();
516
- }
517
- await this.next.promise;
518
- this.next = null;
519
- }
520
- const value = this.queue.shift();
521
- return { done: false, value };
522
- },
523
- return: async () => {
524
- this.break();
525
- return { done: true, value: void 0 };
526
- }
527
- };
528
- }
529
- /**
530
- * Collects all the values from the {@link Readable} into an array.
531
- *
532
- * @see {@link Readable}'s typedoc for more information
533
- */
534
- async collect() {
535
- const array = [];
536
- for await (const value of this) {
537
- array.push(value);
538
- }
539
- return array;
540
- }
541
- /**
542
- * Breaks the {@link Readable} and signals an error to any iterators waiting for the next value.
543
- *
544
- * @see {@link Readable}'s typedoc for more information
545
- */
546
- break() {
547
- if (this.broken) {
548
- return;
549
- }
550
- this.locked = true;
551
- this.broken = true;
552
- this.brokenWithValuesLeftToRead = this.queue.length > 0;
553
- this.queue.length = 0;
554
- this.next?.resolve();
555
- }
556
- /**
557
- * Whether the {@link Readable} is readable.
558
- *
559
- * @see {@link Readable}'s typedoc for more information
560
- */
561
- isReadable() {
562
- return !this.locked && !this.broken;
563
- }
564
- /**
565
- * Pushes a value to be read.
566
- */
567
- _pushValue(value) {
568
- if (this.broken) {
569
- return;
570
- }
571
- if (this.closed) {
572
- throw new Error("Cannot push to closed Readable");
573
- }
574
- this.queue.push(value);
575
- this.next?.resolve();
576
- }
577
- /**
578
- * Triggers the close of the {@link Readable}. Make sure to push all remaining
579
- * values before calling this method.
580
- */
581
- _triggerClose() {
582
- if (this.closed) {
583
- throw new Error("Unexpected closing multiple times");
584
- }
585
- this.closed = true;
586
- this.next?.resolve();
587
- }
588
- /**
589
- * @internal meant for use within river, not exposed as a public API
590
- */
591
- _hasValuesInQueue() {
592
- return this.queue.length > 0;
593
- }
594
- /**
595
- * Whether the {@link Readable} is closed.
596
- */
597
- isClosed() {
598
- return this.closed;
599
- }
600
- };
601
- var WritableImpl = class {
602
- /**
603
- * Passed via constructor to pass on calls to {@link write}
604
- */
605
- writeCb;
606
- /**
607
- * Passed via constructor to pass on calls to {@link close}
608
- */
609
- closeCb;
610
- /**
611
- * Whether {@link close} was called, and {@link Writable} is not writable anymore.
612
- */
613
- closed = false;
614
- constructor(callbacks) {
615
- this.writeCb = callbacks.writeCb;
616
- this.closeCb = callbacks.closeCb;
617
- }
618
- write(value) {
619
- if (this.closed) {
620
- throw new Error("Cannot write to closed Writable");
621
- }
622
- this.writeCb(value);
623
- }
624
- isWritable() {
625
- return !this.closed;
626
- }
627
- close(value) {
628
- if (this.closed) {
629
- return;
630
- }
631
- if (value !== void 0) {
632
- this.writeCb(value);
633
- }
634
- this.closed = true;
635
- this.writeCb = () => void 0;
636
- this.closeCb();
637
- this.closeCb = () => void 0;
638
- }
639
- /**
640
- * @internal meant for use within river, not exposed as a public API
641
- */
642
- isClosed() {
643
- return this.closed;
644
- }
645
- };
646
-
647
- // router/procedures.ts
648
- var import_typebox4 = require("@sinclair/typebox");
649
- function rpc({
650
- requestInit,
651
- responseData,
652
- responseError = import_typebox4.Type.Never(),
653
- description,
654
- handler
655
- }) {
656
- return {
657
- ...description ? { description } : {},
658
- type: "rpc",
659
- requestInit,
660
- responseData,
661
- responseError,
662
- handler
663
- };
664
- }
665
- function upload({
666
- requestInit,
667
- requestData,
668
- responseData,
669
- responseError = import_typebox4.Type.Never(),
670
- description,
671
- handler
672
- }) {
673
- return {
674
- type: "upload",
675
- ...description ? { description } : {},
676
- requestInit,
677
- requestData,
678
- responseData,
679
- responseError,
680
- handler
681
- };
682
- }
683
- function subscription({
684
- requestInit,
685
- responseData,
686
- responseError = import_typebox4.Type.Never(),
687
- description,
688
- handler
689
- }) {
690
- return {
691
- type: "subscription",
692
- ...description ? { description } : {},
693
- requestInit,
694
- responseData,
695
- responseError,
696
- handler
697
- };
698
- }
699
- function stream({
700
- requestInit,
701
- requestData,
702
- responseData,
703
- responseError = import_typebox4.Type.Never(),
704
- description,
705
- handler
706
- }) {
707
- return {
708
- type: "stream",
709
- ...description ? { description } : {},
710
- requestInit,
711
- requestData,
712
- responseData,
713
- responseError,
714
- handler
715
- };
716
- }
717
- var Procedure = {
718
- rpc,
719
- upload,
720
- subscription,
721
- stream
722
- };
723
-
724
- // transport/message.ts
725
- var import_typebox5 = require("@sinclair/typebox");
726
-
727
- // transport/id.ts
728
- var import_nanoid = require("nanoid");
729
- var alphabet = (0, import_nanoid.customAlphabet)(
730
- "1234567890abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ"
731
- );
732
- var generateId = () => alphabet(12);
733
-
734
- // transport/message.ts
735
- var TransportMessageSchema = (t) => import_typebox5.Type.Object({
736
- id: import_typebox5.Type.String(),
737
- from: import_typebox5.Type.String(),
738
- to: import_typebox5.Type.String(),
739
- seq: import_typebox5.Type.Integer(),
740
- ack: import_typebox5.Type.Integer(),
741
- serviceName: import_typebox5.Type.Optional(import_typebox5.Type.String()),
742
- procedureName: import_typebox5.Type.Optional(import_typebox5.Type.String()),
743
- streamId: import_typebox5.Type.String(),
744
- controlFlags: import_typebox5.Type.Integer(),
745
- tracing: import_typebox5.Type.Optional(
746
- import_typebox5.Type.Object({
747
- traceparent: import_typebox5.Type.String(),
748
- tracestate: import_typebox5.Type.String()
749
- })
750
- ),
751
- payload: t
752
- });
753
- var ControlMessageAckSchema = import_typebox5.Type.Object({
754
- type: import_typebox5.Type.Literal("ACK")
755
- });
756
- var ControlMessageCloseSchema = import_typebox5.Type.Object({
757
- type: import_typebox5.Type.Literal("CLOSE")
758
- });
759
- var ControlMessageHandshakeRequestSchema = import_typebox5.Type.Object({
760
- type: import_typebox5.Type.Literal("HANDSHAKE_REQ"),
761
- protocolVersion: import_typebox5.Type.String(),
762
- sessionId: import_typebox5.Type.String(),
763
- /**
764
- * Specifies what the server's expected session state (from the pov of the client). This can be
765
- * used by the server to know whether this is a new or a reestablished connection, and whether it
766
- * is compatible with what it already has.
767
- */
768
- expectedSessionState: import_typebox5.Type.Object({
769
- // what the client expects the server to send next
770
- nextExpectedSeq: import_typebox5.Type.Integer(),
771
- nextSentSeq: import_typebox5.Type.Integer()
772
- }),
773
- metadata: import_typebox5.Type.Optional(import_typebox5.Type.Unknown())
774
- });
775
- var HandshakeErrorRetriableResponseCodes = import_typebox5.Type.Union([
776
- import_typebox5.Type.Literal("SESSION_STATE_MISMATCH")
777
- ]);
778
- var HandshakeErrorCustomHandlerFatalResponseCodes = import_typebox5.Type.Union([
779
- // The custom validation handler rejected the handler because the client is unsupported.
780
- import_typebox5.Type.Literal("REJECTED_UNSUPPORTED_CLIENT"),
781
- // The custom validation handler rejected the handshake.
782
- import_typebox5.Type.Literal("REJECTED_BY_CUSTOM_HANDLER")
783
- ]);
784
- var HandshakeErrorFatalResponseCodes = import_typebox5.Type.Union([
785
- HandshakeErrorCustomHandlerFatalResponseCodes,
786
- // The ciient sent a handshake that doesn't comply with the extended handshake metadata.
787
- import_typebox5.Type.Literal("MALFORMED_HANDSHAKE_META"),
788
- // The ciient sent a handshake that doesn't comply with ControlMessageHandshakeRequestSchema.
789
- import_typebox5.Type.Literal("MALFORMED_HANDSHAKE"),
790
- // The client's protocol version does not match the server's.
791
- import_typebox5.Type.Literal("PROTOCOL_VERSION_MISMATCH")
792
- ]);
793
- var HandshakeErrorResponseCodes = import_typebox5.Type.Union([
794
- HandshakeErrorRetriableResponseCodes,
795
- HandshakeErrorFatalResponseCodes
796
- ]);
797
- var ControlMessageHandshakeResponseSchema = import_typebox5.Type.Object({
798
- type: import_typebox5.Type.Literal("HANDSHAKE_RESP"),
799
- status: import_typebox5.Type.Union([
800
- import_typebox5.Type.Object({
801
- ok: import_typebox5.Type.Literal(true),
802
- sessionId: import_typebox5.Type.String()
803
- }),
804
- import_typebox5.Type.Object({
805
- ok: import_typebox5.Type.Literal(false),
806
- reason: import_typebox5.Type.String(),
807
- code: HandshakeErrorResponseCodes
808
- })
809
- ])
810
- });
811
- var ControlMessagePayloadSchema = import_typebox5.Type.Union([
812
- ControlMessageCloseSchema,
813
- ControlMessageAckSchema,
814
- ControlMessageHandshakeRequestSchema,
815
- ControlMessageHandshakeResponseSchema
816
- ]);
817
- var OpaqueTransportMessageSchema = TransportMessageSchema(
818
- import_typebox5.Type.Unknown()
819
- );
820
- function closeStreamMessage(streamId) {
821
- return {
822
- streamId,
823
- controlFlags: 8 /* StreamClosedBit */,
824
- payload: {
825
- type: "CLOSE"
826
- }
827
- };
828
- }
829
- function cancelMessage(streamId, payload) {
830
- return {
831
- streamId,
832
- controlFlags: 4 /* StreamCancelBit */,
833
- payload
834
- };
835
- }
836
- function isStreamOpen(controlFlag) {
837
- return (
838
- /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */
839
- (controlFlag & 2 /* StreamOpenBit */) === 2 /* StreamOpenBit */
840
- );
841
- }
842
- function isStreamClose(controlFlag) {
843
- return (
844
- /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */
845
- (controlFlag & 8 /* StreamClosedBit */) === 8 /* StreamClosedBit */
846
- );
847
- }
848
- function isStreamCancel(controlFlag) {
849
- return (
850
- /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */
851
- (controlFlag & 4 /* StreamCancelBit */) === 4 /* StreamCancelBit */
852
- );
853
- }
854
-
855
- // tracing/index.ts
856
- var import_api = require("@opentelemetry/api");
857
- function getPropagationContext(ctx) {
858
- const tracing = {
859
- traceparent: "",
860
- tracestate: ""
861
- };
862
- import_api.propagation.inject(ctx, tracing);
863
- return tracing;
864
- }
865
- function createProcTelemetryInfo(tracer, session, kind, serviceName, procedureName, streamId) {
866
- const baseCtx = import_api.context.active();
867
- const span = tracer.startSpan(
868
- `river.client.${serviceName}.${procedureName}`,
869
- {
870
- attributes: {
871
- component: "river",
872
- "river.method.kind": kind,
873
- "river.method.service": serviceName,
874
- "river.method.name": procedureName,
875
- "river.streamId": streamId,
876
- "span.kind": "client"
877
- },
878
- links: [{ context: session.telemetry.span.spanContext() }],
879
- kind: import_api.SpanKind.CLIENT
880
- },
881
- baseCtx
882
- );
883
- const ctx = import_api.trace.setSpan(baseCtx, span);
884
- const metadata = {
885
- ...session.loggingMetadata,
886
- transportMessage: {
887
- procedureName,
888
- serviceName
889
- }
890
- };
891
- if (span.isRecording()) {
892
- metadata.telemetry = {
893
- traceId: span.spanContext().traceId,
894
- spanId: span.spanContext().spanId
895
- };
896
- }
897
- session.log?.info(`invoked ${serviceName}.${procedureName}`, metadata);
898
- return { span, ctx };
899
- }
900
- function createHandlerSpan(tracer, session, kind, serviceName, procedureName, streamId, tracing, fn) {
901
- const ctx = tracing ? import_api.propagation.extract(import_api.context.active(), tracing) : import_api.context.active();
902
- return tracer.startActiveSpan(
903
- `river.server.${serviceName}.${procedureName}`,
904
- {
905
- attributes: {
906
- component: "river",
907
- "river.method.kind": kind,
908
- "river.method.service": serviceName,
909
- "river.method.name": procedureName,
910
- "river.streamId": streamId,
911
- "span.kind": "server"
912
- },
913
- links: [{ context: session.telemetry.span.spanContext() }],
914
- kind: import_api.SpanKind.SERVER
915
- },
916
- ctx,
917
- fn
918
- );
919
- }
920
- function recordRiverError(span, error) {
921
- span.setStatus({
922
- code: import_api.SpanStatusCode.ERROR,
923
- message: error.message
924
- });
925
- span.setAttributes({
926
- "river.error_code": error.code,
927
- "river.error_message": error.message
928
- });
929
- }
930
- function getTracer() {
931
- return import_api.trace.getTracer("river", version);
932
- }
933
-
934
- // router/client.ts
935
- var import_value = require("@sinclair/typebox/value");
936
- var noop = () => {
937
- };
938
- function _createRecursiveProxy(callback, path) {
939
- const proxy = new Proxy(noop, {
940
- // property access, recurse and add field to path
941
- get(_obj, key) {
942
- if (typeof key !== "string") return void 0;
943
- if (key === "then") return void 0;
944
- return _createRecursiveProxy(callback, [...path, key]);
945
- },
946
- // hit the end, let's invoke the handler
947
- apply(_target, _this, args) {
948
- return callback({
949
- path,
950
- args
951
- });
952
- }
953
- });
954
- return proxy;
955
- }
956
- var defaultClientOptions = {
957
- connectOnInvoke: true,
958
- eagerlyConnect: true
959
- };
960
- function createClient(transport, serverId, providedClientOptions = {}) {
961
- if (providedClientOptions.handshakeOptions) {
962
- transport.extendHandshake(providedClientOptions.handshakeOptions);
963
- }
964
- const clientOptions = { ...defaultClientOptions, ...providedClientOptions };
965
- if (clientOptions.eagerlyConnect) {
966
- transport.connect(serverId);
967
- }
968
- return _createRecursiveProxy((opts) => {
969
- const [serviceName, procName, procMethod] = [...opts.path];
970
- if (!(serviceName && procName && procMethod)) {
971
- throw new Error(
972
- "invalid river call, ensure the service and procedure you are calling exists"
973
- );
974
- }
975
- const [init, callOptions] = opts.args;
976
- if (clientOptions.connectOnInvoke && !transport.sessions.has(serverId)) {
977
- transport.connect(serverId);
978
- }
979
- if (procMethod !== "rpc" && procMethod !== "subscribe" && procMethod !== "stream" && procMethod !== "upload") {
980
- throw new Error(
981
- `invalid river call, unknown procedure type ${procMethod}`
982
- );
983
- }
984
- const merged = mergeCallOptions(
985
- clientOptions.defaultCallOptions,
986
- callOptions
987
- );
988
- return handleProc(
989
- procMethod === "subscribe" ? "subscription" : procMethod,
990
- transport,
991
- serverId,
992
- init,
993
- serviceName,
994
- procName,
995
- merged.signal
996
- );
997
- }, []);
998
- }
999
- function mergeCallOptions(defaults, caller) {
1000
- const resolved = typeof defaults === "function" ? defaults() : defaults ?? {};
1001
- return { ...resolved, ...caller };
1002
- }
1003
- function handleProc(procType, transport, serverId, init, serviceName, procedureName, abortSignal) {
1004
- if (transport.getStatus() === "closed") {
1005
- return getPreClosedReturnForProc(procType);
1006
- }
1007
- const session = transport.sessions.get(serverId) ?? transport.createUnconnectedSession(serverId);
1008
- const sessionScopedSend = transport.getSessionBoundSendFn(
1009
- serverId,
1010
- session.id
1011
- );
1012
- const procClosesWithInit = procType === "rpc" || procType === "subscription";
1013
- const streamId = generateId();
1014
- const { span, ctx } = createProcTelemetryInfo(
1015
- transport.tracer,
1016
- session,
1017
- procType,
1018
- serviceName,
1019
- procedureName,
1020
- streamId
1021
- );
1022
- let cleanClose = true;
1023
- const reqWritable = new WritableImpl({
1024
- writeCb: (rawIn) => {
1025
- sessionScopedSend({
1026
- streamId,
1027
- payload: rawIn,
1028
- controlFlags: 0
1029
- });
1030
- },
1031
- // close callback
1032
- closeCb: () => {
1033
- span.addEvent("reqWritable closed");
1034
- if (!procClosesWithInit && cleanClose) {
1035
- sessionScopedSend(closeStreamMessage(streamId));
1036
- }
1037
- if (resReadable.isClosed()) {
1038
- cleanup();
1039
- }
1040
- }
1041
- });
1042
- const resReadable = new ReadableImpl();
1043
- const closeReadable = () => {
1044
- resReadable._triggerClose();
1045
- span.addEvent("resReadable closed");
1046
- if (reqWritable.isClosed()) {
1047
- cleanup();
1048
- }
1049
- };
1050
- function cleanup() {
1051
- transport.removeEventListener("message", onMessage);
1052
- transport.removeEventListener("sessionStatus", onSessionStatus);
1053
- abortSignal?.removeEventListener("abort", onClientCancel);
1054
- span.end();
1055
- }
1056
- function onClientCancel() {
1057
- if (resReadable.isClosed() && reqWritable.isClosed()) {
1058
- return;
1059
- }
1060
- span.addEvent("sending cancel");
1061
- cleanClose = false;
1062
- if (!resReadable.isClosed()) {
1063
- resReadable._pushValue(
1064
- Err({
1065
- code: CANCEL_CODE,
1066
- message: "cancelled by client"
1067
- })
1068
- );
1069
- closeReadable();
1070
- }
1071
- reqWritable.close();
1072
- sessionScopedSend(
1073
- cancelMessage(
1074
- streamId,
1075
- Err({
1076
- code: CANCEL_CODE,
1077
- message: "cancelled by client"
1078
- })
1079
- )
1080
- );
1081
- }
1082
- function onMessage(msg) {
1083
- if (msg.streamId !== streamId) return;
1084
- if (msg.to !== transport.clientId) {
1085
- transport.log?.error("got stream message from unexpected client", {
1086
- clientId: transport.clientId,
1087
- transportMessage: msg
1088
- });
1089
- return;
1090
- }
1091
- if (isStreamCancel(msg.controlFlags)) {
1092
- cleanClose = false;
1093
- span.addEvent("received cancel");
1094
- let cancelResult;
1095
- if (import_value.Value.Check(ReaderErrorResultSchema, msg.payload)) {
1096
- cancelResult = msg.payload;
1097
- } else {
1098
- cancelResult = Err({
1099
- code: CANCEL_CODE,
1100
- message: "stream cancelled with invalid payload"
1101
- });
1102
- transport.log?.warn(
1103
- "got stream cancel without a valid protocol error",
1104
- {
1105
- clientId: transport.clientId,
1106
- transportMessage: msg,
1107
- validationErrors: [
1108
- ...import_value.Value.Errors(ReaderErrorResultSchema, msg.payload)
1109
- ]
1110
- }
1111
- );
1112
- }
1113
- if (!resReadable.isClosed()) {
1114
- resReadable._pushValue(cancelResult);
1115
- closeReadable();
1116
- }
1117
- reqWritable.close();
1118
- return;
1119
- }
1120
- if (resReadable.isClosed()) {
1121
- span.recordException("received message after response stream is closed");
1122
- transport.log?.error("received message after response stream is closed", {
1123
- clientId: transport.clientId,
1124
- transportMessage: msg
1125
- });
1126
- return;
1127
- }
1128
- if (!import_value.Value.Check(ControlMessageCloseSchema, msg.payload)) {
1129
- if (import_value.Value.Check(AnyResultSchema, msg.payload)) {
1130
- resReadable._pushValue(msg.payload);
1131
- } else {
1132
- transport.log?.error(
1133
- "Got non-control payload, but was not a valid result",
1134
- {
1135
- clientId: transport.clientId,
1136
- transportMessage: msg,
1137
- validationErrors: [...import_value.Value.Errors(AnyResultSchema, msg.payload)]
1138
- }
1139
- );
1140
- }
1141
- }
1142
- if (isStreamClose(msg.controlFlags)) {
1143
- span.addEvent("received response close");
1144
- if (resReadable.isClosed()) {
1145
- transport.log?.error(
1146
- "received stream close but readable was already closed"
1147
- );
1148
- } else {
1149
- closeReadable();
1150
- }
1151
- }
1152
- }
1153
- function onSessionStatus(evt) {
1154
- if (evt.status !== "closing" || evt.session.to !== serverId || session.id !== evt.session.id) {
1155
- return;
1156
- }
1157
- cleanClose = false;
1158
- if (!resReadable.isClosed()) {
1159
- resReadable._pushValue(
1160
- Err({
1161
- code: UNEXPECTED_DISCONNECT_CODE,
1162
- message: `${serverId} unexpectedly disconnected`
1163
- })
1164
- );
1165
- closeReadable();
1166
- }
1167
- reqWritable.close();
1168
- }
1169
- abortSignal?.addEventListener("abort", onClientCancel);
1170
- transport.addEventListener("message", onMessage);
1171
- transport.addEventListener("sessionStatus", onSessionStatus);
1172
- try {
1173
- sessionScopedSend({
1174
- streamId,
1175
- serviceName,
1176
- procedureName,
1177
- tracing: getPropagationContext(ctx),
1178
- payload: init,
1179
- controlFlags: procClosesWithInit ? 2 /* StreamOpenBit */ | 8 /* StreamClosedBit */ : 2 /* StreamOpenBit */
1180
- });
1181
- } catch (e) {
1182
- cleanup();
1183
- throw e;
1184
- }
1185
- if (procClosesWithInit) {
1186
- reqWritable.close();
1187
- }
1188
- return getReturnForProc(procType, resReadable, reqWritable, transport.log);
1189
- }
1190
- function getPreClosedReturnForProc(procType) {
1191
- const readable = new ReadableImpl();
1192
- const err = Err({
1193
- code: UNEXPECTED_DISCONNECT_CODE,
1194
- message: `transport is closed`
1195
- });
1196
- readable._pushValue(err);
1197
- readable._triggerClose();
1198
- const writable = new WritableImpl({
1199
- writeCb: () => {
1200
- },
1201
- closeCb: () => {
1202
- }
1203
- });
1204
- writable.close();
1205
- return getReturnForProc(procType, readable, writable);
1206
- }
1207
- function getReturnForProc(procType, resReadable, reqWritable, log) {
1208
- if (procType === "subscription") {
1209
- return {
1210
- resReadable
1211
- };
1212
- }
1213
- if (procType === "rpc") {
1214
- return getSingleMessage(resReadable, log);
1215
- }
1216
- if (procType === "upload") {
1217
- let didFinalize = false;
1218
- return {
1219
- reqWritable,
1220
- finalize: () => {
1221
- if (didFinalize) {
1222
- throw new Error("upload stream already finalized");
1223
- }
1224
- didFinalize = true;
1225
- if (!reqWritable.isClosed()) {
1226
- reqWritable.close();
1227
- }
1228
- return getSingleMessage(resReadable, log);
1229
- }
1230
- };
1231
- }
1232
- return {
1233
- resReadable,
1234
- reqWritable
1235
- };
1236
- }
1237
- async function getSingleMessage(resReadable, log) {
1238
- const ret = await resReadable.collect();
1239
- if (ret.length > 1) {
1240
- log?.error("Expected single message from server, got multiple");
1241
- }
1242
- return ret[0];
1243
- }
1244
-
1245
- // router/server.ts
1246
- var import_value2 = require("@sinclair/typebox/value");
1247
-
1248
- // transport/stringifyError.ts
1249
- function coerceErrorString(err) {
1250
- if (err instanceof Error) {
1251
- return err.message || "unknown reason";
1252
- }
1253
- return `[coerced to error] ${String(err)}`;
1254
- }
1255
-
1256
- // router/server.ts
1257
- var import_api2 = require("@opentelemetry/api");
1258
- var RiverServer = class {
1259
- transport;
1260
- contextMap;
1261
- extendedContext;
1262
- log;
1263
- middlewares;
1264
- /**
1265
- * We create a tombstones for streams cancelled by the server
1266
- * so that we don't hit errors when the client has inflight
1267
- * requests it sent before it saw the cancel.
1268
- * We track cancelled streams for every client separately, so
1269
- * that bad clients don't affect good clients.
1270
- */
1271
- serverCancelledStreams;
1272
- maxCancelledStreamTombstonesPerSession;
1273
- streams;
1274
- services;
1275
- unregisterTransportListeners;
1276
- constructor(transport, services, handshakeOptions, extendedContext, maxCancelledStreamTombstonesPerSession = 200, middlewares = []) {
1277
- const instances = {};
1278
- this.middlewares = middlewares;
1279
- this.services = instances;
1280
- this.contextMap = /* @__PURE__ */ new Map();
1281
- extendedContext = extendedContext ?? {};
1282
- this.extendedContext = extendedContext;
1283
- for (const [name, service] of Object.entries(services)) {
1284
- const instance = service.instantiate(extendedContext);
1285
- instances[name] = instance;
1286
- this.contextMap.set(instance, {
1287
- ...extendedContext,
1288
- state: instance.state
1289
- });
1290
- }
1291
- if (handshakeOptions) {
1292
- transport.extendHandshake(handshakeOptions);
1293
- }
1294
- this.transport = transport;
1295
- this.streams = /* @__PURE__ */ new Map();
1296
- this.serverCancelledStreams = /* @__PURE__ */ new Map();
1297
- this.maxCancelledStreamTombstonesPerSession = maxCancelledStreamTombstonesPerSession;
1298
- this.log = transport.log;
1299
- const handleCreatingNewStreams = (message) => {
1300
- if (message.to !== this.transport.clientId) {
1301
- this.log?.info(
1302
- `got msg with destination that isn't this server, ignoring`,
1303
- {
1304
- clientId: this.transport.clientId,
1305
- transportMessage: message
1306
- }
1307
- );
1308
- return;
1309
- }
1310
- const streamId = message.streamId;
1311
- const stream2 = this.streams.get(streamId);
1312
- if (stream2) {
1313
- stream2.handleMsg(message);
1314
- return;
1315
- }
1316
- if (this.serverCancelledStreams.get(message.from)?.has(streamId)) {
1317
- return;
1318
- }
1319
- const newStreamProps = this.validateNewProcStream(message);
1320
- if (!newStreamProps) {
1321
- return;
1322
- }
1323
- createHandlerSpan(
1324
- transport.tracer,
1325
- newStreamProps.initialSession,
1326
- newStreamProps.procedure.type,
1327
- newStreamProps.serviceName,
1328
- newStreamProps.procedureName,
1329
- newStreamProps.streamId,
1330
- newStreamProps.tracingCtx,
1331
- (span) => {
1332
- this.createNewProcStream(span, newStreamProps);
1333
- }
1334
- );
1335
- };
1336
- const handleSessionStatus = (evt) => {
1337
- if (evt.status !== "closing") return;
1338
- const disconnectedClientId = evt.session.to;
1339
- this.log?.info(
1340
- `got session disconnect from ${disconnectedClientId}, cleaning up streams`,
1341
- evt.session.loggingMetadata
1342
- );
1343
- for (const stream2 of this.streams.values()) {
1344
- if (stream2.from === disconnectedClientId) {
1345
- stream2.handleSessionDisconnect();
1346
- }
1347
- }
1348
- this.serverCancelledStreams.delete(disconnectedClientId);
1349
- };
1350
- const handleTransportStatus = (evt) => {
1351
- if (evt.status !== "closed") return;
1352
- this.unregisterTransportListeners();
1353
- };
1354
- this.unregisterTransportListeners = () => {
1355
- this.transport.removeEventListener("message", handleCreatingNewStreams);
1356
- this.transport.removeEventListener("sessionStatus", handleSessionStatus);
1357
- this.transport.removeEventListener(
1358
- "transportStatus",
1359
- handleTransportStatus
1360
- );
1361
- };
1362
- this.transport.addEventListener("message", handleCreatingNewStreams);
1363
- this.transport.addEventListener("sessionStatus", handleSessionStatus);
1364
- this.transport.addEventListener("transportStatus", handleTransportStatus);
1365
- }
1366
- createNewProcStream(span, props) {
1367
- const {
1368
- streamId,
1369
- initialSession,
1370
- procedureName,
1371
- serviceName,
1372
- procedure,
1373
- sessionMetadata,
1374
- serviceContext,
1375
- initPayload,
1376
- procClosesWithInit,
1377
- passInitAsDataForBackwardsCompat
1378
- } = props;
1379
- const {
1380
- to: from,
1381
- loggingMetadata,
1382
- protocolVersion,
1383
- id: sessionId
1384
- } = initialSession;
1385
- loggingMetadata.telemetry = {
1386
- traceId: span.spanContext().traceId,
1387
- spanId: span.spanContext().spanId
1388
- };
1389
- let cleanClose = true;
1390
- const onMessage = (msg) => {
1391
- if (msg.from !== from) {
1392
- this.log?.error("got stream message from unexpected client", {
1393
- ...loggingMetadata,
1394
- transportMessage: msg,
1395
- tags: ["invariant-violation"]
1396
- });
1397
- return;
1398
- }
1399
- if (isStreamCancelBackwardsCompat(msg.controlFlags, protocolVersion)) {
1400
- let cancelResult;
1401
- if (import_value2.Value.Check(CancelResultSchema, msg.payload)) {
1402
- cancelResult = msg.payload;
1403
- } else {
1404
- cancelResult = Err({
1405
- code: CANCEL_CODE,
1406
- message: "stream cancelled, client sent invalid payload"
1407
- });
1408
- this.log?.warn("got stream cancel without a valid protocol error", {
1409
- ...loggingMetadata,
1410
- transportMessage: msg,
1411
- validationErrors: [
1412
- ...import_value2.Value.Errors(CancelResultSchema, msg.payload)
1413
- ],
1414
- tags: ["invalid-request"]
1415
- });
1416
- }
1417
- if (!reqReadable.isClosed()) {
1418
- reqReadable._pushValue(cancelResult);
1419
- closeReadable();
1420
- }
1421
- resWritable.close();
1422
- return;
1423
- }
1424
- if (reqReadable.isClosed()) {
1425
- this.log?.warn("received message after request stream is closed", {
1426
- ...loggingMetadata,
1427
- transportMessage: msg,
1428
- tags: ["invalid-request"]
1429
- });
1430
- onServerCancel({
1431
- code: INVALID_REQUEST_CODE,
1432
- message: "received message after request stream is closed"
1433
- });
1434
- return;
1435
- }
1436
- if ("requestData" in procedure && import_value2.Value.Check(procedure.requestData, msg.payload)) {
1437
- reqReadable._pushValue(Ok(msg.payload));
1438
- if (isStreamCloseBackwardsCompat(msg.controlFlags, protocolVersion)) {
1439
- closeReadable();
1440
- }
1441
- return;
1442
- }
1443
- if (import_value2.Value.Check(ControlMessagePayloadSchema, msg.payload) && isStreamCloseBackwardsCompat(msg.controlFlags, protocolVersion)) {
1444
- closeReadable();
1445
- return;
1446
- }
1447
- let validationErrors;
1448
- let errMessage;
1449
- if ("requestData" in procedure) {
1450
- errMessage = "message in requestData position did not match schema";
1451
- validationErrors = castTypeboxValueErrors(
1452
- import_value2.Value.Errors(procedure.requestData, msg.payload)
1453
- );
1454
- } else {
1455
- validationErrors = castTypeboxValueErrors(
1456
- import_value2.Value.Errors(ControlMessagePayloadSchema, msg.payload)
1457
- );
1458
- errMessage = "message in control payload position did not match schema";
1459
- }
1460
- this.log?.warn(errMessage, {
1461
- ...loggingMetadata,
1462
- transportMessage: msg,
1463
- validationErrors: validationErrors.map((error) => ({
1464
- path: error.path,
1465
- message: error.message
1466
- })),
1467
- tags: ["invalid-request"]
1468
- });
1469
- onServerCancel({
1470
- code: INVALID_REQUEST_CODE,
1471
- message: errMessage,
1472
- extras: {
1473
- totalErrors: validationErrors.length,
1474
- firstValidationErrors: validationErrors.slice(0, 5)
1475
- }
1476
- });
1477
- };
1478
- const finishedController = new AbortController();
1479
- const procStream = {
1480
- from,
1481
- streamId,
1482
- procedureName,
1483
- serviceName,
1484
- sessionMetadata,
1485
- procedure,
1486
- handleMsg: onMessage,
1487
- handleSessionDisconnect: () => {
1488
- cleanClose = false;
1489
- const errPayload = {
1490
- code: UNEXPECTED_DISCONNECT_CODE,
1491
- message: "client unexpectedly disconnected"
1492
- };
1493
- if (!reqReadable.isClosed()) {
1494
- reqReadable._pushValue(Err(errPayload));
1495
- closeReadable();
1496
- }
1497
- resWritable.close();
1498
- }
1499
- };
1500
- const sessionScopedSend = this.transport.getSessionBoundSendFn(
1501
- from,
1502
- sessionId
1503
- );
1504
- const cancelStream = (streamId2, payload) => {
1505
- this.cancelStream(from, sessionScopedSend, streamId2, payload);
1506
- };
1507
- const onServerCancel = (e) => {
1508
- recordRiverError(span, e);
1509
- if (reqReadable.isClosed() && resWritable.isClosed()) {
1510
- return;
1511
- }
1512
- cleanClose = false;
1513
- const result = Err(e);
1514
- if (!reqReadable.isClosed()) {
1515
- reqReadable._pushValue(result);
1516
- closeReadable();
1517
- }
1518
- resWritable.close();
1519
- cancelStream(streamId, result);
1520
- };
1521
- const deferredCleanups = [];
1522
- let cleanupsHaveRun = false;
1523
- const runCleanupSafe = async (fn) => {
1524
- try {
1525
- await fn();
1526
- } catch (err) {
1527
- span.recordException(
1528
- err instanceof Error ? err : new Error(coerceErrorString(err))
1529
- );
1530
- }
1531
- };
1532
- const deferCleanup = (fn) => {
1533
- if (cleanupsHaveRun) {
1534
- void runCleanupSafe(fn);
1535
- return;
1536
- }
1537
- deferredCleanups.push(fn);
1538
- };
1539
- const runDeferredCleanups = async () => {
1540
- if (deferredCleanups.length === 0) {
1541
- cleanupsHaveRun = true;
1542
- span.end();
1543
- return;
1544
- }
1545
- const cleanupSpan = getTracer().startSpan(
1546
- "river.cleanup",
1547
- {},
1548
- import_api2.trace.setSpan(import_api2.context.active(), span)
1549
- );
1550
- try {
1551
- for (let fn = deferredCleanups.pop(); fn; fn = deferredCleanups.pop()) {
1552
- await runCleanupSafe(fn);
1553
- }
1554
- } finally {
1555
- cleanupsHaveRun = true;
1556
- cleanupSpan.end();
1557
- span.end();
1558
- }
1559
- };
1560
- const cleanup = () => {
1561
- finishedController.abort();
1562
- this.streams.delete(streamId);
1563
- void runDeferredCleanups();
1564
- };
1565
- const procClosesWithResponse = procedure.type === "rpc" || procedure.type === "upload";
1566
- const reqReadable = new ReadableImpl();
1567
- const closeReadable = () => {
1568
- reqReadable._triggerClose();
1569
- if (protocolVersion === "v1.1") {
1570
- if (!procClosesWithResponse && !resWritable.isClosed()) {
1571
- resWritable.close();
1572
- }
1573
- }
1574
- if (resWritable.isClosed()) {
1575
- cleanup();
1576
- }
1577
- };
1578
- if (passInitAsDataForBackwardsCompat) {
1579
- reqReadable._pushValue(Ok(initPayload));
1580
- }
1581
- const resWritable = new WritableImpl({
1582
- writeCb: (response) => {
1583
- if (!response.ok) {
1584
- recordRiverError(span, response.payload);
1585
- }
1586
- sessionScopedSend({
1587
- streamId,
1588
- controlFlags: procClosesWithResponse ? getStreamCloseBackwardsCompat(protocolVersion) : 0,
1589
- payload: response
1590
- });
1591
- if (procClosesWithResponse) {
1592
- resWritable.close();
1593
- }
1594
- },
1595
- // close callback
1596
- closeCb: () => {
1597
- if (!procClosesWithResponse && cleanClose) {
1598
- const message = closeStreamMessage(streamId);
1599
- message.controlFlags = getStreamCloseBackwardsCompat(protocolVersion);
1600
- sessionScopedSend(message);
1601
- }
1602
- if (protocolVersion === "v1.1") {
1603
- if (!reqReadable.isClosed()) {
1604
- closeReadable();
1605
- }
1606
- }
1607
- if (reqReadable.isClosed()) {
1608
- cleanup();
1609
- }
1610
- }
1611
- });
1612
- const onHandlerError = (err, span2) => {
1613
- const errorMsg = coerceErrorString(err);
1614
- span2.recordException(err instanceof Error ? err : new Error(errorMsg));
1615
- this.log?.error(
1616
- `${serviceName}.${procedureName} handler threw an uncaught error`,
1617
- {
1618
- ...loggingMetadata,
1619
- transportMessage: {
1620
- procedureName,
1621
- serviceName
1622
- },
1623
- extras: {
1624
- error: errorMsg,
1625
- originalException: err
1626
- },
1627
- tags: ["uncaught-handler-error"]
1628
- }
1629
- );
1630
- onServerCancel({
1631
- code: UNCAUGHT_ERROR_CODE,
1632
- message: errorMsg
1633
- });
1634
- };
1635
- if (procClosesWithInit) {
1636
- closeReadable();
1637
- }
1638
- const handlerContextWithSpan = {
1639
- ...serviceContext,
1640
- from,
1641
- sessionId,
1642
- metadata: sessionMetadata,
1643
- span,
1644
- cancel: (message) => {
1645
- const errRes = {
1646
- code: CANCEL_CODE,
1647
- message: message ?? "cancelled by server procedure handler"
1648
- };
1649
- onServerCancel(errRes);
1650
- return Err(errRes);
1651
- },
1652
- deferCleanup,
1653
- signal: finishedController.signal
1654
- };
1655
- const middlewareContext = {
1656
- ...serviceContext,
1657
- sessionId,
1658
- from,
1659
- metadata: sessionMetadata,
1660
- span,
1661
- deferCleanup,
1662
- signal: finishedController.signal,
1663
- streamId,
1664
- procedureName,
1665
- serviceName
1666
- };
1667
- const runProcedureHandler = async () => {
1668
- switch (procedure.type) {
1669
- case "rpc":
1670
- try {
1671
- const responsePayload = await procedure.handler({
1672
- ctx: handlerContextWithSpan,
1673
- reqInit: initPayload
1674
- });
1675
- if (resWritable.isClosed()) {
1676
- return;
1677
- }
1678
- resWritable.write(responsePayload);
1679
- } catch (err) {
1680
- onHandlerError(err, span);
1681
- }
1682
- break;
1683
- case "stream":
1684
- try {
1685
- await procedure.handler({
1686
- ctx: handlerContextWithSpan,
1687
- reqInit: initPayload,
1688
- reqReadable,
1689
- resWritable
1690
- });
1691
- } catch (err) {
1692
- onHandlerError(err, span);
1693
- }
1694
- break;
1695
- case "subscription":
1696
- try {
1697
- await procedure.handler({
1698
- ctx: handlerContextWithSpan,
1699
- reqInit: initPayload,
1700
- resWritable
1701
- });
1702
- } catch (err) {
1703
- onHandlerError(err, span);
1704
- }
1705
- break;
1706
- case "upload":
1707
- try {
1708
- const responsePayload = await procedure.handler({
1709
- ctx: handlerContextWithSpan,
1710
- reqInit: initPayload,
1711
- reqReadable
1712
- });
1713
- if (resWritable.isClosed()) {
1714
- return;
1715
- }
1716
- resWritable.write(responsePayload);
1717
- } catch (err) {
1718
- onHandlerError(err, span);
1719
- }
1720
- break;
1721
- }
1722
- };
1723
- this.middlewares.reduceRight(
1724
- (next, middleware) => {
1725
- return () => {
1726
- middleware({
1727
- ctx: middlewareContext,
1728
- reqInit: initPayload,
1729
- next
1730
- });
1731
- };
1732
- },
1733
- () => {
1734
- void runProcedureHandler();
1735
- }
1736
- )();
1737
- if (!finishedController.signal.aborted) {
1738
- this.streams.set(streamId, procStream);
1739
- }
1740
- }
1741
- getContext(service, serviceName) {
1742
- const context2 = this.contextMap.get(service);
1743
- if (!context2) {
1744
- const err = `no context found for ${serviceName}`;
1745
- this.log?.error(err, {
1746
- clientId: this.transport.clientId,
1747
- tags: ["invariant-violation"]
1748
- });
1749
- throw new Error(err);
1750
- }
1751
- return context2;
1752
- }
1753
- validateNewProcStream(initMessage) {
1754
- const session = this.transport.sessions.get(initMessage.from);
1755
- if (!session) {
1756
- this.log?.error(`couldn't find session for ${initMessage.from}`, {
1757
- clientId: this.transport.clientId,
1758
- transportMessage: initMessage,
1759
- tags: ["invariant-violation"]
1760
- });
1761
- return null;
1762
- }
1763
- const sessionScopedSend = this.transport.getSessionBoundSendFn(
1764
- initMessage.from,
1765
- session.id
1766
- );
1767
- const cancelStream = (streamId, payload) => {
1768
- this.cancelStream(initMessage.from, sessionScopedSend, streamId, payload);
1769
- };
1770
- const sessionMetadata = this.transport.sessionHandshakeMetadata.get(
1771
- session.to
1772
- );
1773
- if (!sessionMetadata) {
1774
- const errMessage = `session doesn't have handshake metadata`;
1775
- this.log?.error(errMessage, {
1776
- ...session.loggingMetadata,
1777
- tags: ["invariant-violation"]
1778
- });
1779
- cancelStream(
1780
- initMessage.streamId,
1781
- Err({
1782
- code: UNCAUGHT_ERROR_CODE,
1783
- message: errMessage
1784
- })
1785
- );
1786
- return null;
1787
- }
1788
- if (!isStreamOpen(initMessage.controlFlags)) {
1789
- const errMessage = `can't create a new procedure stream from a message that doesn't have the stream open bit set`;
1790
- this.log?.warn(errMessage, {
1791
- ...session.loggingMetadata,
1792
- clientId: this.transport.clientId,
1793
- transportMessage: initMessage,
1794
- tags: ["invalid-request"]
1795
- });
1796
- cancelStream(
1797
- initMessage.streamId,
1798
- Err({
1799
- code: INVALID_REQUEST_CODE,
1800
- message: errMessage
1801
- })
1802
- );
1803
- return null;
1804
- }
1805
- if (!initMessage.serviceName) {
1806
- const errMessage = `missing service name in stream open message`;
1807
- this.log?.warn(errMessage, {
1808
- ...session.loggingMetadata,
1809
- transportMessage: initMessage,
1810
- tags: ["invalid-request"]
1811
- });
1812
- cancelStream(
1813
- initMessage.streamId,
1814
- Err({
1815
- code: INVALID_REQUEST_CODE,
1816
- message: errMessage
1817
- })
1818
- );
1819
- return null;
1820
- }
1821
- if (!initMessage.procedureName) {
1822
- const errMessage = `missing procedure name in stream open message`;
1823
- this.log?.warn(errMessage, {
1824
- ...session.loggingMetadata,
1825
- transportMessage: initMessage,
1826
- tags: ["invalid-request"]
1827
- });
1828
- cancelStream(
1829
- initMessage.streamId,
1830
- Err({
1831
- code: INVALID_REQUEST_CODE,
1832
- message: errMessage
1833
- })
1834
- );
1835
- return null;
1836
- }
1837
- if (!(initMessage.serviceName in this.services)) {
1838
- const errMessage = `couldn't find service ${initMessage.serviceName}`;
1839
- this.log?.warn(errMessage, {
1840
- ...session.loggingMetadata,
1841
- clientId: this.transport.clientId,
1842
- transportMessage: initMessage,
1843
- tags: ["invalid-request"]
1844
- });
1845
- cancelStream(
1846
- initMessage.streamId,
1847
- Err({
1848
- code: INVALID_REQUEST_CODE,
1849
- message: errMessage
1850
- })
1851
- );
1852
- return null;
1853
- }
1854
- const service = this.services[initMessage.serviceName];
1855
- if (!(initMessage.procedureName in service.procedures)) {
1856
- const errMessage = `couldn't find a matching procedure for ${initMessage.serviceName}.${initMessage.procedureName}`;
1857
- this.log?.warn(errMessage, {
1858
- ...session.loggingMetadata,
1859
- transportMessage: initMessage,
1860
- tags: ["invalid-request"]
1861
- });
1862
- cancelStream(
1863
- initMessage.streamId,
1864
- Err({
1865
- code: INVALID_REQUEST_CODE,
1866
- message: errMessage
1867
- })
1868
- );
1869
- return null;
1870
- }
1871
- const serviceContext = this.getContext(service, initMessage.serviceName);
1872
- const procedure = service.procedures[initMessage.procedureName];
1873
- if (!["rpc", "upload", "stream", "subscription"].includes(procedure.type)) {
1874
- this.log?.error(
1875
- `got request for invalid procedure type ${procedure.type} at ${initMessage.serviceName}.${initMessage.procedureName}`,
1876
- {
1877
- ...session.loggingMetadata,
1878
- transportMessage: initMessage,
1879
- tags: ["invariant-violation"]
1880
- }
1881
- );
1882
- return null;
1883
- }
1884
- let passInitAsDataForBackwardsCompat = false;
1885
- if (session.protocolVersion === "v1.1" && (procedure.type === "upload" || procedure.type === "stream") && import_value2.Value.Check(procedure.requestData, initMessage.payload) && import_value2.Value.Check(procedure.requestInit, {})) {
1886
- passInitAsDataForBackwardsCompat = true;
1887
- } else if (!import_value2.Value.Check(procedure.requestInit, initMessage.payload)) {
1888
- const errMessage = `procedure init failed validation`;
1889
- this.log?.warn(errMessage, {
1890
- ...session.loggingMetadata,
1891
- clientId: this.transport.clientId,
1892
- transportMessage: initMessage,
1893
- tags: ["invalid-request"]
1894
- });
1895
- cancelStream(
1896
- initMessage.streamId,
1897
- Err({
1898
- code: INVALID_REQUEST_CODE,
1899
- message: errMessage
1900
- })
1901
- );
1902
- return null;
1903
- }
1904
- return {
1905
- initialSession: session,
1906
- streamId: initMessage.streamId,
1907
- procedureName: initMessage.procedureName,
1908
- serviceName: initMessage.serviceName,
1909
- tracingCtx: initMessage.tracing,
1910
- initPayload: initMessage.payload,
1911
- sessionMetadata,
1912
- procedure,
1913
- serviceContext,
1914
- procClosesWithInit: isStreamCloseBackwardsCompat(
1915
- initMessage.controlFlags,
1916
- session.protocolVersion
1917
- ),
1918
- passInitAsDataForBackwardsCompat
1919
- };
1920
- }
1921
- cancelStream(to, sessionScopedSend, streamId, payload) {
1922
- let cancelledStreamsInSession = this.serverCancelledStreams.get(to);
1923
- if (!cancelledStreamsInSession) {
1924
- cancelledStreamsInSession = new LRUSet(
1925
- this.maxCancelledStreamTombstonesPerSession
1926
- );
1927
- this.serverCancelledStreams.set(to, cancelledStreamsInSession);
1928
- }
1929
- cancelledStreamsInSession.add(streamId);
1930
- const msg = cancelMessage(streamId, payload);
1931
- sessionScopedSend(msg);
1932
- }
1933
- async close() {
1934
- this.unregisterTransportListeners();
1935
- for (const serviceName of Object.keys(this.services)) {
1936
- const service = this.services[serviceName];
1937
- await service[Symbol.asyncDispose]();
1938
- }
1939
- if (this.extendedContext) {
1940
- const ctx = this.extendedContext;
1941
- if (ctx[Symbol.asyncDispose]) {
1942
- await ctx[Symbol.asyncDispose]?.();
1943
- } else if (ctx[Symbol.dispose]) {
1944
- ctx[Symbol.dispose]?.();
1945
- } else {
1946
- for (const value of Object.values(ctx)) {
1947
- if (value && typeof value === "object") {
1948
- const v = value;
1949
- if (v[Symbol.asyncDispose]) {
1950
- await v[Symbol.asyncDispose]?.();
1951
- } else if (v[Symbol.dispose]) {
1952
- v[Symbol.dispose]?.();
1953
- }
1954
- }
1955
- }
1956
- }
1957
- }
1958
- }
1959
- };
1960
- var LRUSet = class {
1961
- items;
1962
- maxItems;
1963
- constructor(maxItems) {
1964
- this.items = /* @__PURE__ */ new Set();
1965
- this.maxItems = maxItems;
1966
- }
1967
- add(item) {
1968
- if (this.items.has(item)) {
1969
- this.items.delete(item);
1970
- } else if (this.items.size >= this.maxItems) {
1971
- const first = this.items.values().next();
1972
- if (!first.done) {
1973
- this.items.delete(first.value);
1974
- }
1975
- }
1976
- this.items.add(item);
1977
- }
1978
- has(item) {
1979
- return this.items.has(item);
1980
- }
1981
- };
1982
- function isStreamCancelBackwardsCompat(controlFlags, protocolVersion) {
1983
- if (protocolVersion === "v1.1") {
1984
- return false;
1985
- }
1986
- return isStreamCancel(controlFlags);
1987
- }
1988
- function isStreamCloseBackwardsCompat(controlFlags, protocolVersion) {
1989
- if (protocolVersion === "v1.1") {
1990
- return isStreamCancel(controlFlags);
1991
- }
1992
- return isStreamClose(controlFlags);
1993
- }
1994
- function getStreamCloseBackwardsCompat(protocolVersion) {
1995
- if (protocolVersion === "v1.1") {
1996
- return 4 /* StreamCancelBit */;
1997
- }
1998
- return 8 /* StreamClosedBit */;
1999
- }
2000
- function createServer(transport, services, providedServerOptions) {
2001
- return new RiverServer(
2002
- transport,
2003
- services,
2004
- providedServerOptions?.handshakeOptions,
2005
- providedServerOptions?.extendedContext,
2006
- providedServerOptions?.maxCancelledStreamTombstonesPerSession,
2007
- providedServerOptions?.middlewares
2008
- );
2009
- }
2010
-
2011
- // router/handshake.ts
2012
- function createClientHandshakeOptions(schema, construct) {
2013
- return { schema, construct };
2014
- }
2015
- function createServerHandshakeOptions(schema, validate) {
2016
- return { schema, validate };
2017
- }
2018
-
2019
- // package.json
2020
- var version = "0.216.1";
2021
- // Annotate the CommonJS export names for ESM import in node:
2022
- 0 && (module.exports = {
2023
- CANCEL_CODE,
2024
- Err,
2025
- INVALID_REQUEST_CODE,
2026
- Ok,
2027
- Procedure,
2028
- RIVER_VERSION,
2029
- RawReadable,
2030
- ReadableBrokenError,
2031
- ReaderErrorSchema,
2032
- UNCAUGHT_ERROR_CODE,
2033
- UNEXPECTED_DISCONNECT_CODE,
2034
- createClient,
2035
- createClientHandshakeOptions,
2036
- createServer,
2037
- createServerHandshakeOptions,
2038
- createServiceSchema,
2039
- flattenErrorType,
2040
- serializeSchema,
2041
- serializeSchemaV1Compat
2042
- });
2043
- //# sourceMappingURL=index.cjs.map