import { TSchema, TObject, TLiteral, TEnum, TString, TNever, TUnion, Type, Static } from 'typebox'; import { Span } from '@opentelemetry/api'; import { C as CustomHandshakeErrorCodeSchema, T as TransportClientId } from './message-C2qDAau6.js'; import { C as Connection, n as ClientHandshakeOptions, A as SessionId } from './transport-DF2T202E.js'; import { C as ClientTransport } from './client-C8pwDvTN.js'; declare const ReadableBrokenError: { readonly code: "READABLE_BROKEN"; readonly message: "Readable was broken before it is fully consumed"; }; /** * Similar to {@link Result} but with an extra error to handle cases where {@link Readable.break} is called */ type ReadableResult = Result; /** * A simple {@link AsyncIterator} used in {@link Readable} * that doesn't have a the extra "return" and "throw" methods, and * the doesn't have a "done value" (TReturn). */ interface ReadableIterator extends AsyncIterator> { next(): Promise<{ done: false; value: ReadableResult; } | { done: true; value: undefined; }>; } /** * A {@link Readable} is an abstraction from which data is consumed from {@link Writable} source. * * - On the server the argument passed the procedure handler for `upload` and `stream` implements a {@link Readable} interface * so you can read client's request data. * - On the client the returned value of `subscription` or `stream` invocation implements a {@link Readable} interface * so you can read server's response data. * * A {@link Readable} can only have one consumer (iterator or {@link collect}) for the {@link Readable}'s * lifetime, in essense, reading from a {@link Readable} locks it forever. */ interface Readable { /** * {@link Readable} implements AsyncIterator API and can be consumed via * for-await-of loops. Iteration locks the Readable. Exiting the loop * will **not** release the lock and it'll be equivalent of calling * {@link break}. */ [Symbol.asyncIterator](): ReadableIterator; /** * {@link collect} locks the {@link Readable} and returns a promise that resolves * with an array of the content when the {@link Readable} is fully done. This could * be due to the {@link Writable} end of the pipe closing cleanly, the procedure invocation * is cancelled, or {@link break} is called. */ collect(): Promise>>; /** * {@link break} locks the {@link Readable} and discards any existing or future incoming data. * * If there is an existing reader waiting for the next value, {@link break} causes it to * resolve with a {@link ReadableBrokenError} error. */ break(): undefined; /** * {@link isReadable} returns true if it's safe to read from the {@link Readable}, either * via iteration or {@link collect}. It returns false if the {@link Readable} is locked * by a consumer (iterator or {@link collect}) or readable was broken via {@link break}. */ isReadable(): boolean; } /** * A {@link Writeable} is a an abstraction for a {@link Readable} destination to which data is written to. * * - On the server the argument passed the procedure handler for `subscription` and `stream` implements a {@link Writeable} * so you can write server's response data. * - On the client the returned value of `upload` or `stream` invocation implements a {@link Writeable} * so you can write client's request data. * * Once closed, a {@link Writeable} can't be re-opened.` ` */ interface Writable { /** * {@link write} writes a value to the pipe. An error is thrown if writing to a closed {@link Writable}. * * Returns `false` if the underlying session's send buffer is at or above * its high-water mark, signalling that the producer should stop writing * until {@link waitForWriteReady} resolves. This is purely advisory — * the value is still buffered and will be delivered, exactly like * node's `stream.Writable.write`. */ write(value: T): boolean; /** * {@link waitForWriteReady} resolves once the underlying session's send * buffer has drained back below its high-water mark and it is productive * to call {@link write} again. * * Resolves immediately if there is no backpressure or if this * {@link Writable} is already closed. Never rejects. Note that a promise * that is already pending when this {@link Writable} closes stays pending * until the underlying session drains or closes (the latter is bounded by * the session grace period) — producers should re-check {@link isWritable} * after awaiting. */ waitForWriteReady(): Promise; /** * {@link close} signals the closure of the {@link Writeable}, informing the {@link Readable} end that * all data has been transmitted and we've cleanly closed. * Optionally a final value can be passed to {@link close}, which will be the last value * to write before it closes. * * Calling {@link close} multiple times is a no-op. */ close(value?: T): undefined; /** * {@link isWritable} returns true if it's safe to call {@link write}, which * means that the {@link Writable} hasn't been closed due to {@link close} being called * on this {@link Writable} or the procedure invocation ending for any reason. */ isWritable(): boolean; } /** * @internal * * @see {@link createPromiseWithResolvers} */ /** * Internal implementation of a {@link Readable}. * This should generally not be constructed directly by consumers * of river, but rather through either the client or procedure handlers. * * There are rare cases where this is useful to construct in tests or * to 'tee' a {@link Readable} to create a copy of the stream but * this is not the common case. */ declare class ReadableImpl implements Readable { /** * Whether the {@link Readable} is closed. * * Closed {@link Readable}s are done receiving values, but that doesn't affect * any other aspect of the {@link Readable} such as it's consumability. */ private closed; /** * Whether the {@link Readable} is locked. * * @see {@link Readable}'s typedoc to understand locking */ private locked; /** * Whether {@link break} was called. * * @see {@link break} for more information */ private broken; /** * This flag allows us to avoid emitting a {@link ReadableBrokenError} after {@link break} was called * in cases where the {@link queue} is fully consumed and {@link ReadableImpl} is {@link closed}. This is just an * ergonomic feature to avoid emitting an error in our iteration when we don't have to. */ private brokenWithValuesLeftToRead; /** * A list of values that have been pushed to the {@link ReadableImpl} but not yet emitted to the user. */ private queue; /** * Used by methods in the class to signal to the iterator that it * should check for the next value. */ private next; /** * Consumes the {@link Readable} and returns an {@link AsyncIterator} that can be used * to iterate over the values in the {@link Readable}. */ [Symbol.asyncIterator](): ReadableIterator; /** * Collects all the values from the {@link Readable} into an array. * * @see {@link Readable}'s typedoc for more information */ collect(): Promise>>; /** * Breaks the {@link Readable} and signals an error to any iterators waiting for the next value. * * @see {@link Readable}'s typedoc for more information */ break(): undefined; /** * Whether the {@link Readable} is readable. * * @see {@link Readable}'s typedoc for more information */ isReadable(): boolean; /** * Pushes a value to be read. */ _pushValue(value: Result): undefined; /** * Triggers the close of the {@link Readable}. Make sure to push all remaining * values before calling this method. */ _triggerClose(): undefined; /** * @internal meant for use within river, not exposed as a public API */ _hasValuesInQueue(): boolean; /** * Whether the {@link Readable} is closed. */ isClosed(): boolean; } interface CallOptions { signal?: AbortSignal; } type RpcFn = (reqInit: ProcInit, options?: CallOptions) => Promise, ProcErrors>>; type UploadFn = (reqInit: ProcInit, options?: CallOptions) => { reqWritable: Writable>; finalize: () => Promise, ProcErrors>>; }; type StreamFn = (reqInit: ProcInit, options?: CallOptions) => { reqWritable: Writable>; resReadable: Readable, ProcErrors>; }; type SubscriptionFn = (reqInit: ProcInit, options?: CallOptions) => { resReadable: Readable, ProcErrors>; }; /** * A helper type to transform an actual service type into a type * we can case to in the proxy. * @template Service - The type of the Service. */ type ServiceClient = { [ProcName in keyof Service['procedures']]: ProcType extends 'rpc' ? { rpc: RpcFn; } : ProcType extends 'upload' ? { upload: UploadFn; } : ProcType extends 'stream' ? { stream: StreamFn; } : ProcType extends 'subscription' ? { subscribe: SubscriptionFn; } : never; }; /** * Defines a type that represents a client for a server with a set of services. * @template Srv - The type of the server. */ type Client, IS extends InstantiatedServiceSchemaMap = InstantiatedServiceSchemaMap> = { [SvcName in keyof IS]: ServiceClient; }; interface ClientOptions { connectOnInvoke: boolean; eagerlyConnect: boolean; /** * Default options merged into every leaf call (`rpc`, `stream`, * `upload`, `subscribe`). Caller-supplied `options` win field-by-field, * so a caller can override `signal` while keeping other defaults. * * Pass a function form when the default needs to be re-resolved per * call (e.g. an ambient signal that changes between invocations of * the same client). */ defaultCallOptions?: CallOptions | (() => CallOptions); } /** * Creates a client for a given server using the provided transport. * Note that the client only needs the type of the server, not the actual * server definition itself. * * This relies on a proxy to dynamically create the client, so the client * will be typed as if it were the actual server with the appropriate services * and procedures. * * @template Srv - The type of the server. * @param {Transport} transport - The transport to use for communication. * @param {TransportClientId} serverId - The ID of the server to connect to. * @param {Partial} providedClientOptions - The options for the client. * @returns The client for the server. */ declare function createClient, RejectionCodeSchema extends CustomHandshakeErrorCodeSchema = never>(transport: ClientTransport, serverId: TransportClientId, providedClientOptions?: Partial; }>): Client; /** * {@link UNCAUGHT_ERROR_CODE} is the code that is used when an error is thrown * inside a procedure handler that's not required. */ declare const UNCAUGHT_ERROR_CODE = "UNCAUGHT_ERROR"; /** * {@link UNEXPECTED_DISCONNECT_CODE} is the code used the stream's session * disconnect unexpetedly. */ declare const UNEXPECTED_DISCONNECT_CODE = "UNEXPECTED_DISCONNECT"; /** * {@link INVALID_REQUEST_CODE} is the code used when a client's request is invalid. */ declare const INVALID_REQUEST_CODE = "INVALID_REQUEST"; /** * {@link CANCEL_CODE} is the code used when either server or client cancels the stream. */ declare const CANCEL_CODE = "CANCEL"; type TLiteralString = TLiteral; type TEnumString = TEnum>; type BaseErrorSchemaType = TObject<{ code: TLiteralString | TEnumString; message: TLiteralString | TString; }> | TObject<{ code: TLiteralString | TEnumString; message: TLiteralString | TString; extras: TSchema; }>; /** * A schema for cancel payloads sent from the client */ declare const CancelErrorSchema: TObject<{ code: TLiteral<"CANCEL">; message: TString; }>; /** * {@link ReaderErrorSchema} is the schema for all the built-in river errors that * can be emitted to a reader (request reader on the server, and response reader * on the client). */ declare const ReaderErrorSchema: TUnion<[TObject<{ code: TLiteral<"UNCAUGHT_ERROR">; message: TString; }>, TObject<{ code: TLiteral<"UNEXPECTED_DISCONNECT">; message: TString; }>, TObject<{ code: TLiteral<"INVALID_REQUEST">; message: TString; extras: Type.TOptional>; totalErrors: Type.TNumber; }>>; }>, TObject<{ code: TLiteral<"CANCEL">; message: TString; }>]>; /** * Represents an acceptable schema to pass to a procedure. * Just a type of a schema, not an actual schema. * */ type ProcedureErrorSchemaType = TNever | BaseErrorSchemaType | TUnion>; type NestableProcedureErrorSchemaType = BaseErrorSchemaType | TUnion; interface NestableProcedureErrorSchemaTypeArray extends Array { } type Flatten = T extends BaseErrorSchemaType ? T : T extends TUnion> ? Flatten : unknown; /** * In the case where API consumers for some god-forsaken reason want to use * arbitrarily nested unions, this helper flattens them to a single level. * * Note that loses some metadata information on the nested unions like * nested description fields, etc. * * @param errType - An arbitrarily union-nested error schema. * @returns The flattened error schema. */ declare function flattenErrorType(errType: T): Flatten; /** * The minimum error shape supported by river's `Result` and stream primitives. * * The existing TypeBox router uses schema-derived object types for this, while * the protobuf router can use a richer structural error type. */ interface ErrorPayload { code: string; message: string; extras?: unknown; } interface OkResult { ok: true; payload: T; } interface ErrResult { ok: false; payload: Err; } type Result = OkResult | ErrResult; declare function Ok>(p: T): OkResult; declare function Ok>(p: T): OkResult; declare function Ok(payload: T): OkResult; declare function Err(error: Err): ErrResult; /** * Refine a {@link Result} type to its returned payload. */ type ResultUnwrapOk = R extends Result ? T : never; /** * Refine a {@link Result} type to its error payload. */ type ResultUnwrapErr = R extends Result ? Err : never; /** * Retrieve the response type for a procedure, represented as a {@link Result} * type. * Example: * ``` * type Message = ResponseData * ``` */ type ResponseData unknown = (...args: never) => unknown> = RiverClient extends Client ? Procedure extends object ? Procedure extends object & { rpc: infer RpcFn extends Fn; } ? Awaited> : Procedure extends object & { upload: infer UploadFn extends Fn; } ? ReturnType extends { finalize: (...args: never) => Promise; } ? UploadOutputMessage : never : Procedure extends object & { stream: infer StreamFn extends Fn; } ? ReturnType extends { resReadable: Readable>; } ? StreamOutputMessage : never : Procedure extends object & { subscribe: infer SubscriptionFn extends Fn; } ? Awaited> extends { resReadable: Readable>; } ? SubscriptionOutputMessage : never : never : never : never; /** * This is passed to every procedure handler and contains various context-level * information and utilities. */ type ProcedureHandlerContext = Context & { /** * State for this service as defined by the service definition. */ state: State; /** * The span for this procedure call. You can use this to add attributes, events, and * links to the span. */ span: Span; /** * Metadata parsed on the server. See {@link createServerHandshakeOptions} */ metadata: ParsedMetadata; /** * The ID of the session that sent this request. */ sessionId: SessionId; /** * The ID of the client that sent this request. There may be multiple sessions per client. */ from: TransportClientId; /** * This is used to cancel the procedure call from the handler and notify the client that the * call was cancelled. * * Cancelling is not the same as closing procedure calls gracefully, please refer to * the river documentation to understand the difference between the two concepts. */ cancel: (message?: string) => ErrResult>; /** * Register a cleanup function that will run after the procedure handler * completes (whether it returns normally, throws, or is cancelled). * Cleanup functions run in reverse registration order (LIFO) and each * cleanup is awaited before the next one starts. * * Prefer this over registering async cleanup work on `signal`'s 'abort' * event. Abort signal callbacks fire synchronously and do not await async * work, so multiple async callbacks will interlace their execution * (coroutine-like behavior) rather than running sequentially to completion. * `deferCleanup` guarantees each cleanup finishes before the next begins. * * If a cleanup function throws, the error is recorded on the cleanup span * but remaining cleanups continue to run. */ deferCleanup: (fn: () => void | Promise) => void; /** * This signal is a standard [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) * triggered when the procedure invocation is done. This signal tracks the invocation/request finishing * for _any_ reason, for example: * - client explicit cancellation * - procedure handler explicit cancellation via {@link cancel} * - client session disconnect * - server cancellation due to client invalid payload * - invocation finishes cleanly, this depends on the type of the procedure (i.e. rpc handler return, or in a stream after the client-side has closed the request writable and the server-side has closed the response writable) * * You can use this to pass it on to asynchronous operations (such as fetch). * * You may also want to explicitly register callbacks on the * ['abort' event](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/abort_event) * as a way to cleanup after the request is finished. * * Note that (per standard AbortSignals) callbacks registered _after_ the procedure invocation * is done are not triggered. In such cases, you can check the "aborted" property and cleanup * immediately if needed. */ signal: AbortSignal; }; /** * Brands a type to prevent it from being directly constructed. */ type Branded = T & { readonly __BRAND_DO_NOT_USE: unique symbol; }; /** * Unbrands a {@link Branded} type. */ type Unbranded = T extends Branded ? U : never; /** * The valid {@link Procedure} types. The `stream` and `upload` types can optionally have a * different type for the very first initialization message. The suffixless types correspond to * gRPC's four combinations of stream / non-stream in each direction. */ type ValidProcType = 'rpc' | 'upload' | 'subscription' | 'stream'; /** * Represents the payload type for {@link Procedure}s. */ type PayloadType = TSchema; type Cancellable = T | Static; /** * Procedure for a single message in both directions (1:1). * * @template State - The context state object. * @template RequestInit - The TypeBox schema of the initialization object. * @template ResponseData - The TypeBox schema of the response object. * @template ResponseErr - The TypeBox schema of the error object. */ interface RpcProcedure { type: 'rpc'; requestInit: RequestInit; responseData: ResponseData; responseError: ResponseErr; description?: string; handler(param: { ctx: ProcedureHandlerContext; reqInit: Static; }): Promise, Cancellable>>>; } /** * Procedure for a client-stream (potentially preceded by an initialization message), * single message from server (n:1). * * @template State - The context state object. * @template RequestInit - The TypeBox schema of the initialization object. * @template RequestData - The TypeBox schema of the request object. * @template ResponseData - The TypeBox schema of the response object. * @template ResponseErr - The TypeBox schema of the error object. */ interface UploadProcedure { type: 'upload'; requestInit: RequestInit; requestData: RequestData; responseData: ResponseData; responseError: ResponseErr; description?: string; handler(param: { ctx: ProcedureHandlerContext; reqInit: Static; reqReadable: Readable, Static>; }): Promise, Cancellable>>>; } /** * Procedure for a single message from client, stream from server (1:n). * * @template State - The context state object. * @template RequestInit - The TypeBox schema of the initialization object. * @template ResponseData - The TypeBox schema of the response object. * @template ResponseErr - The TypeBox schema of the error object. */ interface SubscriptionProcedure { type: 'subscription'; requestInit: RequestInit; responseData: ResponseData; responseError: ResponseErr; description?: string; handler(param: { ctx: ProcedureHandlerContext; reqInit: Static; resWritable: Writable, Cancellable>>>; }): Promise; } /** * Procedure for a bidirectional stream (potentially preceded by an initialization message), * (n:n). * * @template State - The context state object. * @template RequestInit - The TypeBox schema of the initialization object. * @template RequestData - The TypeBox schema of the request object. * @template ResponseData - The TypeBox schema of the response object. * @template ResponseErr - The TypeBox schema of the error object. */ interface StreamProcedure { type: 'stream'; requestInit: RequestInit; requestData: RequestData; responseData: ResponseData; responseError: ResponseErr; description?: string; handler(param: { ctx: ProcedureHandlerContext; reqInit: Static; reqReadable: Readable, Static>; resWritable: Writable, Cancellable>>>; }): Promise; } /** * Represents any {@link Procedure} type. * * @template State - The context state object. You can provide this to constrain * the type of procedures. */ type AnyProcedure = Procedure; /** * Represents a map of {@link Procedure}s. * * @template State - The context state object. You can provide this to constrain * the type of procedures. */ type ProcedureMap = Record>; /** * Creates an {@link RpcProcedure}. */ declare function rpc(def: { requestInit: RequestInit; responseData: ResponseData; responseError?: never; description?: string; handler: RpcProcedure['handler']; }): Branded>; declare function rpc(def: { requestInit: RequestInit; responseData: ResponseData; responseError: ResponseErr; description?: string; handler: RpcProcedure['handler']; }): Branded>; /** * Creates an {@link UploadProcedure}, optionally with an initialization message. */ declare function upload(def: { requestInit: RequestInit; requestData: RequestData; responseData: ResponseData; responseError?: never; description?: string; handler: UploadProcedure['handler']; }): Branded>; declare function upload(def: { requestInit: RequestInit; requestData: RequestData; responseData: ResponseData; responseError: ResponseErr; description?: string; handler: UploadProcedure['handler']; }): Branded>; /** * Creates a {@link SubscriptionProcedure}. */ declare function subscription(def: { requestInit: RequestInit; responseData: ResponseData; responseError?: never; description?: string; handler: SubscriptionProcedure['handler']; }): Branded>; declare function subscription(def: { requestInit: RequestInit; responseData: ResponseData; responseError: ResponseErr; description?: string; handler: SubscriptionProcedure['handler']; }): Branded>; /** * Creates a {@link StreamProcedure}, optionally with an initialization message. */ declare function stream(def: { requestInit: RequestInit; requestData: RequestData; responseData: ResponseData; responseError?: never; description?: string; handler: StreamProcedure['handler']; }): Branded>; declare function stream(def: { requestInit: RequestInit; requestData: RequestData; responseData: ResponseData; responseError: ResponseErr; description?: string; handler: StreamProcedure['handler']; }): Branded>; /** * Defines a Procedure type that can be a: * - {@link RpcProcedure} for a single message in both directions (1:1) * - {@link UploadProcedure} for a client-stream (potentially preceded by an * initialization message) * - {@link SubscriptionProcedure} for a single message from client, stream from server (1:n) * - {@link StreamProcedure} for a bidirectional stream (potentially preceded by an * initialization message) * * @template State - The TypeBox schema of the state object. * @template Ty - The type of the procedure. * @template RequestData - The TypeBox schema of the request object. * @template RequestInit - The TypeBox schema of the request initialization object, if any. * @template ResponseData - The TypeBox schema of the response object. */ type Procedure = { type: Ty; } & (RequestData extends PayloadType ? Ty extends 'upload' ? UploadProcedure : Ty extends 'stream' ? StreamProcedure : never : Ty extends 'rpc' ? RpcProcedure : Ty extends 'subscription' ? SubscriptionProcedure : never); /** * Holds the {@link Procedure} creation functions. Use these to create * procedures for services. You aren't allowed to create procedures directly. */ declare const Procedure: { rpc: typeof rpc; upload: typeof upload; subscription: typeof subscription; stream: typeof stream; }; /** * An instantiated service, probably from a {@link ServiceSchema}. * * You shouldn't construct these directly, use {@link ServiceSchema} instead. */ interface Service> { readonly state: State; readonly procedures: Procs; [Symbol.asyncDispose]: () => PromiseLike; } /** * Represents any {@link Service} object. */ type AnyService = Service; /** * Represents any {@link ServiceSchema} object. */ type AnyServiceSchema = InstanceType>>; /** * A dictionary of {@link ServiceSchema}s, where the key is the service name. */ type AnyServiceSchemaMap = Record>; /** * Takes a {@link AnyServiceSchemaMap} and returns a dictionary of instantiated * services. */ type InstantiatedServiceSchemaMap> = { [K in keyof T]: T[K] extends AnyServiceSchema ? T[K] extends { initializeState: (ctx: Context) => infer S; procedures: infer P; } ? Service ? P : ProcedureMap> : never : never; }; /** * Helper to get the type definition for a specific handler of a procedure in a service. * @template S - The service. * @template ProcName - The name of the procedure. */ type ProcHandler = S['procedures'][ProcName]['handler']; /** * Helper to get the type definition for the procedure init type of a service. * @template S - The service. * @template ProcName - The name of the procedure. */ type ProcInit = Static; /** * Helper to get the type definition for the procedure request of a service. * @template S - The service. * @template ProcName - The name of the procedure. */ type ProcRequest = S['procedures'][ProcName] extends { requestData: PayloadType; } ? Static : never; /** * Helper to get the type definition for the procedure response of a service. * @template S - The service. * @template ProcName - The name of the procedure. */ type ProcResponse = Static; /** * Helper to get the type definition for the procedure errors of a service. * @template S - The service. * @template ProcName - The name of the procedure. */ type ProcErrors = Static | Static; /** * Helper to get the type of procedure in a service. * @template S - The service. * @template ProcName - The name of the procedure. */ type ProcType = S['procedures'][ProcName]['type']; /** * A list of procedures where every procedure is "branded", as-in the procedure * was created via the {@link Procedure} constructors. */ type BrandedProcedureMap = Record>>; type MaybeDisposable> = T & { [Symbol.asyncDispose]?: () => PromiseLike; [Symbol.dispose]?: () => void; }; /** * The configuration for a service. */ interface ServiceConfiguration { /** * A factory function for creating a fresh state. */ initializeState: (extendedContext: Context) => MaybeDisposable; } interface SerializedProcedureSchemaProtocolv1 { init?: PayloadType; input: PayloadType; output: PayloadType; errors?: ProcedureErrorSchemaType; type: 'rpc' | 'subscription' | 'upload' | 'stream'; } interface SerializedServiceSchemaProtocolv1 { procedures: Record; } interface SerializedServerSchemaProtocolv1 { handshakeSchema?: TSchema; services: Record; } /** * Same as {@link serializeSchema} but with a format that is compatible with * protocolv1. This is useful to be able to continue to generate schemas for older * clients as they are still supported. */ declare function serializeSchemaV1Compat(services: AnyServiceSchemaMap, handshakeSchema?: TSchema): SerializedServerSchemaProtocolv1; interface SerializedProcedureSchema { init: PayloadType; input?: PayloadType; output: PayloadType; errors?: ProcedureErrorSchemaType; type: 'rpc' | 'subscription' | 'upload' | 'stream'; } interface SerializedServiceSchema { procedures: Record; } interface SerializedServerSchema { handshakeSchema?: TSchema; services: Record; } /** * Serializes a server schema into a plain object that is JSON compatible. */ declare function serializeSchema(services: AnyServiceSchemaMap, handshakeSchema?: TSchema): SerializedServerSchema; /** * Creates a ServiceSchema class that can be used to define services with their initial state and procedures. * This is a factory function that returns a ServiceSchema class constructor bound to the specified Context type. * * @template Context - The context type that will be available to all procedures in services created with this schema. * @returns A ServiceSchema class constructor with static methods for defining services. * * @example * ```ts * // Create a ServiceSchema class for your context type * const ServiceSchema = createServiceSchema<{ userId: string }>(); * * // Define a simple stateless service * const mathService = ServiceSchema.define({ * add: Procedure.rpc({ * requestInit: Type.Object({ a: Type.Number(), b: Type.Number() }), * responseData: Type.Object({ result: Type.Number() }), * async handler({ ctx, reqInit }) { * return Ok({ result: reqInit.a + reqInit.b }); * } * }), * getUserId: Procedure.rpc({ * requestInit: Type.Object({}), * responseData: Type.Object({ id: Type.String() }), * async handler(ctx) { * return Ok({ id: ctx.userId }); * } * }), * }); * ``` * * There are two main ways to define services with the returned ServiceSchema class: * * 1. **ServiceSchema.define()** - Takes a configuration and procedures directly. * Use this for smaller services or when you want to define everything in one place. * * 2. **ServiceSchema.scaffold()** - Creates a scaffold that can be used to define * procedures separately from the configuration. Use this for larger services or * when you want to organize procedures across multiple files. * * When defining procedures, always use the {@link Procedure} constructors to create them. */ declare function createServiceSchema(): { new >(config: ServiceConfiguration, procedures: Procedures): { /** * Factory function for creating a fresh state. */ readonly initializeState: (extendedContext: Context) => MaybeDisposable; /** * The procedures for this service. */ readonly procedures: Procedures; /** * Serializes this schema's procedures into a plain object that is JSON compatible. */ serialize(): SerializedServiceSchema; /** * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with * protocol v1. This is useful to be able to continue to generate schemas for older * clients as they are still supported. */ serializeV1Compat(): SerializedServiceSchemaProtocolv1; /** * Instantiates this schema into a {@link Service} object. * * You probably don't need this, usually the River server will handle this * for you. */ instantiate(extendedContext: Context): Service; }; /** * Creates a {@link ServiceScaffold}, which can be used to define procedures * that can then be merged into a {@link ServiceSchema}, via the scaffold's * `finalize` method. * * There are two patterns that work well with this method. The first is using * it to separate the definition of procedures from the definition of the * service's configuration: * ```ts * const MyServiceScaffold = ServiceSchema.scaffold({ * initializeState: () => ({ count: 0 }), * }); * * const incrementProcedures = MyServiceScaffold.procedures({ * increment: Procedure.rpc({ * requestInit: Type.Object({ amount: Type.Number() }), * responseData: Type.Object({ current: Type.Number() }), * async handler({ ctx, reqInit }) { * ctx.state.count += reqInit.amount; * return Ok({ current: ctx.state.count }); * } * }), * }) * * const MyService = MyServiceScaffold.finalize({ * ...incrementProcedures, * // you can also directly define procedures here * }); * ``` * This might be really handy if you have a very large service and you're * wanting to split it over multiple files. You can define the scaffold * in one file, and then import that scaffold in other files where you * define procedures - and then finally import the scaffolds and your * procedure objects in a final file where you finalize the scaffold into * a service schema. * * The other way is to use it like in a builder pattern: * ```ts * const MyService = ServiceSchema * .scaffold({ initializeState: () => ({ count: 0 }) }) * .finalize({ * increment: Procedure.rpc({ * requestInit: Type.Object({ amount: Type.Number() }), * responseData: Type.Object({ current: Type.Number() }), * async handler({ ctx, reqInit }) { * ctx.state.count += reqInit.amount; * return Ok({ current: ctx.state.count }); * } * }), * }) * ``` * Depending on your preferences, this may be a more appealing way to define * a schema versus using the {@link ServiceSchema.define} method. */ scaffold(config: ServiceConfiguration): ServiceScaffold; /** * Creates a new {@link ServiceSchema} with the given configuration and procedures. * * All procedures must be created with the {@link Procedure} constructors. * * NOTE: There is an overload that lets you just provide the procedures alone if your * service has no state. * * @param config - The configuration for this service. * @param procedures - The procedures for this service. * * @example * ``` * const service = ServiceSchema.define( * { initializeState: () => ({ count: 0 }) }, * { * increment: Procedure.rpc({ * requestInit: Type.Object({ amount: Type.Number() }), * responseData: Type.Object({ current: Type.Number() }), * async handler({ ctx, reqInit }) { * ctx.state.count += reqInit.amount; * return Ok({ current: ctx.state.count }); * } * }), * }, * ); * ``` */ define>(config: ServiceConfiguration, procedures: Procedures_1): { /** * Factory function for creating a fresh state. */ readonly initializeState: (extendedContext: Context) => MaybeDisposable; /** * The procedures for this service. */ readonly procedures: { [K in keyof Procedures_1]: Unbranded; }; /** * Serializes this schema's procedures into a plain object that is JSON compatible. */ serialize(): SerializedServiceSchema; /** * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with * protocol v1. This is useful to be able to continue to generate schemas for older * clients as they are still supported. */ serializeV1Compat(): SerializedServiceSchemaProtocolv1; /** * Instantiates this schema into a {@link Service} object. * * You probably don't need this, usually the River server will handle this * for you. */ instantiate(extendedContext: Context): Service; }>; }; /** * Creates a new {@link ServiceSchema} with the given configuration and procedures. * * All procedures must be created with the {@link Procedure} constructors. * * NOTE: There is an overload that lets you just provide the procedures alone if your * service has no state. * * @param config - The configuration for this service. * @param procedures - The procedures for this service. * * @example * ``` * const service = ServiceSchema.define( * { initializeState: () => ({ count: 0 }) }, * { * increment: Procedure.rpc({ * requestInit: Type.Object({ amount: Type.Number() }), * responseData: Type.Object({ current: Type.Number() }), * async handler({ ctx, reqInit }) { * ctx.state.count += reqInit.amount; * return Ok({ current: ctx.state.count }); * } * }), * }, * ); * ``` */ define>(procedures: Procedures_2): { /** * Factory function for creating a fresh state. */ readonly initializeState: (extendedContext: Context) => MaybeDisposable; /** * The procedures for this service. */ readonly procedures: { [K_1 in keyof Procedures_2]: Unbranded; }; /** * Serializes this schema's procedures into a plain object that is JSON compatible. */ serialize(): SerializedServiceSchema; /** * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with * protocol v1. This is useful to be able to continue to generate schemas for older * clients as they are still supported. */ serializeV1Compat(): SerializedServiceSchemaProtocolv1; /** * Instantiates this schema into a {@link Service} object. * * You probably don't need this, usually the River server will handle this * for you. */ instantiate(extendedContext: Context): Service; }>; }; }; /** * A scaffold for defining a service's procedures. * * @see {@link ServiceSchema.scaffold} */ declare class ServiceScaffold { /** * The configuration for this service. */ protected readonly config: ServiceConfiguration; /** * @param config - The configuration for this service. */ constructor(config: ServiceConfiguration); /** * Define procedures for this service. Use the {@link Procedure} constructors * to create them. This returns the procedures object, which can then be * passed to {@link ServiceSchema.finalize} to create a {@link ServiceSchema}. * * @example * ``` * const myProcedures = MyServiceScaffold.procedures({ * myRPC: Procedure.rpc({ * // ... * }), * }); * * const MyService = MyServiceScaffold.finalize({ * ...myProcedures, * }); * ``` * * @param procedures - The procedures for this service. */ procedures>(procedures: T): T; /** * Finalizes the scaffold into a {@link ServiceSchema}. This is where you * provide the service's procedures and get a {@link ServiceSchema} in return. * * You can directly define procedures here, or you can define them separately * with the {@link ServiceScaffold.procedures} method, and then pass them here. * * @example * ``` * const MyService = MyServiceScaffold.finalize({ * myRPC: Procedure.rpc({ * // ... * }), * // e.g. from the procedures method * ...myOtherProcedures, * }); * ``` */ finalize>(procedures: T): { /** * Factory function for creating a fresh state. */ readonly initializeState: (extendedContext: Context) => MaybeDisposable; /** * The procedures for this service. */ readonly procedures: { [K in keyof T]: Unbranded; }; /** * Serializes this schema's procedures into a plain object that is JSON compatible. */ serialize(): SerializedServiceSchema; /** * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with * protocol v1. This is useful to be able to continue to generate schemas for older * clients as they are still supported. */ serializeV1Compat(): SerializedServiceSchemaProtocolv1; /** * Instantiates this schema into a {@link Service} object. * * You probably don't need this, usually the River server will handle this * for you. */ instantiate(extendedContext: Context): Service; }>; }; } export { serializeSchema as $, type AnyServiceSchemaMap as A, type BaseErrorSchemaType as B, CANCEL_CODE as C, type SerializedProcedureSchemaProtocolv1 as D, Err as E, type SerializedServerSchema as F, type SerializedServerSchemaProtocolv1 as G, type SerializedServiceSchema as H, type InstantiatedServiceSchemaMap as I, type SerializedServiceSchemaProtocolv1 as J, type Service as K, type ServiceConfiguration as L, type MaybeDisposable as M, type StreamProcedure as N, Ok as O, type ProcedureHandlerContext as P, type SubscriptionProcedure as Q, type RpcProcedure as R, type SerializedProcedureSchema as S, UNEXPECTED_DISCONNECT_CODE as T, UNCAUGHT_ERROR_CODE as U, type UploadProcedure as V, type ValidProcType as W, type Writable as X, createClient as Y, createServiceSchema as Z, flattenErrorType as _, type PayloadType as a, serializeSchemaV1Compat as a0, type ReadableIterator as a1, type ErrorPayload as a2, type AnyProcedure as b, type CallOptions as c, type Client as d, type ClientOptions as e, type ErrResult as f, INVALID_REQUEST_CODE as g, type OkResult as h, type ProcErrors as i, type ProcHandler as j, type ProcInit as k, type ProcRequest as l, type ProcResponse as m, type ProcType as n, Procedure as o, type ProcedureErrorSchemaType as p, type ProcedureMap as q, ReadableImpl as r, type Readable as s, ReadableBrokenError as t, type ReadableResult as u, ReaderErrorSchema as v, type ResponseData as w, type Result as x, type ResultUnwrapErr as y, type ResultUnwrapOk as z };