@orpc/client
Advanced tools
| import { Promisable, OrderablePlugin, Interceptor } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { C as ClientContext, a as ClientOptions, A as AnyORPCError, b as ClientLink } from './client.l_EYklFG.mjs'; | ||
| type StandardLinkCodecDecodedResponse = { | ||
| kind: 'output'; | ||
| output: unknown; | ||
| } | { | ||
| kind: 'error'; | ||
| error: AnyORPCError; | ||
| }; | ||
| interface StandardLinkCodec<T extends ClientContext> { | ||
| encodeInput(input: unknown, path: string[], options: ClientOptions<T>): Promisable<StandardRequest>; | ||
| decodeResponse(response: StandardLazyResponse, path: string[], options: ClientOptions<T>): Promisable<StandardLinkCodecDecodedResponse>; | ||
| } | ||
| interface StandardLinkPlugin<T extends ClientContext> extends OrderablePlugin { | ||
| /** | ||
| * Initializes the plugin and returns new link options. | ||
| * Called once per plugin instance during composition. | ||
| * | ||
| * This method allows plugins to wrap, extend, or transform link options | ||
| * such as interceptors, or configuration. | ||
| * | ||
| * @param options - The current link options from previous plugins or base configuration | ||
| * @returns Transformed link options with plugin's modifications applied | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * init(options) { | ||
| * return { | ||
| * ...options, | ||
| * interceptors: [...(options.interceptors || []), myInterceptor] | ||
| * } | ||
| * } | ||
| * ``` | ||
| */ | ||
| init?(options: StandardLinkOptions<T>): StandardLinkOptions<T>; | ||
| } | ||
| declare class CompositeStandardLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> { | ||
| name: string; | ||
| protected readonly plugins: StandardLinkPlugin<T>[]; | ||
| constructor(plugins?: StandardLinkPlugin<T>[]); | ||
| init(options: StandardLinkOptions<T>): StandardLinkOptions<T>; | ||
| } | ||
| /** | ||
| * Handles the transport layer for sending requests and receiving responses. | ||
| * | ||
| * Implementations are responsible for the actual network communication, | ||
| * such as HTTP fetch, WebSocket, or other transport mechanisms. | ||
| */ | ||
| interface StandardLinkTransport<T extends ClientContext> { | ||
| /** | ||
| * @throws Transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| send(request: StandardRequest, path: string[], options: ClientOptions<T>): Promise<StandardLazyResponse>; | ||
| } | ||
| interface StandardLinkInterceptorOptions<T extends ClientContext> extends ClientOptions<T> { | ||
| path: string[]; | ||
| input: unknown; | ||
| } | ||
| type StandardLinkInterceptor<T extends ClientContext> = Interceptor<StandardLinkInterceptorOptions<T>, Promise<unknown>>; | ||
| interface StandardLinkTransportInterceptorOptions<T extends ClientContext> extends ClientOptions<T> { | ||
| path: string[]; | ||
| request: StandardRequest; | ||
| } | ||
| type StandardLinkTransportInterceptor<T extends ClientContext> = Interceptor<StandardLinkTransportInterceptorOptions<T>, Promise<StandardLazyResponse>>; | ||
| interface StandardLinkOptions<T extends ClientContext> { | ||
| /** | ||
| * Interceptors that execute around the entire call, including transport and codec. | ||
| * Useful for error handling, logging, metrics, ... | ||
| */ | ||
| interceptors?: StandardLinkInterceptor<T>[]; | ||
| /** | ||
| * Interceptors that execute around the transport layer, after encoding and before decoding. | ||
| * Useful for modifying the request or response, adding transport-level logging, ... | ||
| */ | ||
| transportInterceptors?: StandardLinkTransportInterceptor<T>[]; | ||
| plugins?: StandardLinkPlugin<T>[]; | ||
| } | ||
| declare class StandardLink<T extends ClientContext> implements ClientLink<T> { | ||
| private readonly codec; | ||
| private readonly transport; | ||
| private readonly interceptors; | ||
| private readonly transportInterceptors; | ||
| constructor(codec: StandardLinkCodec<T>, transport: StandardLinkTransport<T>, options?: StandardLinkOptions<T>); | ||
| /** | ||
| * @throws ORPCError, transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| call(path: string[], input: unknown, options: ClientOptions<T>): Promise<unknown>; | ||
| } | ||
| export { CompositeStandardLinkPlugin as C, StandardLink as a }; | ||
| export type { StandardLinkTransport as S, StandardLinkOptions as b, StandardLinkPlugin as c, StandardLinkTransportInterceptorOptions as d, StandardLinkInterceptorOptions as e, StandardLinkCodec as f, StandardLinkCodecDecodedResponse as g, StandardLinkInterceptor as h, StandardLinkTransportInterceptor as i }; |
| import { Promisable, OrderablePlugin, Interceptor } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { C as ClientContext, a as ClientOptions, A as AnyORPCError, b as ClientLink } from './client.l_EYklFG.js'; | ||
| type StandardLinkCodecDecodedResponse = { | ||
| kind: 'output'; | ||
| output: unknown; | ||
| } | { | ||
| kind: 'error'; | ||
| error: AnyORPCError; | ||
| }; | ||
| interface StandardLinkCodec<T extends ClientContext> { | ||
| encodeInput(input: unknown, path: string[], options: ClientOptions<T>): Promisable<StandardRequest>; | ||
| decodeResponse(response: StandardLazyResponse, path: string[], options: ClientOptions<T>): Promisable<StandardLinkCodecDecodedResponse>; | ||
| } | ||
| interface StandardLinkPlugin<T extends ClientContext> extends OrderablePlugin { | ||
| /** | ||
| * Initializes the plugin and returns new link options. | ||
| * Called once per plugin instance during composition. | ||
| * | ||
| * This method allows plugins to wrap, extend, or transform link options | ||
| * such as interceptors, or configuration. | ||
| * | ||
| * @param options - The current link options from previous plugins or base configuration | ||
| * @returns Transformed link options with plugin's modifications applied | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * init(options) { | ||
| * return { | ||
| * ...options, | ||
| * interceptors: [...(options.interceptors || []), myInterceptor] | ||
| * } | ||
| * } | ||
| * ``` | ||
| */ | ||
| init?(options: StandardLinkOptions<T>): StandardLinkOptions<T>; | ||
| } | ||
| declare class CompositeStandardLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> { | ||
| name: string; | ||
| protected readonly plugins: StandardLinkPlugin<T>[]; | ||
| constructor(plugins?: StandardLinkPlugin<T>[]); | ||
| init(options: StandardLinkOptions<T>): StandardLinkOptions<T>; | ||
| } | ||
| /** | ||
| * Handles the transport layer for sending requests and receiving responses. | ||
| * | ||
| * Implementations are responsible for the actual network communication, | ||
| * such as HTTP fetch, WebSocket, or other transport mechanisms. | ||
| */ | ||
| interface StandardLinkTransport<T extends ClientContext> { | ||
| /** | ||
| * @throws Transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| send(request: StandardRequest, path: string[], options: ClientOptions<T>): Promise<StandardLazyResponse>; | ||
| } | ||
| interface StandardLinkInterceptorOptions<T extends ClientContext> extends ClientOptions<T> { | ||
| path: string[]; | ||
| input: unknown; | ||
| } | ||
| type StandardLinkInterceptor<T extends ClientContext> = Interceptor<StandardLinkInterceptorOptions<T>, Promise<unknown>>; | ||
| interface StandardLinkTransportInterceptorOptions<T extends ClientContext> extends ClientOptions<T> { | ||
| path: string[]; | ||
| request: StandardRequest; | ||
| } | ||
| type StandardLinkTransportInterceptor<T extends ClientContext> = Interceptor<StandardLinkTransportInterceptorOptions<T>, Promise<StandardLazyResponse>>; | ||
| interface StandardLinkOptions<T extends ClientContext> { | ||
| /** | ||
| * Interceptors that execute around the entire call, including transport and codec. | ||
| * Useful for error handling, logging, metrics, ... | ||
| */ | ||
| interceptors?: StandardLinkInterceptor<T>[]; | ||
| /** | ||
| * Interceptors that execute around the transport layer, after encoding and before decoding. | ||
| * Useful for modifying the request or response, adding transport-level logging, ... | ||
| */ | ||
| transportInterceptors?: StandardLinkTransportInterceptor<T>[]; | ||
| plugins?: StandardLinkPlugin<T>[]; | ||
| } | ||
| declare class StandardLink<T extends ClientContext> implements ClientLink<T> { | ||
| private readonly codec; | ||
| private readonly transport; | ||
| private readonly interceptors; | ||
| private readonly transportInterceptors; | ||
| constructor(codec: StandardLinkCodec<T>, transport: StandardLinkTransport<T>, options?: StandardLinkOptions<T>); | ||
| /** | ||
| * @throws ORPCError, transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| call(path: string[], input: unknown, options: ClientOptions<T>): Promise<unknown>; | ||
| } | ||
| export { CompositeStandardLinkPlugin as C, StandardLink as a }; | ||
| export type { StandardLinkTransport as S, StandardLinkOptions as b, StandardLinkPlugin as c, StandardLinkTransportInterceptorOptions as d, StandardLinkInterceptorOptions as e, StandardLinkCodec as f, StandardLinkCodecDecodedResponse as g, StandardLinkInterceptor as h, StandardLinkTransportInterceptor as i }; |
| import { isPlainObject, wrapAsyncIterator, isTypescriptObject, NullProtoObj, isAsyncIteratorObject, stringifyJSON } from '@orpc/shared'; | ||
| import { getEventMeta, withEventMeta, ErrorEvent } from '@standardserver/core'; | ||
| import { O as ORPCError } from './client.CPcOxSex.mjs'; | ||
| function isInferableError(error) { | ||
| return error instanceof ORPCError && error.inferable; | ||
| } | ||
| function toORPCError(error) { | ||
| return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", { cause: error }); | ||
| } | ||
| function isORPCErrorJson(json) { | ||
| if (!isPlainObject(json)) { | ||
| return false; | ||
| } | ||
| const validKeys = ["defined", "inferable", "code", "message", "data"]; | ||
| if (Object.keys(json).some((k) => !validKeys.includes(k))) { | ||
| return false; | ||
| } | ||
| return "defined" in json && typeof json.defined === "boolean" && "inferable" in json && typeof json.inferable === "boolean" && "code" in json && typeof json.code === "string" && "message" in json && typeof json.message === "string"; | ||
| } | ||
| function createORPCErrorFromJson(json, options = {}) { | ||
| const error = new ORPCError(json.code, { | ||
| ...json, | ||
| ...options | ||
| }); | ||
| error.defined = json.defined; | ||
| error.inferable = json.inferable; | ||
| return error; | ||
| } | ||
| function cloneORPCError(error) { | ||
| const cloned = new ORPCError(error.code, { | ||
| message: error.message, | ||
| data: error.data, | ||
| cause: error.cause | ||
| }); | ||
| Object.setPrototypeOf(cloned, Object.getPrototypeOf(error)); | ||
| Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(error)); | ||
| cloned.stack = error.stack; | ||
| return cloned; | ||
| } | ||
| function wrapAsyncIteratorPreservingEventMeta(iterator, { mapResult, mapError, ...rest }) { | ||
| return wrapAsyncIterator(iterator, { | ||
| ...rest, | ||
| mapResult: mapResult && (async (result) => { | ||
| const mapped = await mapResult(result); | ||
| if (mapped.value !== result.value) { | ||
| const meta = getEventMeta(result.value); | ||
| if (meta && isTypescriptObject(mapped.value)) { | ||
| return { done: mapped.done, value: withEventMeta(mapped.value, meta) }; | ||
| } | ||
| } | ||
| return mapped; | ||
| }), | ||
| mapError: mapError && (async (error) => { | ||
| const mapped = await mapError(error); | ||
| if (mapped !== error) { | ||
| const meta = getEventMeta(error); | ||
| if (meta && isTypescriptObject(mapped)) { | ||
| return withEventMeta(mapped, meta); | ||
| } | ||
| } | ||
| return mapped; | ||
| }) | ||
| }); | ||
| } | ||
| const REGEX_STRING_PATTERN = /^\/([\s\S]*)\/([a-z]*)$/; | ||
| const DEFAULT_RPC_JSON_SERIALIZER_HANDLERS = { | ||
| undefined: { | ||
| condition(data) { | ||
| return data === void 0; | ||
| }, | ||
| serialize() { | ||
| return null; | ||
| }, | ||
| deserialize() { | ||
| return void 0; | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| bigint: { | ||
| condition(data) { | ||
| return typeof data === "bigint"; | ||
| }, | ||
| serialize(data) { | ||
| return data.toString(); | ||
| }, | ||
| deserialize(serialized) { | ||
| return BigInt(serialized); | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| date: { | ||
| condition(data) { | ||
| return data instanceof Date; | ||
| }, | ||
| serialize(data) { | ||
| if (Number.isNaN(data.getTime())) { | ||
| return null; | ||
| } | ||
| return data.toISOString(); | ||
| }, | ||
| deserialize(serialized) { | ||
| return new Date(serialized ?? "Invalid Date"); | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| nan: { | ||
| condition(data) { | ||
| return typeof data === "number" && Number.isNaN(data); | ||
| }, | ||
| serialize() { | ||
| return null; | ||
| }, | ||
| deserialize() { | ||
| return Number.NaN; | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| url: { | ||
| condition(data) { | ||
| return data instanceof URL; | ||
| }, | ||
| serialize(data) { | ||
| return data.toString(); | ||
| }, | ||
| deserialize(serialized) { | ||
| return new URL(serialized); | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| regexp: { | ||
| condition(data) { | ||
| return data instanceof RegExp; | ||
| }, | ||
| serialize(data) { | ||
| return data.toString(); | ||
| }, | ||
| deserialize(serialized) { | ||
| const [, pattern, flags] = serialized.match(REGEX_STRING_PATTERN); | ||
| return new RegExp(pattern, flags); | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| set: { | ||
| condition(data) { | ||
| return data instanceof Set; | ||
| }, | ||
| serialize(data) { | ||
| return Array.from(data); | ||
| }, | ||
| deserialize(serialized) { | ||
| return new Set(serialized); | ||
| } | ||
| }, | ||
| map: { | ||
| condition(data) { | ||
| return data instanceof Map; | ||
| }, | ||
| serialize(data) { | ||
| return Array.from(data.entries()); | ||
| }, | ||
| deserialize(serialized) { | ||
| return new Map(serialized); | ||
| } | ||
| } | ||
| }; | ||
| class RPCJsonSerializer { | ||
| handlers; | ||
| inlineBuiltInHandlers; | ||
| handlerEntries; | ||
| omitUndefinedProperties; | ||
| constructor(options = {}) { | ||
| this.omitUndefinedProperties = options.omitUndefinedProperties !== false; | ||
| this.handlers = Object.assign(new NullProtoObj(), DEFAULT_RPC_JSON_SERIALIZER_HANDLERS); | ||
| const customHandlers = options.handlers; | ||
| if (customHandlers === void 0) { | ||
| this.inlineBuiltInHandlers = true; | ||
| return; | ||
| } | ||
| let inlineBuiltInHandlers = true; | ||
| let handlerEntries = []; | ||
| for (const key in customHandlers) { | ||
| const handler = customHandlers[key]; | ||
| this.handlers[key] = handler; | ||
| if (inlineBuiltInHandlers && key in DEFAULT_RPC_JSON_SERIALIZER_HANDLERS) { | ||
| inlineBuiltInHandlers = false; | ||
| } | ||
| if (inlineBuiltInHandlers && handler !== void 0) { | ||
| handlerEntries.push([key, handler]); | ||
| } | ||
| } | ||
| if (!inlineBuiltInHandlers) { | ||
| handlerEntries = []; | ||
| for (const key in this.handlers) { | ||
| const handler = this.handlers[key]; | ||
| if (handler !== void 0) { | ||
| handlerEntries.push([key, handler]); | ||
| } | ||
| } | ||
| } | ||
| this.inlineBuiltInHandlers = inlineBuiltInHandlers; | ||
| this.handlerEntries = handlerEntries; | ||
| } | ||
| serialize(data) { | ||
| let meta = []; | ||
| const maps = []; | ||
| const blobs = []; | ||
| const json = this.serializeValue(data, [], meta, maps, blobs); | ||
| meta = meta.length === 0 ? void 0 : meta; | ||
| if (maps.length === 0) { | ||
| return { json, meta }; | ||
| } | ||
| return { json, meta, maps, blobs }; | ||
| } | ||
| /** | ||
| * `segments` is a shared mutable stack (push/pop while walking), | ||
| * so it must be copied before being stored in `meta` or `maps`. | ||
| */ | ||
| serializeValue(data, segments, meta, maps, blobs) { | ||
| if (this.inlineBuiltInHandlers) { | ||
| switch (typeof data) { | ||
| case "string": | ||
| case "boolean": | ||
| return data; | ||
| case "number": | ||
| if (Number.isNaN(data)) { | ||
| meta.push(["nan", ...segments]); | ||
| return null; | ||
| } | ||
| return data; | ||
| case "undefined": | ||
| meta.push(["undefined", ...segments]); | ||
| return null; | ||
| case "bigint": | ||
| meta.push(["bigint", ...segments]); | ||
| return data.toString(); | ||
| case "object": { | ||
| if (data === null) { | ||
| return data; | ||
| } | ||
| if (data instanceof Date) { | ||
| meta.push(["date", ...segments]); | ||
| return Number.isNaN(data.getTime()) ? null : data.toISOString(); | ||
| } | ||
| if (data instanceof URL) { | ||
| meta.push(["url", ...segments]); | ||
| return data.toString(); | ||
| } | ||
| if (data instanceof RegExp) { | ||
| meta.push(["regexp", ...segments]); | ||
| return data.toString(); | ||
| } | ||
| if (data instanceof Set) { | ||
| const result = this.serializeValue(Array.from(data), segments, meta, maps, blobs); | ||
| meta.push(["set", ...segments]); | ||
| return result; | ||
| } | ||
| if (data instanceof Map) { | ||
| const result = this.serializeValue(Array.from(data.entries()), segments, meta, maps, blobs); | ||
| meta.push(["map", ...segments]); | ||
| return result; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| const handlerEntries = this.handlerEntries; | ||
| if (handlerEntries) { | ||
| for (let i = 0; i < handlerEntries.length; i++) { | ||
| const entry = handlerEntries[i]; | ||
| const handler = entry[1]; | ||
| if (handler.condition(data)) { | ||
| const serialized = handler.serialize(data); | ||
| if (handler.isTerminal) { | ||
| meta.push([entry[0], ...segments]); | ||
| if (serialized instanceof Blob) { | ||
| maps.push(segments.slice()); | ||
| blobs.push(serialized); | ||
| } | ||
| return serialized; | ||
| } | ||
| const result = this.serializeValue(serialized, segments, meta, maps, blobs); | ||
| meta.push([entry[0], ...segments]); | ||
| return result; | ||
| } | ||
| } | ||
| } | ||
| if (data instanceof Blob) { | ||
| maps.push(segments.slice()); | ||
| blobs.push(data); | ||
| return data; | ||
| } | ||
| if (Array.isArray(data)) { | ||
| const json = []; | ||
| for (let i = 0; i < data.length; i++) { | ||
| segments.push(i); | ||
| json.push(this.serializeValue(data[i], segments, meta, maps, blobs)); | ||
| segments.pop(); | ||
| } | ||
| return json; | ||
| } | ||
| if (isPlainObject(data)) { | ||
| const json = new NullProtoObj(); | ||
| for (const k in data) { | ||
| const v = data[k]; | ||
| if (k === "toJSON" && typeof v === "function") { | ||
| continue; | ||
| } | ||
| if (v === void 0 && this.omitUndefinedProperties) { | ||
| continue; | ||
| } | ||
| segments.push(k); | ||
| json[k] = this.serializeValue(v, segments, meta, maps, blobs); | ||
| segments.pop(); | ||
| } | ||
| return json; | ||
| } | ||
| return data; | ||
| } | ||
| deserialize(serialized) { | ||
| const ref = { data: serialized.json }; | ||
| if (serialized.blobs?.length) { | ||
| for (let i = 0; i < serialized.maps.length; i++) { | ||
| const segments = serialized.maps[i]; | ||
| let currentRef = ref; | ||
| let preSegment = "data"; | ||
| for (let j = 0; j < segments.length; j++) { | ||
| currentRef = currentRef[preSegment]; | ||
| preSegment = segments[j]; | ||
| if (!Object.hasOwn(currentRef, preSegment)) { | ||
| throw new Error(`Security error: Invalid serialized data. Segment "${preSegment}" does not exist.`); | ||
| } | ||
| } | ||
| currentRef[preSegment] = serialized.blobs[i]; | ||
| } | ||
| } | ||
| if (serialized.meta) { | ||
| for (const item of serialized.meta) { | ||
| const type = item[0]; | ||
| let currentRef = ref; | ||
| let preSegment = "data"; | ||
| for (let i = 1; i < item.length; i++) { | ||
| currentRef = currentRef[preSegment]; | ||
| preSegment = item[i]; | ||
| if (!Object.hasOwn(currentRef, preSegment)) { | ||
| throw new Error(`Security error: Invalid serialized data. Segment "${preSegment}" does not exist.`); | ||
| } | ||
| } | ||
| currentRef[preSegment] = this.handlers[type].deserialize(currentRef[preSegment]); | ||
| } | ||
| } | ||
| return ref.data; | ||
| } | ||
| } | ||
| class RPCSerializer { | ||
| jsonSerializer; | ||
| defaultSerializeOptions; | ||
| constructor(options = {}) { | ||
| this.jsonSerializer = new RPCJsonSerializer(options); | ||
| this.defaultSerializeOptions = options.serialize; | ||
| } | ||
| serialize(data, options = {}) { | ||
| if (data === void 0 || data instanceof ReadableStream || data instanceof Blob) { | ||
| return data; | ||
| } | ||
| if (isAsyncIteratorObject(data)) { | ||
| return wrapAsyncIteratorPreservingEventMeta(data, { | ||
| mapResult: (result) => { | ||
| if (result.value === void 0) { | ||
| return result; | ||
| } | ||
| return { done: result.done, value: this.serializeValue(result.value, false) }; | ||
| }, | ||
| mapError: (e) => new ErrorEvent( | ||
| this.serializeValue(toORPCError(e).toJSON(), false), | ||
| { cause: e } | ||
| ) | ||
| }); | ||
| } | ||
| const useFormDataForBlobs = options.useFormDataForBlobFields ?? this.defaultSerializeOptions?.useFormDataForBlobFields ?? true; | ||
| return this.serializeValue(data, useFormDataForBlobs); | ||
| } | ||
| serializeValue(data, useFormDataForBlobs) { | ||
| const { json, meta, maps, blobs } = this.jsonSerializer.serialize(data); | ||
| if (!useFormDataForBlobs || !blobs?.length) { | ||
| return { json, meta }; | ||
| } | ||
| const form = new FormData(); | ||
| form.set("data", stringifyJSON({ json, meta, maps })); | ||
| blobs.forEach((blob, i) => { | ||
| form.set(i.toString(), blob); | ||
| }); | ||
| return form; | ||
| } | ||
| deserialize(data) { | ||
| if (data === void 0 || data instanceof ReadableStream || data instanceof Blob) { | ||
| return data; | ||
| } | ||
| if (isAsyncIteratorObject(data)) { | ||
| return wrapAsyncIteratorPreservingEventMeta(data, { | ||
| mapResult: (result) => { | ||
| if (result.value === void 0) { | ||
| return result; | ||
| } | ||
| return { done: result.done, value: this.deserializeValue(result.value) }; | ||
| }, | ||
| mapError: (e) => { | ||
| if (!(e instanceof ErrorEvent)) { | ||
| return e; | ||
| } | ||
| const deserialized = this.deserializeValue(e.data); | ||
| if (isORPCErrorJson(deserialized)) { | ||
| return createORPCErrorFromJson(deserialized, { cause: e }); | ||
| } | ||
| return new ErrorEvent(deserialized, { cause: e }); | ||
| } | ||
| }); | ||
| } | ||
| return this.deserializeValue(data); | ||
| } | ||
| deserializeValue(data) { | ||
| if (!(data instanceof FormData)) { | ||
| return this.jsonSerializer.deserialize(data); | ||
| } | ||
| const serialized = JSON.parse(data.get("data")); | ||
| const blobs = []; | ||
| for (const [key, value] of data) { | ||
| if (value instanceof Blob) { | ||
| blobs[Number(key)] = value; | ||
| } | ||
| } | ||
| return this.jsonSerializer.deserialize({ ...serialized, blobs }); | ||
| } | ||
| } | ||
| export { RPCSerializer as R, isInferableError as a, RPCJsonSerializer as b, createORPCErrorFromJson as c, cloneORPCError as d, isORPCErrorJson as i, toORPCError as t, wrapAsyncIteratorPreservingEventMeta as w }; |
| import { PromiseWithError, Registry, MaybeOptionalOptions } from '@orpc/shared'; | ||
| interface ClientContext { | ||
| [key: PropertyKey]: any; | ||
| } | ||
| interface ClientOptions<T extends ClientContext> { | ||
| signal?: AbortSignal | undefined; | ||
| lastEventId?: string | undefined; | ||
| context: T; | ||
| } | ||
| type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (object extends T ? { | ||
| context?: T; | ||
| } : { | ||
| context: T; | ||
| }); | ||
| type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>]; | ||
| interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> { | ||
| (...rest: ClientRest<TClientContext, TInput>): PromiseWithError<TOutput, TError>; | ||
| } | ||
| type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | { | ||
| [k: string]: NestedClient<TClientContext>; | ||
| }; | ||
| type AnyNestedClient = NestedClient<any>; | ||
| /** | ||
| * Infers the **client context type** required by a client. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-context | Client-Side Clients - Infer Client Context} | ||
| */ | ||
| type InferClientContext<T extends AnyNestedClient> = T extends NestedClient<infer U> ? U : never; | ||
| interface ClientLink<TClientContext extends ClientContext> { | ||
| call: (path: string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>; | ||
| } | ||
| /** | ||
| * Recursively infers the **input types** from a client. | ||
| * | ||
| * Produces a nested map where each endpoint's input type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-inputs | Client-Side Clients - Infer Client Inputs} | ||
| */ | ||
| type InferClientInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientInputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **body input types** from a client. | ||
| * | ||
| * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted. | ||
| * Produces a nested map of body input types. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-inputs | Client-Side Clients - Infer Client Body Inputs} | ||
| */ | ||
| type InferClientBodyInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U extends { | ||
| body: infer UBody; | ||
| } ? UBody : U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyInputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **output types** from a client. | ||
| * | ||
| * Produces a nested map where each endpoint's output type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-outputs | Client-Side Clients - Infer Client Outputs} | ||
| */ | ||
| type InferClientOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientOutputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **body output types** from a client. | ||
| * | ||
| * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted. | ||
| * Produces a nested map of body output types. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-outputs | Client-Side Clients - Infer Client Body Outputs} | ||
| */ | ||
| type InferClientBodyOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U extends { | ||
| body: infer UBody; | ||
| } ? UBody : U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyOutputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors). | ||
| * | ||
| * Produces a nested map where each endpoint's error type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-errors | Client-Side Clients - Infer Client Errors} | ||
| */ | ||
| type InferClientErrors<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientErrors<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors). | ||
| * | ||
| * Useful when you want to handle all possible errors from any endpoint at once. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-error | Client-Side Clients - Infer Client Error} | ||
| */ | ||
| type InferClientError<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientError<T[K]> : never; | ||
| }[keyof T]; | ||
| /** | ||
| * Default mapping between common oRPC error codes and HTTP status codes. | ||
| * Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response} | ||
| * @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response} | ||
| */ | ||
| declare const COMMON_ERROR_STATUS_MAP: { | ||
| BAD_REQUEST: number; | ||
| UNAUTHORIZED: number; | ||
| PAYMENT_REQUIRED: number; | ||
| FORBIDDEN: number; | ||
| NOT_FOUND: number; | ||
| METHOD_NOT_SUPPORTED: number; | ||
| NOT_ACCEPTABLE: number; | ||
| TIMEOUT: number; | ||
| CONFLICT: number; | ||
| GONE: number; | ||
| PRECONDITION_FAILED: number; | ||
| PAYLOAD_TOO_LARGE: number; | ||
| UNSUPPORTED_MEDIA_TYPE: number; | ||
| UNPROCESSABLE_CONTENT: number; | ||
| PRECONDITION_REQUIRED: number; | ||
| TOO_MANY_REQUESTS: number; | ||
| CLIENT_CLOSED_REQUEST: number; | ||
| INTERNAL_SERVER_ERROR: number; | ||
| NOT_IMPLEMENTED: number; | ||
| BAD_GATEWAY: number; | ||
| SERVICE_UNAVAILABLE: number; | ||
| GATEWAY_TIMEOUT: number; | ||
| }; | ||
| type ORPCErrorCode = Registry extends { | ||
| ORPCErrorCode: infer T extends string; | ||
| } ? T : (keyof typeof COMMON_ERROR_STATUS_MAP) | (string & {}); | ||
| type ORPCErrorOptions<TData> = ErrorOptions & { | ||
| message?: string; | ||
| } & (undefined extends TData ? { | ||
| data?: TData; | ||
| } : { | ||
| data: TData; | ||
| }); | ||
| /** | ||
| * Typed error carrying a `code`, a `message`, and optional `data`. | ||
| * Throw it from handlers or middleware to produce typed error responses on the client. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class} | ||
| */ | ||
| declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error { | ||
| /** | ||
| * @remarks | ||
| * **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish | ||
| * an `ORPCError` instance from plain objects with a similar structure. | ||
| */ | ||
| readonly name: "ORPCError" & { | ||
| __branch: "ORPCError"; | ||
| }; | ||
| /** | ||
| * Indicates whether the error matches a definition in the procedure's `.errors` map. | ||
| */ | ||
| readonly defined: boolean; | ||
| /** | ||
| * Indicates whether the error's type is inferable at the TypeScript level. | ||
| * This is typically true when the error is explicitly defined or returned within a handler. | ||
| */ | ||
| readonly inferable: boolean; | ||
| code: TCode; | ||
| data: TData; | ||
| constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>); | ||
| toJSON(): ORPCErrorJSON<TCode, TData>; | ||
| /** | ||
| * Workaround for Next.js where different contexts use separate | ||
| * dependency graphs, causing multiple ORPCError constructors existing and breaking | ||
| * `instanceof` checks across contexts. | ||
| * | ||
| * This is particularly problematic with "Optimized SSR", where orpc-client | ||
| * executes in one context but is invoked from another. When an error is thrown | ||
| * in the execution context, `instanceof ORPCError` checks fail in the | ||
| * invocation context due to separate class constructors. | ||
| * | ||
| * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue. | ||
| */ | ||
| static [Symbol.hasInstance](instance: unknown): boolean; | ||
| } | ||
| interface ORPCErrorJSON<TCode extends string, TData> extends Pick<ORPCError<TCode, TData>, 'code' | 'message' | 'data'> { | ||
| /** | ||
| * remove readonly | ||
| */ | ||
| defined: boolean; | ||
| /** | ||
| * remove readonly | ||
| */ | ||
| inferable: boolean; | ||
| } | ||
| type AnyORPCError = ORPCError<any, any>; | ||
| type AnyORPCErrorJSON = ORPCErrorJSON<any, any>; | ||
| export { ORPCError as h, COMMON_ERROR_STATUS_MAP as j }; | ||
| export type { AnyORPCError as A, ClientContext as C, FriendlyClientOptions as F, InferClientContext as I, NestedClient as N, ORPCErrorCode as O, ClientOptions as a, ClientLink as b, AnyNestedClient as c, InferClientError as d, Client as e, ClientRest as f, ORPCErrorJSON as g, AnyORPCErrorJSON as i, InferClientBodyInputs as k, InferClientBodyOutputs as l, InferClientErrors as m, InferClientInputs as n, InferClientOutputs as o, ORPCErrorOptions as p }; |
| import { PromiseWithError, Registry, MaybeOptionalOptions } from '@orpc/shared'; | ||
| interface ClientContext { | ||
| [key: PropertyKey]: any; | ||
| } | ||
| interface ClientOptions<T extends ClientContext> { | ||
| signal?: AbortSignal | undefined; | ||
| lastEventId?: string | undefined; | ||
| context: T; | ||
| } | ||
| type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (object extends T ? { | ||
| context?: T; | ||
| } : { | ||
| context: T; | ||
| }); | ||
| type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>]; | ||
| interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> { | ||
| (...rest: ClientRest<TClientContext, TInput>): PromiseWithError<TOutput, TError>; | ||
| } | ||
| type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | { | ||
| [k: string]: NestedClient<TClientContext>; | ||
| }; | ||
| type AnyNestedClient = NestedClient<any>; | ||
| /** | ||
| * Infers the **client context type** required by a client. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-context | Client-Side Clients - Infer Client Context} | ||
| */ | ||
| type InferClientContext<T extends AnyNestedClient> = T extends NestedClient<infer U> ? U : never; | ||
| interface ClientLink<TClientContext extends ClientContext> { | ||
| call: (path: string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>; | ||
| } | ||
| /** | ||
| * Recursively infers the **input types** from a client. | ||
| * | ||
| * Produces a nested map where each endpoint's input type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-inputs | Client-Side Clients - Infer Client Inputs} | ||
| */ | ||
| type InferClientInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientInputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **body input types** from a client. | ||
| * | ||
| * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted. | ||
| * Produces a nested map of body input types. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-inputs | Client-Side Clients - Infer Client Body Inputs} | ||
| */ | ||
| type InferClientBodyInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U extends { | ||
| body: infer UBody; | ||
| } ? UBody : U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyInputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **output types** from a client. | ||
| * | ||
| * Produces a nested map where each endpoint's output type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-outputs | Client-Side Clients - Infer Client Outputs} | ||
| */ | ||
| type InferClientOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientOutputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **body output types** from a client. | ||
| * | ||
| * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted. | ||
| * Produces a nested map of body output types. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-outputs | Client-Side Clients - Infer Client Body Outputs} | ||
| */ | ||
| type InferClientBodyOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U extends { | ||
| body: infer UBody; | ||
| } ? UBody : U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyOutputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors). | ||
| * | ||
| * Produces a nested map where each endpoint's error type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-errors | Client-Side Clients - Infer Client Errors} | ||
| */ | ||
| type InferClientErrors<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientErrors<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors). | ||
| * | ||
| * Useful when you want to handle all possible errors from any endpoint at once. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-error | Client-Side Clients - Infer Client Error} | ||
| */ | ||
| type InferClientError<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientError<T[K]> : never; | ||
| }[keyof T]; | ||
| /** | ||
| * Default mapping between common oRPC error codes and HTTP status codes. | ||
| * Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response} | ||
| * @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response} | ||
| */ | ||
| declare const COMMON_ERROR_STATUS_MAP: { | ||
| BAD_REQUEST: number; | ||
| UNAUTHORIZED: number; | ||
| PAYMENT_REQUIRED: number; | ||
| FORBIDDEN: number; | ||
| NOT_FOUND: number; | ||
| METHOD_NOT_SUPPORTED: number; | ||
| NOT_ACCEPTABLE: number; | ||
| TIMEOUT: number; | ||
| CONFLICT: number; | ||
| GONE: number; | ||
| PRECONDITION_FAILED: number; | ||
| PAYLOAD_TOO_LARGE: number; | ||
| UNSUPPORTED_MEDIA_TYPE: number; | ||
| UNPROCESSABLE_CONTENT: number; | ||
| PRECONDITION_REQUIRED: number; | ||
| TOO_MANY_REQUESTS: number; | ||
| CLIENT_CLOSED_REQUEST: number; | ||
| INTERNAL_SERVER_ERROR: number; | ||
| NOT_IMPLEMENTED: number; | ||
| BAD_GATEWAY: number; | ||
| SERVICE_UNAVAILABLE: number; | ||
| GATEWAY_TIMEOUT: number; | ||
| }; | ||
| type ORPCErrorCode = Registry extends { | ||
| ORPCErrorCode: infer T extends string; | ||
| } ? T : (keyof typeof COMMON_ERROR_STATUS_MAP) | (string & {}); | ||
| type ORPCErrorOptions<TData> = ErrorOptions & { | ||
| message?: string; | ||
| } & (undefined extends TData ? { | ||
| data?: TData; | ||
| } : { | ||
| data: TData; | ||
| }); | ||
| /** | ||
| * Typed error carrying a `code`, a `message`, and optional `data`. | ||
| * Throw it from handlers or middleware to produce typed error responses on the client. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class} | ||
| */ | ||
| declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error { | ||
| /** | ||
| * @remarks | ||
| * **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish | ||
| * an `ORPCError` instance from plain objects with a similar structure. | ||
| */ | ||
| readonly name: "ORPCError" & { | ||
| __branch: "ORPCError"; | ||
| }; | ||
| /** | ||
| * Indicates whether the error matches a definition in the procedure's `.errors` map. | ||
| */ | ||
| readonly defined: boolean; | ||
| /** | ||
| * Indicates whether the error's type is inferable at the TypeScript level. | ||
| * This is typically true when the error is explicitly defined or returned within a handler. | ||
| */ | ||
| readonly inferable: boolean; | ||
| code: TCode; | ||
| data: TData; | ||
| constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>); | ||
| toJSON(): ORPCErrorJSON<TCode, TData>; | ||
| /** | ||
| * Workaround for Next.js where different contexts use separate | ||
| * dependency graphs, causing multiple ORPCError constructors existing and breaking | ||
| * `instanceof` checks across contexts. | ||
| * | ||
| * This is particularly problematic with "Optimized SSR", where orpc-client | ||
| * executes in one context but is invoked from another. When an error is thrown | ||
| * in the execution context, `instanceof ORPCError` checks fail in the | ||
| * invocation context due to separate class constructors. | ||
| * | ||
| * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue. | ||
| */ | ||
| static [Symbol.hasInstance](instance: unknown): boolean; | ||
| } | ||
| interface ORPCErrorJSON<TCode extends string, TData> extends Pick<ORPCError<TCode, TData>, 'code' | 'message' | 'data'> { | ||
| /** | ||
| * remove readonly | ||
| */ | ||
| defined: boolean; | ||
| /** | ||
| * remove readonly | ||
| */ | ||
| inferable: boolean; | ||
| } | ||
| type AnyORPCError = ORPCError<any, any>; | ||
| type AnyORPCErrorJSON = ORPCErrorJSON<any, any>; | ||
| export { ORPCError as h, COMMON_ERROR_STATUS_MAP as j }; | ||
| export type { AnyORPCError as A, ClientContext as C, FriendlyClientOptions as F, InferClientContext as I, NestedClient as N, ORPCErrorCode as O, ClientOptions as a, ClientLink as b, AnyNestedClient as c, InferClientError as d, Client as e, ClientRest as f, ORPCErrorJSON as g, AnyORPCErrorJSON as i, InferClientBodyInputs as k, InferClientBodyOutputs as l, InferClientErrors as m, InferClientInputs as n, InferClientOutputs as o, ORPCErrorOptions as p }; |
| import { sortPlugins, runWithSpan, ORPC_NAME, isAsyncIteratorObject, override, traceAsyncIterator, intercept, getOpenTelemetryConfig, value, pathToHttpPath, stringifyJSON } from '@orpc/shared'; | ||
| import { mergeStandardHeaders, parseStandardUrl } from '@standardserver/core'; | ||
| import { toStandardHeaders } from '@standardserver/fetch'; | ||
| import { O as ORPCError } from './client.CPcOxSex.mjs'; | ||
| import { R as RPCSerializer, i as isORPCErrorJson, c as createORPCErrorFromJson } from './client.COv0qq2C.mjs'; | ||
| class CompositeStandardLinkPlugin { | ||
| name = "~composite"; | ||
| plugins; | ||
| constructor(plugins = []) { | ||
| this.plugins = sortPlugins(plugins); | ||
| } | ||
| init(options) { | ||
| for (const plugin of this.plugins) { | ||
| if (plugin.init) { | ||
| options = plugin.init(options); | ||
| } | ||
| } | ||
| return options; | ||
| } | ||
| } | ||
| class StandardLink { | ||
| constructor(codec, transport, options = {}) { | ||
| this.codec = codec; | ||
| this.transport = transport; | ||
| options = new CompositeStandardLinkPlugin(options.plugins).init(options); | ||
| this.interceptors = options.interceptors; | ||
| this.transportInterceptors = options.transportInterceptors; | ||
| } | ||
| interceptors; | ||
| transportInterceptors; | ||
| /** | ||
| * @throws ORPCError, transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| call(path, input, options) { | ||
| return runWithSpan(`${ORPC_NAME}.${path.join("/")}`, (span) => { | ||
| span?.setAttribute("rpc.system", ORPC_NAME); | ||
| span?.setAttribute("rpc.method", path.join(".")); | ||
| if (isAsyncIteratorObject(input)) { | ||
| input = override(input, traceAsyncIterator("consume_async_iterator_object_input", input)); | ||
| } | ||
| return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => { | ||
| const otel = getOpenTelemetryConfig(); | ||
| let activeContext; | ||
| const activeSpan = otel?.trace.getActiveSpan() ?? span; | ||
| if (activeSpan && otel) { | ||
| activeContext = otel.trace.setSpan(otel.context.active(), activeSpan); | ||
| } | ||
| let request = await runWithSpan( | ||
| { name: "encode_input", context: activeContext }, | ||
| () => this.codec.encodeInput(input2, path2, options2) | ||
| ); | ||
| if (activeContext && otel?.propagation) { | ||
| const headers = { ...request.headers }; | ||
| otel.propagation.inject(activeContext, headers); | ||
| request = { ...request, headers }; | ||
| } | ||
| const response = await intercept( | ||
| this.transportInterceptors, | ||
| { ...options2, path: path2, request }, | ||
| ({ path: path3, request: request2, ...options3 }) => { | ||
| let activeTransportContext; | ||
| const activeTransportSpan = otel?.trace.getActiveSpan() ?? activeSpan; | ||
| if (activeTransportSpan && otel) { | ||
| activeTransportContext = otel.trace.setSpan(otel.context.active(), activeTransportSpan); | ||
| } | ||
| return runWithSpan( | ||
| { name: "send_request", context: activeTransportContext }, | ||
| () => this.transport.send(request2, path3, options3) | ||
| ); | ||
| } | ||
| ); | ||
| const decodedResult = await runWithSpan( | ||
| { name: "decode_response", context: activeContext }, | ||
| () => this.codec.decodeResponse(response, path2, options2) | ||
| ); | ||
| if (decodedResult.kind === "error") { | ||
| throw decodedResult.error; | ||
| } | ||
| const output = decodedResult.output; | ||
| if (isAsyncIteratorObject(output)) { | ||
| return override(output, traceAsyncIterator("consume_async_iterator_object_output", output)); | ||
| } | ||
| return output; | ||
| }); | ||
| }); | ||
| } | ||
| } | ||
| const END_SLASH_REGEX = /\/$/; | ||
| class RPCLinkCodec { | ||
| baseUrl; | ||
| maxUrlLength; | ||
| fallbackMethod; | ||
| expectedMethod; | ||
| headers; | ||
| serializer; | ||
| constructor(options) { | ||
| this.baseUrl = options.url ?? "/"; | ||
| this.maxUrlLength = options.maxUrlLength ?? 2083; | ||
| this.fallbackMethod = options.fallbackMethod ?? "POST"; | ||
| this.expectedMethod = options.method ?? this.fallbackMethod; | ||
| this.headers = options.headers ?? {}; | ||
| this.serializer = options.serializer ?? new RPCSerializer(); | ||
| } | ||
| async encodeInput(input, path, options) { | ||
| let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input)); | ||
| if (options.lastEventId !== void 0) { | ||
| headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId }); | ||
| } | ||
| const expectedMethod = await value(this.expectedMethod, options, path, input); | ||
| const baseUrl = await value(this.baseUrl, options, path, input); | ||
| const [pathname, search, hash] = parseStandardUrl(baseUrl); | ||
| const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path)}`; | ||
| const serialized = this.serializer.serialize(input); | ||
| if (expectedMethod === "GET" && !(serialized instanceof Blob) && !(serialized instanceof ReadableStream) && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) { | ||
| const maxUrlLength = await value(this.maxUrlLength, options, path, input); | ||
| const mergedSearch = new URLSearchParams(search); | ||
| mergedSearch.append("data", stringifyJSON(serialized) ?? ""); | ||
| const url2 = `${newPathname}?${mergedSearch}${hash ?? ""}`; | ||
| if (url2.length <= maxUrlLength) { | ||
| return { | ||
| body: void 0, | ||
| method: expectedMethod, | ||
| headers, | ||
| url: url2, | ||
| signal: options.signal | ||
| }; | ||
| } | ||
| } | ||
| const url = `${newPathname}${search ?? ""}${hash ?? ""}`; | ||
| return { | ||
| url, | ||
| method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod, | ||
| headers, | ||
| body: serialized, | ||
| signal: options.signal | ||
| }; | ||
| } | ||
| async decodeResponse(response) { | ||
| const isOk = response.status < 400; | ||
| const body = await response.resolveBody(); | ||
| const deserialized = await (async () => { | ||
| try { | ||
| return this.serializer.deserialize(body); | ||
| } catch (cause) { | ||
| throw new Error("Invalid RPC response format.", { | ||
| cause | ||
| }); | ||
| } | ||
| })(); | ||
| if (!isOk) { | ||
| if (isORPCErrorJson(deserialized)) { | ||
| return { kind: "error", error: createORPCErrorFromJson(deserialized) }; | ||
| } | ||
| return { | ||
| kind: "error", | ||
| error: new ORPCError("MALFORMED_ORPC_ERROR_RESPONSE", { | ||
| data: { headers: response.headers, status: response.status, body: deserialized } | ||
| }) | ||
| }; | ||
| } | ||
| return { kind: "output", output: deserialized }; | ||
| } | ||
| } | ||
| function toResolvedStandardHeaders(headers) { | ||
| if (typeof headers.forEach === "function") { | ||
| return toStandardHeaders(headers); | ||
| } | ||
| return headers; | ||
| } | ||
| export { CompositeStandardLinkPlugin as C, RPCLinkCodec as R, StandardLink as S }; |
@@ -1,6 +0,6 @@ | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.EMUKnkap.mjs'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.l_EYklFG.mjs'; | ||
| import { Value, Promisable, Interceptor } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { ToFetchBodyOptions } from '@standardserver/fetch'; | ||
| import { S as StandardLinkTransport, c as StandardLinkPlugin, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BpRn9TAI.mjs'; | ||
| import { S as StandardLinkTransport, c as StandardLinkPlugin, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BkoxWb8f.mjs'; | ||
| import { RPCLinkCodecOptions } from '../standard/index.mjs'; | ||
@@ -7,0 +7,0 @@ import '../../shared/client.B8tCfDzm.mjs'; |
@@ -1,6 +0,6 @@ | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.EMUKnkap.js'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.l_EYklFG.js'; | ||
| import { Value, Promisable, Interceptor } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { ToFetchBodyOptions } from '@standardserver/fetch'; | ||
| import { S as StandardLinkTransport, c as StandardLinkPlugin, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BGShxYPR.js'; | ||
| import { S as StandardLinkTransport, c as StandardLinkPlugin, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.ByTd6BR5.js'; | ||
| import { RPCLinkCodecOptions } from '../standard/index.js'; | ||
@@ -7,0 +7,0 @@ import '../../shared/client.B8tCfDzm.js'; |
| import { sortPlugins, value, intercept, once } from '@orpc/shared'; | ||
| import { toFetchBody, toFetchHeaders, toStandardLazyResponse } from '@standardserver/fetch'; | ||
| import { S as StandardLink, R as RPCLinkCodec } from '../../shared/client.B6ItE3bt.mjs'; | ||
| import { S as StandardLink, R as RPCLinkCodec } from '../../shared/client.uztMy1KD.mjs'; | ||
| import '@standardserver/core'; | ||
| import '../../shared/client.CPcOxSex.mjs'; | ||
| import '../../shared/client.BZMJyvQd.mjs'; | ||
| import '../../shared/client.COv0qq2C.mjs'; | ||
@@ -8,0 +8,0 @@ class CompositeFetchLinkTransportPlugin { |
@@ -1,6 +0,6 @@ | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.EMUKnkap.mjs'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.l_EYklFG.mjs'; | ||
| import { Value, Promisable } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { ClientPeer, EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standardserver/peer'; | ||
| import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BpRn9TAI.mjs'; | ||
| import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BkoxWb8f.mjs'; | ||
| import { RPCLinkCodecOptions } from '../standard/index.mjs'; | ||
@@ -7,0 +7,0 @@ import '../../shared/client.B8tCfDzm.mjs'; |
@@ -1,6 +0,6 @@ | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.EMUKnkap.js'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.l_EYklFG.js'; | ||
| import { Value, Promisable } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { ClientPeer, EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standardserver/peer'; | ||
| import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BGShxYPR.js'; | ||
| import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.ByTd6BR5.js'; | ||
| import { RPCLinkCodecOptions } from '../standard/index.js'; | ||
@@ -7,0 +7,0 @@ import '../../shared/client.B8tCfDzm.js'; |
| import { value } from '@orpc/shared'; | ||
| import { ClientPeer, encodePeerMessage, decodePeerMessage, isServerPeerSendMessage, isPeerMessage } from '@standardserver/peer'; | ||
| import { S as StandardLink, R as RPCLinkCodec } from '../../shared/client.B6ItE3bt.mjs'; | ||
| import { S as StandardLink, R as RPCLinkCodec } from '../../shared/client.uztMy1KD.mjs'; | ||
| import '@standardserver/core'; | ||
| import '@standardserver/fetch'; | ||
| import '../../shared/client.CPcOxSex.mjs'; | ||
| import '../../shared/client.BZMJyvQd.mjs'; | ||
| import '../../shared/client.COv0qq2C.mjs'; | ||
@@ -9,0 +9,0 @@ function postMessagePortMessage(port, data, transfer) { |
@@ -1,7 +0,7 @@ | ||
| import { f as StandardLinkCodec, g as StandardLinkCodecDecodedResponse } from '../../shared/client.BpRn9TAI.mjs'; | ||
| export { C as CompositeStandardLinkPlugin, a as StandardLink, h as StandardLinkInterceptor, e as StandardLinkInterceptorOptions, b as StandardLinkOptions, c as StandardLinkPlugin, S as StandardLinkTransport, i as StandardLinkTransportInterceptor, d as StandardLinkTransportInterceptorOptions } from '../../shared/client.BpRn9TAI.mjs'; | ||
| import { f as StandardLinkCodec, g as StandardLinkCodecDecodedResponse } from '../../shared/client.BkoxWb8f.mjs'; | ||
| export { C as CompositeStandardLinkPlugin, a as StandardLink, h as StandardLinkInterceptor, e as StandardLinkInterceptorOptions, b as StandardLinkOptions, c as StandardLinkPlugin, S as StandardLinkTransport, i as StandardLinkTransportInterceptor, d as StandardLinkTransportInterceptorOptions } from '../../shared/client.BkoxWb8f.mjs'; | ||
| import { Value, Promisable } from '@orpc/shared'; | ||
| import { StandardUrl, StandardHeaders, StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| export { StandardBody, StandardBodyHint, StandardHeaders, StandardLazyRequest, StandardLazyResponse, StandardMethod, StandardRequest, StandardResponse, StandardUrl } from '@standardserver/core'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.EMUKnkap.mjs'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.l_EYklFG.mjs'; | ||
| import { e as RPCSerializer } from '../../shared/client.B8tCfDzm.mjs'; | ||
@@ -8,0 +8,0 @@ |
@@ -1,7 +0,7 @@ | ||
| import { f as StandardLinkCodec, g as StandardLinkCodecDecodedResponse } from '../../shared/client.BGShxYPR.js'; | ||
| export { C as CompositeStandardLinkPlugin, a as StandardLink, h as StandardLinkInterceptor, e as StandardLinkInterceptorOptions, b as StandardLinkOptions, c as StandardLinkPlugin, S as StandardLinkTransport, i as StandardLinkTransportInterceptor, d as StandardLinkTransportInterceptorOptions } from '../../shared/client.BGShxYPR.js'; | ||
| import { f as StandardLinkCodec, g as StandardLinkCodecDecodedResponse } from '../../shared/client.ByTd6BR5.js'; | ||
| export { C as CompositeStandardLinkPlugin, a as StandardLink, h as StandardLinkInterceptor, e as StandardLinkInterceptorOptions, b as StandardLinkOptions, c as StandardLinkPlugin, S as StandardLinkTransport, i as StandardLinkTransportInterceptor, d as StandardLinkTransportInterceptorOptions } from '../../shared/client.ByTd6BR5.js'; | ||
| import { Value, Promisable } from '@orpc/shared'; | ||
| import { StandardUrl, StandardHeaders, StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| export { StandardBody, StandardBodyHint, StandardHeaders, StandardLazyRequest, StandardLazyResponse, StandardMethod, StandardRequest, StandardResponse, StandardUrl } from '@standardserver/core'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.EMUKnkap.js'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.l_EYklFG.js'; | ||
| import { e as RPCSerializer } from '../../shared/client.B8tCfDzm.js'; | ||
@@ -8,0 +8,0 @@ |
@@ -1,2 +0,2 @@ | ||
| export { C as CompositeStandardLinkPlugin, R as RPCLinkCodec, S as StandardLink } from '../../shared/client.B6ItE3bt.mjs'; | ||
| export { C as CompositeStandardLinkPlugin, R as RPCLinkCodec, S as StandardLink } from '../../shared/client.uztMy1KD.mjs'; | ||
| import '@orpc/shared'; | ||
@@ -6,2 +6,2 @@ import '@standardserver/core'; | ||
| import '../../shared/client.CPcOxSex.mjs'; | ||
| import '../../shared/client.BZMJyvQd.mjs'; | ||
| import '../../shared/client.COv0qq2C.mjs'; |
@@ -1,6 +0,6 @@ | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.EMUKnkap.mjs'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.l_EYklFG.mjs'; | ||
| import { Promisable } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standardserver/peer'; | ||
| import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BpRn9TAI.mjs'; | ||
| import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BkoxWb8f.mjs'; | ||
| import { RPCLinkCodecOptions } from '../standard/index.mjs'; | ||
@@ -7,0 +7,0 @@ import '../../shared/client.B8tCfDzm.mjs'; |
@@ -1,6 +0,6 @@ | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.EMUKnkap.js'; | ||
| import { C as ClientContext, a as ClientOptions } from '../../shared/client.l_EYklFG.js'; | ||
| import { Promisable } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standardserver/peer'; | ||
| import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.BGShxYPR.js'; | ||
| import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.ByTd6BR5.js'; | ||
| import { RPCLinkCodecOptions } from '../standard/index.js'; | ||
@@ -7,0 +7,0 @@ import '../../shared/client.B8tCfDzm.js'; |
| import { runWithSignal, AbortError, sleep, promiseWithResolvers, sequential, loadBytes, toStringOrBytes } from '@orpc/shared'; | ||
| import { ClientPeer, encodePeerMessage, decodePeerMessage, isServerPeerSendMessage } from '@standardserver/peer'; | ||
| import { S as StandardLink, R as RPCLinkCodec } from '../../shared/client.B6ItE3bt.mjs'; | ||
| import { S as StandardLink, R as RPCLinkCodec } from '../../shared/client.uztMy1KD.mjs'; | ||
| import '@standardserver/core'; | ||
| import '@standardserver/fetch'; | ||
| import '../../shared/client.CPcOxSex.mjs'; | ||
| import '../../shared/client.BZMJyvQd.mjs'; | ||
| import '../../shared/client.COv0qq2C.mjs'; | ||
@@ -9,0 +9,0 @@ const WEBSOCKET_CONNECTING = 0; |
+11
-3
| import { WrapAsyncIteratorOptions, AsyncIteratorClass, Interceptor, PromiseWithError, ThrowableError, Promisable } from '@orpc/shared'; | ||
| export { AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, PromiseWithError as ClientPromiseResult, MaybeOptionalOptions, PromiseWithError, Registry, ThrowableError, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, consumeAsyncIterator, consumeAsyncIterator as consumeEventIterator, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, streamToAsyncIteratorObject, streamToAsyncIteratorObject as streamToEventIterator } from '@orpc/shared'; | ||
| import { C as ClientContext, a as ClientOptions, c as AnyNestedClient, I as InferClientContext, d as InferClientError, e as Client, b as ClientLink, A as AnyORPCError, f as ClientRest, F as FriendlyClientOptions, O as ORPCErrorCode, g as ORPCError, h as ORPCErrorJSON } from './shared/client.EMUKnkap.mjs'; | ||
| export { i as AnyORPCErrorJSON, j as COMMON_ERROR_STATUS_MAP, k as InferClientBodyInputs, l as InferClientBodyOutputs, m as InferClientErrors, n as InferClientInputs, o as InferClientOutputs, N as NestedClient, p as ORPCErrorOptions } from './shared/client.EMUKnkap.mjs'; | ||
| import { C as ClientContext, a as ClientOptions, c as AnyNestedClient, I as InferClientContext, d as InferClientError, e as Client, b as ClientLink, A as AnyORPCError, f as ClientRest, F as FriendlyClientOptions, O as ORPCErrorCode, g as ORPCErrorJSON, h as ORPCError } from './shared/client.l_EYklFG.mjs'; | ||
| export { i as AnyORPCErrorJSON, j as COMMON_ERROR_STATUS_MAP, k as InferClientBodyInputs, l as InferClientBodyOutputs, m as InferClientErrors, n as InferClientInputs, o as InferClientOutputs, N as NestedClient, p as ORPCErrorOptions } from './shared/client.l_EYklFG.mjs'; | ||
| export { R as RPCJsonSerialization, a as RPCJsonSerializationMeta, b as RPCJsonSerializer, c as RPCJsonSerializerHandler, d as RPCJsonSerializerOptions, e as RPCSerializer, f as RPCSerializerOptions, g as RPCSerializerSerializeOptions } from './shared/client.B8tCfDzm.mjs'; | ||
@@ -134,5 +134,13 @@ export { ErrorEvent, EventMeta, getEventMeta, unwrapEvent, withEventMeta } from '@standardserver/core'; | ||
| declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>; | ||
| declare function cloneORPCError<T extends ORPCErrorCode, TData>(error: ORPCError<T, TData>): ORPCError<T, TData>; | ||
| /** | ||
| * Clones an `ORPCError` while preserving its prototype chain, so instances of | ||
| * `ORPCError` subclasses remain `instanceof` their class. | ||
| * | ||
| * Limitation: subclass constructors are not re-run, so private fields | ||
| * (`#field`) are not carried over and subclass members that read them | ||
| * will throw on the clone. | ||
| */ | ||
| declare function cloneORPCError<T extends AnyORPCError>(error: T): T; | ||
| export { AnyNestedClient, AnyORPCError, Client, ClientContext, ClientLink, ClientOptions, ClientRest, DynamicLink, FriendlyClientOptions, InferClientContext, InferClientError, InferClientError as InferClientErrorUnion, ORPCError, ORPCErrorCode, ORPCErrorJSON, RECURSIVE_CLIENT_UNWRAP_KEYS, cloneORPCError, createORPCClient, createORPCErrorFromJson, createSafeClient, isInferableError as isDefinedError, isInferableError, isORPCErrorJson, resolveClientRest, resolveFriendlyClientOptions, safe, toORPCError, wrapAsyncIteratorPreservingEventMeta }; | ||
| export type { ORPCClientInterceptor, ORPCClientInterceptorOptions, ORPCClientOptions, ORPCClientScoped, ORPCClientScopedOptions, SafeClient, SafeResult }; |
+11
-3
| import { WrapAsyncIteratorOptions, AsyncIteratorClass, Interceptor, PromiseWithError, ThrowableError, Promisable } from '@orpc/shared'; | ||
| export { AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, PromiseWithError as ClientPromiseResult, MaybeOptionalOptions, PromiseWithError, Registry, ThrowableError, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, consumeAsyncIterator, consumeAsyncIterator as consumeEventIterator, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, streamToAsyncIteratorObject, streamToAsyncIteratorObject as streamToEventIterator } from '@orpc/shared'; | ||
| import { C as ClientContext, a as ClientOptions, c as AnyNestedClient, I as InferClientContext, d as InferClientError, e as Client, b as ClientLink, A as AnyORPCError, f as ClientRest, F as FriendlyClientOptions, O as ORPCErrorCode, g as ORPCError, h as ORPCErrorJSON } from './shared/client.EMUKnkap.js'; | ||
| export { i as AnyORPCErrorJSON, j as COMMON_ERROR_STATUS_MAP, k as InferClientBodyInputs, l as InferClientBodyOutputs, m as InferClientErrors, n as InferClientInputs, o as InferClientOutputs, N as NestedClient, p as ORPCErrorOptions } from './shared/client.EMUKnkap.js'; | ||
| import { C as ClientContext, a as ClientOptions, c as AnyNestedClient, I as InferClientContext, d as InferClientError, e as Client, b as ClientLink, A as AnyORPCError, f as ClientRest, F as FriendlyClientOptions, O as ORPCErrorCode, g as ORPCErrorJSON, h as ORPCError } from './shared/client.l_EYklFG.js'; | ||
| export { i as AnyORPCErrorJSON, j as COMMON_ERROR_STATUS_MAP, k as InferClientBodyInputs, l as InferClientBodyOutputs, m as InferClientErrors, n as InferClientInputs, o as InferClientOutputs, N as NestedClient, p as ORPCErrorOptions } from './shared/client.l_EYklFG.js'; | ||
| export { R as RPCJsonSerialization, a as RPCJsonSerializationMeta, b as RPCJsonSerializer, c as RPCJsonSerializerHandler, d as RPCJsonSerializerOptions, e as RPCSerializer, f as RPCSerializerOptions, g as RPCSerializerSerializeOptions } from './shared/client.B8tCfDzm.js'; | ||
@@ -134,5 +134,13 @@ export { ErrorEvent, EventMeta, getEventMeta, unwrapEvent, withEventMeta } from '@standardserver/core'; | ||
| declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>; | ||
| declare function cloneORPCError<T extends ORPCErrorCode, TData>(error: ORPCError<T, TData>): ORPCError<T, TData>; | ||
| /** | ||
| * Clones an `ORPCError` while preserving its prototype chain, so instances of | ||
| * `ORPCError` subclasses remain `instanceof` their class. | ||
| * | ||
| * Limitation: subclass constructors are not re-run, so private fields | ||
| * (`#field`) are not carried over and subclass members that read them | ||
| * will throw on the clone. | ||
| */ | ||
| declare function cloneORPCError<T extends AnyORPCError>(error: T): T; | ||
| export { AnyNestedClient, AnyORPCError, Client, ClientContext, ClientLink, ClientOptions, ClientRest, DynamicLink, FriendlyClientOptions, InferClientContext, InferClientError, InferClientError as InferClientErrorUnion, ORPCError, ORPCErrorCode, ORPCErrorJSON, RECURSIVE_CLIENT_UNWRAP_KEYS, cloneORPCError, createORPCClient, createORPCErrorFromJson, createSafeClient, isInferableError as isDefinedError, isInferableError, isORPCErrorJson, resolveClientRest, resolveFriendlyClientOptions, safe, toORPCError, wrapAsyncIteratorPreservingEventMeta }; | ||
| export type { ORPCClientInterceptor, ORPCClientInterceptorOptions, ORPCClientOptions, ORPCClientScoped, ORPCClientScopedOptions, SafeClient, SafeResult }; |
+2
-2
@@ -1,3 +0,3 @@ | ||
| import { a as isInferableError } from './shared/client.BZMJyvQd.mjs'; | ||
| export { b as RPCJsonSerializer, R as RPCSerializer, d as cloneORPCError, c as createORPCErrorFromJson, i as isORPCErrorJson, t as toORPCError, w as wrapAsyncIteratorPreservingEventMeta } from './shared/client.BZMJyvQd.mjs'; | ||
| import { a as isInferableError } from './shared/client.COv0qq2C.mjs'; | ||
| export { b as RPCJsonSerializer, R as RPCSerializer, d as cloneORPCError, c as createORPCErrorFromJson, i as isORPCErrorJson, t as toORPCError, w as wrapAsyncIteratorPreservingEventMeta } from './shared/client.COv0qq2C.mjs'; | ||
| import { toArray, intercept, isTypescriptObject } from '@orpc/shared'; | ||
@@ -4,0 +4,0 @@ export { AsyncIteratorClass, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, consumeAsyncIterator, consumeAsyncIterator as consumeEventIterator, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, streamToAsyncIteratorObject, streamToAsyncIteratorObject as streamToEventIterator } from '@orpc/shared'; |
| import { Value, Promisable } from '@orpc/shared'; | ||
| import { StandardUrl, StandardHeaders, StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { C as ClientContext } from '../shared/client.EMUKnkap.mjs'; | ||
| import { c as StandardLinkPlugin, d as StandardLinkTransportInterceptorOptions, b as StandardLinkOptions, e as StandardLinkInterceptorOptions } from '../shared/client.BpRn9TAI.mjs'; | ||
| import { C as ClientContext } from '../shared/client.l_EYklFG.mjs'; | ||
| import { c as StandardLinkPlugin, d as StandardLinkTransportInterceptorOptions, b as StandardLinkOptions, e as StandardLinkInterceptorOptions } from '../shared/client.BkoxWb8f.mjs'; | ||
@@ -6,0 +6,0 @@ type BatchLinkPluginMode = 'streaming' | 'buffered'; |
| import { Value, Promisable } from '@orpc/shared'; | ||
| import { StandardUrl, StandardHeaders, StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { C as ClientContext } from '../shared/client.EMUKnkap.js'; | ||
| import { c as StandardLinkPlugin, d as StandardLinkTransportInterceptorOptions, b as StandardLinkOptions, e as StandardLinkInterceptorOptions } from '../shared/client.BGShxYPR.js'; | ||
| import { C as ClientContext } from '../shared/client.l_EYklFG.js'; | ||
| import { c as StandardLinkPlugin, d as StandardLinkTransportInterceptorOptions, b as StandardLinkOptions, e as StandardLinkInterceptorOptions } from '../shared/client.ByTd6BR5.js'; | ||
@@ -6,0 +6,0 @@ type BatchLinkPluginMode = 'streaming' | 'buffered'; |
+3
-2
| { | ||
| "name": "@orpc/client", | ||
| "type": "module", | ||
| "version": "2.0.0-beta.25", | ||
| "version": "2.0.0-beta.26", | ||
| "license": "MIT", | ||
| "funding": "https://github.com/sponsors/dinwwwh", | ||
| "homepage": "https://orpc.dev", | ||
@@ -56,3 +57,3 @@ "repository": { | ||
| "@standardserver/peer": "^0.7.1", | ||
| "@orpc/shared": "2.0.0-beta.25" | ||
| "@orpc/shared": "2.0.0-beta.26" | ||
| }, | ||
@@ -59,0 +60,0 @@ "devDependencies": { |
| import { sortPlugins, runWithSpan, ORPC_NAME, isAsyncIteratorObject, override, traceAsyncIterator, intercept, getOpenTelemetryConfig, value, pathToHttpPath, stringifyJSON } from '@orpc/shared'; | ||
| import { mergeStandardHeaders, parseStandardUrl } from '@standardserver/core'; | ||
| import { toStandardHeaders } from '@standardserver/fetch'; | ||
| import { O as ORPCError } from './client.CPcOxSex.mjs'; | ||
| import { R as RPCSerializer, i as isORPCErrorJson, c as createORPCErrorFromJson } from './client.BZMJyvQd.mjs'; | ||
| class CompositeStandardLinkPlugin { | ||
| name = "~composite"; | ||
| plugins; | ||
| constructor(plugins = []) { | ||
| this.plugins = sortPlugins(plugins); | ||
| } | ||
| init(options) { | ||
| for (const plugin of this.plugins) { | ||
| if (plugin.init) { | ||
| options = plugin.init(options); | ||
| } | ||
| } | ||
| return options; | ||
| } | ||
| } | ||
| class StandardLink { | ||
| constructor(codec, transport, options = {}) { | ||
| this.codec = codec; | ||
| this.transport = transport; | ||
| options = new CompositeStandardLinkPlugin(options.plugins).init(options); | ||
| this.interceptors = options.interceptors; | ||
| this.transportInterceptors = options.transportInterceptors; | ||
| } | ||
| interceptors; | ||
| transportInterceptors; | ||
| /** | ||
| * @throws ORPCError, transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| call(path, input, options) { | ||
| return runWithSpan(`${ORPC_NAME}.${path.join("/")}`, (span) => { | ||
| span?.setAttribute("rpc.system", ORPC_NAME); | ||
| span?.setAttribute("rpc.method", path.join(".")); | ||
| if (isAsyncIteratorObject(input)) { | ||
| input = override(input, traceAsyncIterator("consume_async_iterator_object_input", input)); | ||
| } | ||
| return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => { | ||
| const otel = getOpenTelemetryConfig(); | ||
| let activeContext; | ||
| const activeSpan = otel?.trace.getActiveSpan() ?? span; | ||
| if (activeSpan && otel) { | ||
| activeContext = otel.trace.setSpan(otel.context.active(), activeSpan); | ||
| } | ||
| let request = await runWithSpan( | ||
| { name: "encode_input", context: activeContext }, | ||
| () => this.codec.encodeInput(input2, path2, options2) | ||
| ); | ||
| if (activeContext && otel?.propagation) { | ||
| const headers = { ...request.headers }; | ||
| otel.propagation.inject(activeContext, headers); | ||
| request = { ...request, headers }; | ||
| } | ||
| const response = await intercept( | ||
| this.transportInterceptors, | ||
| { ...options2, path: path2, request }, | ||
| ({ path: path3, request: request2, ...options3 }) => { | ||
| let activeTransportContext; | ||
| const activeTransportSpan = otel?.trace.getActiveSpan() ?? activeSpan; | ||
| if (activeTransportSpan && otel) { | ||
| activeTransportContext = otel.trace.setSpan(otel.context.active(), activeTransportSpan); | ||
| } | ||
| return runWithSpan( | ||
| { name: "send_request", context: activeTransportContext }, | ||
| () => this.transport.send(request2, path3, options3) | ||
| ); | ||
| } | ||
| ); | ||
| const decodedResult = await runWithSpan( | ||
| { name: "decode_response", context: activeContext }, | ||
| () => this.codec.decodeResponse(response, path2, options2) | ||
| ); | ||
| if (decodedResult.kind === "error") { | ||
| throw decodedResult.error; | ||
| } | ||
| const output = decodedResult.output; | ||
| if (isAsyncIteratorObject(output)) { | ||
| return override(output, traceAsyncIterator("consume_async_iterator_object_output", output)); | ||
| } | ||
| return output; | ||
| }); | ||
| }); | ||
| } | ||
| } | ||
| const END_SLASH_REGEX = /\/$/; | ||
| class RPCLinkCodec { | ||
| baseUrl; | ||
| maxUrlLength; | ||
| fallbackMethod; | ||
| expectedMethod; | ||
| headers; | ||
| serializer; | ||
| constructor(options) { | ||
| this.baseUrl = options.url ?? "/"; | ||
| this.maxUrlLength = options.maxUrlLength ?? 2083; | ||
| this.fallbackMethod = options.fallbackMethod ?? "POST"; | ||
| this.expectedMethod = options.method ?? this.fallbackMethod; | ||
| this.headers = options.headers ?? {}; | ||
| this.serializer = options.serializer ?? new RPCSerializer(); | ||
| } | ||
| async encodeInput(input, path, options) { | ||
| let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input)); | ||
| if (options.lastEventId !== void 0) { | ||
| headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId }); | ||
| } | ||
| const expectedMethod = await value(this.expectedMethod, options, path, input); | ||
| const baseUrl = await value(this.baseUrl, options, path, input); | ||
| const [pathname, search, hash] = parseStandardUrl(baseUrl); | ||
| const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path)}`; | ||
| const serialized = this.serializer.serialize(input); | ||
| if (expectedMethod === "GET" && !(serialized instanceof Blob) && !(serialized instanceof ReadableStream) && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) { | ||
| const maxUrlLength = await value(this.maxUrlLength, options, path, input); | ||
| const mergedSearch = new URLSearchParams(search); | ||
| mergedSearch.append("data", stringifyJSON(serialized) ?? ""); | ||
| const url2 = `${newPathname}?${mergedSearch}${hash ?? ""}`; | ||
| if (url2.length <= maxUrlLength) { | ||
| return { | ||
| body: void 0, | ||
| method: expectedMethod, | ||
| headers, | ||
| url: url2, | ||
| signal: options.signal | ||
| }; | ||
| } | ||
| } | ||
| const url = `${newPathname}${search ?? ""}${hash ?? ""}`; | ||
| return { | ||
| url, | ||
| method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod, | ||
| headers, | ||
| body: serialized, | ||
| signal: options.signal | ||
| }; | ||
| } | ||
| async decodeResponse(response) { | ||
| const isOk = response.status < 400; | ||
| const body = await response.resolveBody(); | ||
| const deserialized = await (async () => { | ||
| try { | ||
| return this.serializer.deserialize(body); | ||
| } catch (cause) { | ||
| throw new Error("Invalid RPC response format.", { | ||
| cause | ||
| }); | ||
| } | ||
| })(); | ||
| if (!isOk) { | ||
| if (isORPCErrorJson(deserialized)) { | ||
| return { kind: "error", error: createORPCErrorFromJson(deserialized) }; | ||
| } | ||
| return { | ||
| kind: "error", | ||
| error: new ORPCError("MALFORMED_ORPC_ERROR_RESPONSE", { | ||
| data: { headers: response.headers, status: response.status, body: deserialized } | ||
| }) | ||
| }; | ||
| } | ||
| return { kind: "output", output: deserialized }; | ||
| } | ||
| } | ||
| function toResolvedStandardHeaders(headers) { | ||
| if (typeof headers.forEach === "function") { | ||
| return toStandardHeaders(headers); | ||
| } | ||
| return headers; | ||
| } | ||
| export { CompositeStandardLinkPlugin as C, RPCLinkCodec as R, StandardLink as S }; |
| import { Promisable, OrderablePlugin, Interceptor } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { C as ClientContext, a as ClientOptions, A as AnyORPCError, b as ClientLink } from './client.EMUKnkap.js'; | ||
| type StandardLinkCodecDecodedResponse = { | ||
| kind: 'output'; | ||
| output: unknown; | ||
| } | { | ||
| kind: 'error'; | ||
| error: AnyORPCError; | ||
| }; | ||
| interface StandardLinkCodec<T extends ClientContext> { | ||
| encodeInput(input: unknown, path: string[], options: ClientOptions<T>): Promisable<StandardRequest>; | ||
| decodeResponse(response: StandardLazyResponse, path: string[], options: ClientOptions<T>): Promisable<StandardLinkCodecDecodedResponse>; | ||
| } | ||
| interface StandardLinkPlugin<T extends ClientContext> extends OrderablePlugin { | ||
| /** | ||
| * Initializes the plugin and returns new link options. | ||
| * Called once per plugin instance during composition. | ||
| * | ||
| * This method allows plugins to wrap, extend, or transform link options | ||
| * such as interceptors, or configuration. | ||
| * | ||
| * @param options - The current link options from previous plugins or base configuration | ||
| * @returns Transformed link options with plugin's modifications applied | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * init(options) { | ||
| * return { | ||
| * ...options, | ||
| * interceptors: [...(options.interceptors || []), myInterceptor] | ||
| * } | ||
| * } | ||
| * ``` | ||
| */ | ||
| init?(options: StandardLinkOptions<T>): StandardLinkOptions<T>; | ||
| } | ||
| declare class CompositeStandardLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> { | ||
| name: string; | ||
| protected readonly plugins: StandardLinkPlugin<T>[]; | ||
| constructor(plugins?: StandardLinkPlugin<T>[]); | ||
| init(options: StandardLinkOptions<T>): StandardLinkOptions<T>; | ||
| } | ||
| /** | ||
| * Handles the transport layer for sending requests and receiving responses. | ||
| * | ||
| * Implementations are responsible for the actual network communication, | ||
| * such as HTTP fetch, WebSocket, or other transport mechanisms. | ||
| */ | ||
| interface StandardLinkTransport<T extends ClientContext> { | ||
| /** | ||
| * @throws Transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| send(request: StandardRequest, path: string[], options: ClientOptions<T>): Promise<StandardLazyResponse>; | ||
| } | ||
| interface StandardLinkInterceptorOptions<T extends ClientContext> extends ClientOptions<T> { | ||
| path: string[]; | ||
| input: unknown; | ||
| } | ||
| type StandardLinkInterceptor<T extends ClientContext> = Interceptor<StandardLinkInterceptorOptions<T>, Promise<unknown>>; | ||
| interface StandardLinkTransportInterceptorOptions<T extends ClientContext> extends ClientOptions<T> { | ||
| path: string[]; | ||
| request: StandardRequest; | ||
| } | ||
| type StandardLinkTransportInterceptor<T extends ClientContext> = Interceptor<StandardLinkTransportInterceptorOptions<T>, Promise<StandardLazyResponse>>; | ||
| interface StandardLinkOptions<T extends ClientContext> { | ||
| /** | ||
| * Interceptors that execute around the entire call, including transport and codec. | ||
| * Useful for error handling, logging, metrics, ... | ||
| */ | ||
| interceptors?: StandardLinkInterceptor<T>[]; | ||
| /** | ||
| * Interceptors that execute around the transport layer, after encoding and before decoding. | ||
| * Useful for modifying the request or response, adding transport-level logging, ... | ||
| */ | ||
| transportInterceptors?: StandardLinkTransportInterceptor<T>[]; | ||
| plugins?: StandardLinkPlugin<T>[]; | ||
| } | ||
| declare class StandardLink<T extends ClientContext> implements ClientLink<T> { | ||
| private readonly codec; | ||
| private readonly transport; | ||
| private readonly interceptors; | ||
| private readonly transportInterceptors; | ||
| constructor(codec: StandardLinkCodec<T>, transport: StandardLinkTransport<T>, options?: StandardLinkOptions<T>); | ||
| /** | ||
| * @throws ORPCError, transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| call(path: string[], input: unknown, options: ClientOptions<T>): Promise<unknown>; | ||
| } | ||
| export { CompositeStandardLinkPlugin as C, StandardLink as a }; | ||
| export type { StandardLinkTransport as S, StandardLinkOptions as b, StandardLinkPlugin as c, StandardLinkTransportInterceptorOptions as d, StandardLinkInterceptorOptions as e, StandardLinkCodec as f, StandardLinkCodecDecodedResponse as g, StandardLinkInterceptor as h, StandardLinkTransportInterceptor as i }; |
| import { Promisable, OrderablePlugin, Interceptor } from '@orpc/shared'; | ||
| import { StandardRequest, StandardLazyResponse } from '@standardserver/core'; | ||
| import { C as ClientContext, a as ClientOptions, A as AnyORPCError, b as ClientLink } from './client.EMUKnkap.mjs'; | ||
| type StandardLinkCodecDecodedResponse = { | ||
| kind: 'output'; | ||
| output: unknown; | ||
| } | { | ||
| kind: 'error'; | ||
| error: AnyORPCError; | ||
| }; | ||
| interface StandardLinkCodec<T extends ClientContext> { | ||
| encodeInput(input: unknown, path: string[], options: ClientOptions<T>): Promisable<StandardRequest>; | ||
| decodeResponse(response: StandardLazyResponse, path: string[], options: ClientOptions<T>): Promisable<StandardLinkCodecDecodedResponse>; | ||
| } | ||
| interface StandardLinkPlugin<T extends ClientContext> extends OrderablePlugin { | ||
| /** | ||
| * Initializes the plugin and returns new link options. | ||
| * Called once per plugin instance during composition. | ||
| * | ||
| * This method allows plugins to wrap, extend, or transform link options | ||
| * such as interceptors, or configuration. | ||
| * | ||
| * @param options - The current link options from previous plugins or base configuration | ||
| * @returns Transformed link options with plugin's modifications applied | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * init(options) { | ||
| * return { | ||
| * ...options, | ||
| * interceptors: [...(options.interceptors || []), myInterceptor] | ||
| * } | ||
| * } | ||
| * ``` | ||
| */ | ||
| init?(options: StandardLinkOptions<T>): StandardLinkOptions<T>; | ||
| } | ||
| declare class CompositeStandardLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> { | ||
| name: string; | ||
| protected readonly plugins: StandardLinkPlugin<T>[]; | ||
| constructor(plugins?: StandardLinkPlugin<T>[]); | ||
| init(options: StandardLinkOptions<T>): StandardLinkOptions<T>; | ||
| } | ||
| /** | ||
| * Handles the transport layer for sending requests and receiving responses. | ||
| * | ||
| * Implementations are responsible for the actual network communication, | ||
| * such as HTTP fetch, WebSocket, or other transport mechanisms. | ||
| */ | ||
| interface StandardLinkTransport<T extends ClientContext> { | ||
| /** | ||
| * @throws Transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| send(request: StandardRequest, path: string[], options: ClientOptions<T>): Promise<StandardLazyResponse>; | ||
| } | ||
| interface StandardLinkInterceptorOptions<T extends ClientContext> extends ClientOptions<T> { | ||
| path: string[]; | ||
| input: unknown; | ||
| } | ||
| type StandardLinkInterceptor<T extends ClientContext> = Interceptor<StandardLinkInterceptorOptions<T>, Promise<unknown>>; | ||
| interface StandardLinkTransportInterceptorOptions<T extends ClientContext> extends ClientOptions<T> { | ||
| path: string[]; | ||
| request: StandardRequest; | ||
| } | ||
| type StandardLinkTransportInterceptor<T extends ClientContext> = Interceptor<StandardLinkTransportInterceptorOptions<T>, Promise<StandardLazyResponse>>; | ||
| interface StandardLinkOptions<T extends ClientContext> { | ||
| /** | ||
| * Interceptors that execute around the entire call, including transport and codec. | ||
| * Useful for error handling, logging, metrics, ... | ||
| */ | ||
| interceptors?: StandardLinkInterceptor<T>[]; | ||
| /** | ||
| * Interceptors that execute around the transport layer, after encoding and before decoding. | ||
| * Useful for modifying the request or response, adding transport-level logging, ... | ||
| */ | ||
| transportInterceptors?: StandardLinkTransportInterceptor<T>[]; | ||
| plugins?: StandardLinkPlugin<T>[]; | ||
| } | ||
| declare class StandardLink<T extends ClientContext> implements ClientLink<T> { | ||
| private readonly codec; | ||
| private readonly transport; | ||
| private readonly interceptors; | ||
| private readonly transportInterceptors; | ||
| constructor(codec: StandardLinkCodec<T>, transport: StandardLinkTransport<T>, options?: StandardLinkOptions<T>); | ||
| /** | ||
| * @throws ORPCError, transport-level errors (network failures, timeouts, etc.) | ||
| */ | ||
| call(path: string[], input: unknown, options: ClientOptions<T>): Promise<unknown>; | ||
| } | ||
| export { CompositeStandardLinkPlugin as C, StandardLink as a }; | ||
| export type { StandardLinkTransport as S, StandardLinkOptions as b, StandardLinkPlugin as c, StandardLinkTransportInterceptorOptions as d, StandardLinkInterceptorOptions as e, StandardLinkCodec as f, StandardLinkCodecDecodedResponse as g, StandardLinkInterceptor as h, StandardLinkTransportInterceptor as i }; |
| import { isPlainObject, wrapAsyncIterator, isTypescriptObject, NullProtoObj, isAsyncIteratorObject, stringifyJSON } from '@orpc/shared'; | ||
| import { getEventMeta, withEventMeta, ErrorEvent } from '@standardserver/core'; | ||
| import { O as ORPCError } from './client.CPcOxSex.mjs'; | ||
| function isInferableError(error) { | ||
| return error instanceof ORPCError && error.inferable; | ||
| } | ||
| function toORPCError(error) { | ||
| return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", { cause: error }); | ||
| } | ||
| function isORPCErrorJson(json) { | ||
| if (!isPlainObject(json)) { | ||
| return false; | ||
| } | ||
| const validKeys = ["defined", "inferable", "code", "message", "data"]; | ||
| if (Object.keys(json).some((k) => !validKeys.includes(k))) { | ||
| return false; | ||
| } | ||
| return "defined" in json && typeof json.defined === "boolean" && "inferable" in json && typeof json.inferable === "boolean" && "code" in json && typeof json.code === "string" && "message" in json && typeof json.message === "string"; | ||
| } | ||
| function createORPCErrorFromJson(json, options = {}) { | ||
| const error = new ORPCError(json.code, { | ||
| ...json, | ||
| ...options | ||
| }); | ||
| error.defined = json.defined; | ||
| error.inferable = json.inferable; | ||
| return error; | ||
| } | ||
| function cloneORPCError(error) { | ||
| const cloned = new ORPCError(error.code, { | ||
| ...error, | ||
| message: error.message, | ||
| data: error.data, | ||
| cause: error.cause | ||
| }); | ||
| cloned.stack = error.stack; | ||
| cloned.defined = error.defined; | ||
| cloned.inferable = error.inferable; | ||
| return cloned; | ||
| } | ||
| function wrapAsyncIteratorPreservingEventMeta(iterator, { mapResult, mapError, ...rest }) { | ||
| return wrapAsyncIterator(iterator, { | ||
| ...rest, | ||
| mapResult: mapResult && (async (result) => { | ||
| const mapped = await mapResult(result); | ||
| if (mapped.value !== result.value) { | ||
| const meta = getEventMeta(result.value); | ||
| if (meta && isTypescriptObject(mapped.value)) { | ||
| return { done: mapped.done, value: withEventMeta(mapped.value, meta) }; | ||
| } | ||
| } | ||
| return mapped; | ||
| }), | ||
| mapError: mapError && (async (error) => { | ||
| const mapped = await mapError(error); | ||
| if (mapped !== error) { | ||
| const meta = getEventMeta(error); | ||
| if (meta && isTypescriptObject(mapped)) { | ||
| return withEventMeta(mapped, meta); | ||
| } | ||
| } | ||
| return mapped; | ||
| }) | ||
| }); | ||
| } | ||
| const REGEX_STRING_PATTERN = /^\/([\s\S]*)\/([a-z]*)$/; | ||
| const DEFAULT_RPC_JSON_SERIALIZER_HANDLERS = { | ||
| undefined: { | ||
| condition(data) { | ||
| return data === void 0; | ||
| }, | ||
| serialize() { | ||
| return null; | ||
| }, | ||
| deserialize() { | ||
| return void 0; | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| bigint: { | ||
| condition(data) { | ||
| return typeof data === "bigint"; | ||
| }, | ||
| serialize(data) { | ||
| return data.toString(); | ||
| }, | ||
| deserialize(serialized) { | ||
| return BigInt(serialized); | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| date: { | ||
| condition(data) { | ||
| return data instanceof Date; | ||
| }, | ||
| serialize(data) { | ||
| if (Number.isNaN(data.getTime())) { | ||
| return null; | ||
| } | ||
| return data.toISOString(); | ||
| }, | ||
| deserialize(serialized) { | ||
| return new Date(serialized ?? "Invalid Date"); | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| nan: { | ||
| condition(data) { | ||
| return typeof data === "number" && Number.isNaN(data); | ||
| }, | ||
| serialize() { | ||
| return null; | ||
| }, | ||
| deserialize() { | ||
| return Number.NaN; | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| url: { | ||
| condition(data) { | ||
| return data instanceof URL; | ||
| }, | ||
| serialize(data) { | ||
| return data.toString(); | ||
| }, | ||
| deserialize(serialized) { | ||
| return new URL(serialized); | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| regexp: { | ||
| condition(data) { | ||
| return data instanceof RegExp; | ||
| }, | ||
| serialize(data) { | ||
| return data.toString(); | ||
| }, | ||
| deserialize(serialized) { | ||
| const [, pattern, flags] = serialized.match(REGEX_STRING_PATTERN); | ||
| return new RegExp(pattern, flags); | ||
| }, | ||
| isTerminal: true | ||
| }, | ||
| set: { | ||
| condition(data) { | ||
| return data instanceof Set; | ||
| }, | ||
| serialize(data) { | ||
| return Array.from(data); | ||
| }, | ||
| deserialize(serialized) { | ||
| return new Set(serialized); | ||
| } | ||
| }, | ||
| map: { | ||
| condition(data) { | ||
| return data instanceof Map; | ||
| }, | ||
| serialize(data) { | ||
| return Array.from(data.entries()); | ||
| }, | ||
| deserialize(serialized) { | ||
| return new Map(serialized); | ||
| } | ||
| } | ||
| }; | ||
| class RPCJsonSerializer { | ||
| handlers; | ||
| inlineBuiltInHandlers; | ||
| handlerEntries; | ||
| omitUndefinedProperties; | ||
| constructor(options = {}) { | ||
| this.omitUndefinedProperties = options.omitUndefinedProperties !== false; | ||
| this.handlers = Object.assign(new NullProtoObj(), DEFAULT_RPC_JSON_SERIALIZER_HANDLERS); | ||
| const customHandlers = options.handlers; | ||
| if (customHandlers === void 0) { | ||
| this.inlineBuiltInHandlers = true; | ||
| return; | ||
| } | ||
| let inlineBuiltInHandlers = true; | ||
| let handlerEntries = []; | ||
| for (const key in customHandlers) { | ||
| const handler = customHandlers[key]; | ||
| this.handlers[key] = handler; | ||
| if (inlineBuiltInHandlers && key in DEFAULT_RPC_JSON_SERIALIZER_HANDLERS) { | ||
| inlineBuiltInHandlers = false; | ||
| } | ||
| if (inlineBuiltInHandlers && handler !== void 0) { | ||
| handlerEntries.push([key, handler]); | ||
| } | ||
| } | ||
| if (!inlineBuiltInHandlers) { | ||
| handlerEntries = []; | ||
| for (const key in this.handlers) { | ||
| const handler = this.handlers[key]; | ||
| if (handler !== void 0) { | ||
| handlerEntries.push([key, handler]); | ||
| } | ||
| } | ||
| } | ||
| this.inlineBuiltInHandlers = inlineBuiltInHandlers; | ||
| this.handlerEntries = handlerEntries; | ||
| } | ||
| serialize(data) { | ||
| let meta = []; | ||
| const maps = []; | ||
| const blobs = []; | ||
| const json = this.serializeValue(data, [], meta, maps, blobs); | ||
| meta = meta.length === 0 ? void 0 : meta; | ||
| if (maps.length === 0) { | ||
| return { json, meta }; | ||
| } | ||
| return { json, meta, maps, blobs }; | ||
| } | ||
| /** | ||
| * `segments` is a shared mutable stack (push/pop while walking), | ||
| * so it must be copied before being stored in `meta` or `maps`. | ||
| */ | ||
| serializeValue(data, segments, meta, maps, blobs) { | ||
| if (this.inlineBuiltInHandlers) { | ||
| switch (typeof data) { | ||
| case "string": | ||
| case "boolean": | ||
| return data; | ||
| case "number": | ||
| if (Number.isNaN(data)) { | ||
| meta.push(["nan", ...segments]); | ||
| return null; | ||
| } | ||
| return data; | ||
| case "undefined": | ||
| meta.push(["undefined", ...segments]); | ||
| return null; | ||
| case "bigint": | ||
| meta.push(["bigint", ...segments]); | ||
| return data.toString(); | ||
| case "object": { | ||
| if (data === null) { | ||
| return data; | ||
| } | ||
| if (data instanceof Date) { | ||
| meta.push(["date", ...segments]); | ||
| return Number.isNaN(data.getTime()) ? null : data.toISOString(); | ||
| } | ||
| if (data instanceof URL) { | ||
| meta.push(["url", ...segments]); | ||
| return data.toString(); | ||
| } | ||
| if (data instanceof RegExp) { | ||
| meta.push(["regexp", ...segments]); | ||
| return data.toString(); | ||
| } | ||
| if (data instanceof Set) { | ||
| const result = this.serializeValue(Array.from(data), segments, meta, maps, blobs); | ||
| meta.push(["set", ...segments]); | ||
| return result; | ||
| } | ||
| if (data instanceof Map) { | ||
| const result = this.serializeValue(Array.from(data.entries()), segments, meta, maps, blobs); | ||
| meta.push(["map", ...segments]); | ||
| return result; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| const handlerEntries = this.handlerEntries; | ||
| if (handlerEntries) { | ||
| for (let i = 0; i < handlerEntries.length; i++) { | ||
| const entry = handlerEntries[i]; | ||
| const handler = entry[1]; | ||
| if (handler.condition(data)) { | ||
| const serialized = handler.serialize(data); | ||
| if (handler.isTerminal) { | ||
| meta.push([entry[0], ...segments]); | ||
| if (serialized instanceof Blob) { | ||
| maps.push(segments.slice()); | ||
| blobs.push(serialized); | ||
| } | ||
| return serialized; | ||
| } | ||
| const result = this.serializeValue(serialized, segments, meta, maps, blobs); | ||
| meta.push([entry[0], ...segments]); | ||
| return result; | ||
| } | ||
| } | ||
| } | ||
| if (data instanceof Blob) { | ||
| maps.push(segments.slice()); | ||
| blobs.push(data); | ||
| return data; | ||
| } | ||
| if (Array.isArray(data)) { | ||
| const json = []; | ||
| for (let i = 0; i < data.length; i++) { | ||
| segments.push(i); | ||
| json.push(this.serializeValue(data[i], segments, meta, maps, blobs)); | ||
| segments.pop(); | ||
| } | ||
| return json; | ||
| } | ||
| if (isPlainObject(data)) { | ||
| const json = new NullProtoObj(); | ||
| for (const k in data) { | ||
| const v = data[k]; | ||
| if (k === "toJSON" && typeof v === "function") { | ||
| continue; | ||
| } | ||
| if (v === void 0 && this.omitUndefinedProperties) { | ||
| continue; | ||
| } | ||
| segments.push(k); | ||
| json[k] = this.serializeValue(v, segments, meta, maps, blobs); | ||
| segments.pop(); | ||
| } | ||
| return json; | ||
| } | ||
| return data; | ||
| } | ||
| deserialize(serialized) { | ||
| const ref = { data: serialized.json }; | ||
| if (serialized.blobs?.length) { | ||
| for (let i = 0; i < serialized.maps.length; i++) { | ||
| const segments = serialized.maps[i]; | ||
| let currentRef = ref; | ||
| let preSegment = "data"; | ||
| for (let j = 0; j < segments.length; j++) { | ||
| currentRef = currentRef[preSegment]; | ||
| preSegment = segments[j]; | ||
| if (!Object.hasOwn(currentRef, preSegment)) { | ||
| throw new Error(`Security error: Invalid serialized data. Segment "${preSegment}" does not exist.`); | ||
| } | ||
| } | ||
| currentRef[preSegment] = serialized.blobs[i]; | ||
| } | ||
| } | ||
| if (serialized.meta) { | ||
| for (const item of serialized.meta) { | ||
| const type = item[0]; | ||
| let currentRef = ref; | ||
| let preSegment = "data"; | ||
| for (let i = 1; i < item.length; i++) { | ||
| currentRef = currentRef[preSegment]; | ||
| preSegment = item[i]; | ||
| if (!Object.hasOwn(currentRef, preSegment)) { | ||
| throw new Error(`Security error: Invalid serialized data. Segment "${preSegment}" does not exist.`); | ||
| } | ||
| } | ||
| currentRef[preSegment] = this.handlers[type].deserialize(currentRef[preSegment]); | ||
| } | ||
| } | ||
| return ref.data; | ||
| } | ||
| } | ||
| class RPCSerializer { | ||
| jsonSerializer; | ||
| defaultSerializeOptions; | ||
| constructor(options = {}) { | ||
| this.jsonSerializer = new RPCJsonSerializer(options); | ||
| this.defaultSerializeOptions = options.serialize; | ||
| } | ||
| serialize(data, options = {}) { | ||
| if (data === void 0 || data instanceof ReadableStream || data instanceof Blob) { | ||
| return data; | ||
| } | ||
| if (isAsyncIteratorObject(data)) { | ||
| return wrapAsyncIteratorPreservingEventMeta(data, { | ||
| mapResult: (result) => { | ||
| if (result.value === void 0) { | ||
| return result; | ||
| } | ||
| return { done: result.done, value: this.serializeValue(result.value, false) }; | ||
| }, | ||
| mapError: (e) => new ErrorEvent( | ||
| this.serializeValue(toORPCError(e).toJSON(), false), | ||
| { cause: e } | ||
| ) | ||
| }); | ||
| } | ||
| const useFormDataForBlobs = options.useFormDataForBlobFields ?? this.defaultSerializeOptions?.useFormDataForBlobFields ?? true; | ||
| return this.serializeValue(data, useFormDataForBlobs); | ||
| } | ||
| serializeValue(data, useFormDataForBlobs) { | ||
| const { json, meta, maps, blobs } = this.jsonSerializer.serialize(data); | ||
| if (!useFormDataForBlobs || !blobs?.length) { | ||
| return { json, meta }; | ||
| } | ||
| const form = new FormData(); | ||
| form.set("data", stringifyJSON({ json, meta, maps })); | ||
| blobs.forEach((blob, i) => { | ||
| form.set(i.toString(), blob); | ||
| }); | ||
| return form; | ||
| } | ||
| deserialize(data) { | ||
| if (data === void 0 || data instanceof ReadableStream || data instanceof Blob) { | ||
| return data; | ||
| } | ||
| if (isAsyncIteratorObject(data)) { | ||
| return wrapAsyncIteratorPreservingEventMeta(data, { | ||
| mapResult: (result) => { | ||
| if (result.value === void 0) { | ||
| return result; | ||
| } | ||
| return { done: result.done, value: this.deserializeValue(result.value) }; | ||
| }, | ||
| mapError: (e) => { | ||
| if (!(e instanceof ErrorEvent)) { | ||
| return e; | ||
| } | ||
| const deserialized = this.deserializeValue(e.data); | ||
| if (isORPCErrorJson(deserialized)) { | ||
| return createORPCErrorFromJson(deserialized, { cause: e }); | ||
| } | ||
| return new ErrorEvent(deserialized, { cause: e }); | ||
| } | ||
| }); | ||
| } | ||
| return this.deserializeValue(data); | ||
| } | ||
| deserializeValue(data) { | ||
| if (!(data instanceof FormData)) { | ||
| return this.jsonSerializer.deserialize(data); | ||
| } | ||
| const serialized = JSON.parse(data.get("data")); | ||
| const blobs = []; | ||
| for (const [key, value] of data) { | ||
| if (value instanceof Blob) { | ||
| blobs[Number(key)] = value; | ||
| } | ||
| } | ||
| return this.jsonSerializer.deserialize({ ...serialized, blobs }); | ||
| } | ||
| } | ||
| export { RPCSerializer as R, isInferableError as a, RPCJsonSerializer as b, createORPCErrorFromJson as c, cloneORPCError as d, isORPCErrorJson as i, toORPCError as t, wrapAsyncIteratorPreservingEventMeta as w }; |
| import { PromiseWithError, Registry, MaybeOptionalOptions } from '@orpc/shared'; | ||
| interface ClientContext { | ||
| [key: PropertyKey]: any; | ||
| } | ||
| interface ClientOptions<T extends ClientContext> { | ||
| signal?: AbortSignal | undefined; | ||
| lastEventId?: string | undefined; | ||
| context: T; | ||
| } | ||
| type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (object extends T ? { | ||
| context?: T; | ||
| } : { | ||
| context: T; | ||
| }); | ||
| type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>]; | ||
| interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> { | ||
| (...rest: ClientRest<TClientContext, TInput>): PromiseWithError<TOutput, TError>; | ||
| } | ||
| type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | { | ||
| [k: string]: NestedClient<TClientContext>; | ||
| }; | ||
| type AnyNestedClient = NestedClient<any>; | ||
| /** | ||
| * Infers the **client context type** required by a client. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-context | Client-Side Clients - Infer Client Context} | ||
| */ | ||
| type InferClientContext<T extends AnyNestedClient> = T extends NestedClient<infer U> ? U : never; | ||
| interface ClientLink<TClientContext extends ClientContext> { | ||
| call: (path: string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>; | ||
| } | ||
| /** | ||
| * Recursively infers the **input types** from a client. | ||
| * | ||
| * Produces a nested map where each endpoint's input type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-inputs | Client-Side Clients - Infer Client Inputs} | ||
| */ | ||
| type InferClientInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientInputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **body input types** from a client. | ||
| * | ||
| * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted. | ||
| * Produces a nested map of body input types. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-inputs | Client-Side Clients - Infer Client Body Inputs} | ||
| */ | ||
| type InferClientBodyInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U extends { | ||
| body: infer UBody; | ||
| } ? UBody : U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyInputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **output types** from a client. | ||
| * | ||
| * Produces a nested map where each endpoint's output type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-outputs | Client-Side Clients - Infer Client Outputs} | ||
| */ | ||
| type InferClientOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientOutputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **body output types** from a client. | ||
| * | ||
| * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted. | ||
| * Produces a nested map of body output types. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-outputs | Client-Side Clients - Infer Client Body Outputs} | ||
| */ | ||
| type InferClientBodyOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U extends { | ||
| body: infer UBody; | ||
| } ? UBody : U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyOutputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors). | ||
| * | ||
| * Produces a nested map where each endpoint's error type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-errors | Client-Side Clients - Infer Client Errors} | ||
| */ | ||
| type InferClientErrors<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientErrors<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors). | ||
| * | ||
| * Useful when you want to handle all possible errors from any endpoint at once. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-error | Client-Side Clients - Infer Client Error} | ||
| */ | ||
| type InferClientError<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientError<T[K]> : never; | ||
| }[keyof T]; | ||
| /** | ||
| * Default mapping between common oRPC error codes and HTTP status codes. | ||
| * Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response} | ||
| * @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response} | ||
| */ | ||
| declare const COMMON_ERROR_STATUS_MAP: { | ||
| BAD_REQUEST: number; | ||
| UNAUTHORIZED: number; | ||
| PAYMENT_REQUIRED: number; | ||
| FORBIDDEN: number; | ||
| NOT_FOUND: number; | ||
| METHOD_NOT_SUPPORTED: number; | ||
| NOT_ACCEPTABLE: number; | ||
| TIMEOUT: number; | ||
| CONFLICT: number; | ||
| GONE: number; | ||
| PRECONDITION_FAILED: number; | ||
| PAYLOAD_TOO_LARGE: number; | ||
| UNSUPPORTED_MEDIA_TYPE: number; | ||
| UNPROCESSABLE_CONTENT: number; | ||
| PRECONDITION_REQUIRED: number; | ||
| TOO_MANY_REQUESTS: number; | ||
| CLIENT_CLOSED_REQUEST: number; | ||
| INTERNAL_SERVER_ERROR: number; | ||
| NOT_IMPLEMENTED: number; | ||
| BAD_GATEWAY: number; | ||
| SERVICE_UNAVAILABLE: number; | ||
| GATEWAY_TIMEOUT: number; | ||
| }; | ||
| type ORPCErrorCode = Registry extends { | ||
| ORPCErrorCode: infer T extends string; | ||
| } ? T : (keyof typeof COMMON_ERROR_STATUS_MAP) | (string & {}); | ||
| type ORPCErrorOptions<TData> = ErrorOptions & { | ||
| message?: string; | ||
| } & (undefined extends TData ? { | ||
| data?: TData; | ||
| } : { | ||
| data: TData; | ||
| }); | ||
| /** | ||
| * Typed error carrying a `code`, a `message`, and optional `data`. | ||
| * Throw it from handlers or middleware to produce typed error responses on the client. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class} | ||
| */ | ||
| declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error { | ||
| /** | ||
| * @remarks | ||
| * **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish | ||
| * an `ORPCError` instance from plain objects with a similar structure. | ||
| */ | ||
| readonly name: "ORPCError" & { | ||
| __branch: "ORPCError"; | ||
| }; | ||
| /** | ||
| * Indicates whether the error matches a definition in the procedure's `.errors` map. | ||
| */ | ||
| readonly defined: boolean; | ||
| /** | ||
| * Indicates whether the error's type is inferable at the TypeScript level. | ||
| * This is typically true when the error is explicitly defined or returned within a handler. | ||
| */ | ||
| readonly inferable: boolean; | ||
| code: TCode; | ||
| data: TData; | ||
| constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>); | ||
| toJSON(): ORPCErrorJSON<TCode, TData>; | ||
| /** | ||
| * Workaround for Next.js where different contexts use separate | ||
| * dependency graphs, causing multiple ORPCError constructors existing and breaking | ||
| * `instanceof` checks across contexts. | ||
| * | ||
| * This is particularly problematic with "Optimized SSR", where orpc-client | ||
| * executes in one context but is invoked from another. When an error is thrown | ||
| * in the execution context, `instanceof ORPCError` checks fail in the | ||
| * invocation context due to separate class constructors. | ||
| * | ||
| * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue. | ||
| */ | ||
| static [Symbol.hasInstance](instance: unknown): boolean; | ||
| } | ||
| interface ORPCErrorJSON<TCode extends string, TData> extends Pick<ORPCError<TCode, TData>, 'code' | 'message' | 'data'> { | ||
| /** | ||
| * remove readonly | ||
| */ | ||
| defined: boolean; | ||
| /** | ||
| * remove readonly | ||
| */ | ||
| inferable: boolean; | ||
| } | ||
| type AnyORPCError = ORPCError<any, any>; | ||
| type AnyORPCErrorJSON = ORPCErrorJSON<any, any>; | ||
| export { ORPCError as g, COMMON_ERROR_STATUS_MAP as j }; | ||
| export type { AnyORPCError as A, ClientContext as C, FriendlyClientOptions as F, InferClientContext as I, NestedClient as N, ORPCErrorCode as O, ClientOptions as a, ClientLink as b, AnyNestedClient as c, InferClientError as d, Client as e, ClientRest as f, ORPCErrorJSON as h, AnyORPCErrorJSON as i, InferClientBodyInputs as k, InferClientBodyOutputs as l, InferClientErrors as m, InferClientInputs as n, InferClientOutputs as o, ORPCErrorOptions as p }; |
| import { PromiseWithError, Registry, MaybeOptionalOptions } from '@orpc/shared'; | ||
| interface ClientContext { | ||
| [key: PropertyKey]: any; | ||
| } | ||
| interface ClientOptions<T extends ClientContext> { | ||
| signal?: AbortSignal | undefined; | ||
| lastEventId?: string | undefined; | ||
| context: T; | ||
| } | ||
| type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (object extends T ? { | ||
| context?: T; | ||
| } : { | ||
| context: T; | ||
| }); | ||
| type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>]; | ||
| interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> { | ||
| (...rest: ClientRest<TClientContext, TInput>): PromiseWithError<TOutput, TError>; | ||
| } | ||
| type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | { | ||
| [k: string]: NestedClient<TClientContext>; | ||
| }; | ||
| type AnyNestedClient = NestedClient<any>; | ||
| /** | ||
| * Infers the **client context type** required by a client. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-context | Client-Side Clients - Infer Client Context} | ||
| */ | ||
| type InferClientContext<T extends AnyNestedClient> = T extends NestedClient<infer U> ? U : never; | ||
| interface ClientLink<TClientContext extends ClientContext> { | ||
| call: (path: string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>; | ||
| } | ||
| /** | ||
| * Recursively infers the **input types** from a client. | ||
| * | ||
| * Produces a nested map where each endpoint's input type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-inputs | Client-Side Clients - Infer Client Inputs} | ||
| */ | ||
| type InferClientInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientInputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **body input types** from a client. | ||
| * | ||
| * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted. | ||
| * Produces a nested map of body input types. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-inputs | Client-Side Clients - Infer Client Body Inputs} | ||
| */ | ||
| type InferClientBodyInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U extends { | ||
| body: infer UBody; | ||
| } ? UBody : U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyInputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **output types** from a client. | ||
| * | ||
| * Produces a nested map where each endpoint's output type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-outputs | Client-Side Clients - Infer Client Outputs} | ||
| */ | ||
| type InferClientOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientOutputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **body output types** from a client. | ||
| * | ||
| * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted. | ||
| * Produces a nested map of body output types. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-outputs | Client-Side Clients - Infer Client Body Outputs} | ||
| */ | ||
| type InferClientBodyOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U extends { | ||
| body: infer UBody; | ||
| } ? UBody : U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyOutputs<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors). | ||
| * | ||
| * Produces a nested map where each endpoint's error type is preserved. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-errors | Client-Side Clients - Infer Client Errors} | ||
| */ | ||
| type InferClientErrors<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientErrors<T[K]> : never; | ||
| }; | ||
| /** | ||
| * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors). | ||
| * | ||
| * Useful when you want to handle all possible errors from any endpoint at once. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/client/client-side#infer-client-error | Client-Side Clients - Infer Client Error} | ||
| */ | ||
| type InferClientError<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { | ||
| [K in keyof T]: T[K] extends AnyNestedClient ? InferClientError<T[K]> : never; | ||
| }[keyof T]; | ||
| /** | ||
| * Default mapping between common oRPC error codes and HTTP status codes. | ||
| * Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response} | ||
| * @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response} | ||
| */ | ||
| declare const COMMON_ERROR_STATUS_MAP: { | ||
| BAD_REQUEST: number; | ||
| UNAUTHORIZED: number; | ||
| PAYMENT_REQUIRED: number; | ||
| FORBIDDEN: number; | ||
| NOT_FOUND: number; | ||
| METHOD_NOT_SUPPORTED: number; | ||
| NOT_ACCEPTABLE: number; | ||
| TIMEOUT: number; | ||
| CONFLICT: number; | ||
| GONE: number; | ||
| PRECONDITION_FAILED: number; | ||
| PAYLOAD_TOO_LARGE: number; | ||
| UNSUPPORTED_MEDIA_TYPE: number; | ||
| UNPROCESSABLE_CONTENT: number; | ||
| PRECONDITION_REQUIRED: number; | ||
| TOO_MANY_REQUESTS: number; | ||
| CLIENT_CLOSED_REQUEST: number; | ||
| INTERNAL_SERVER_ERROR: number; | ||
| NOT_IMPLEMENTED: number; | ||
| BAD_GATEWAY: number; | ||
| SERVICE_UNAVAILABLE: number; | ||
| GATEWAY_TIMEOUT: number; | ||
| }; | ||
| type ORPCErrorCode = Registry extends { | ||
| ORPCErrorCode: infer T extends string; | ||
| } ? T : (keyof typeof COMMON_ERROR_STATUS_MAP) | (string & {}); | ||
| type ORPCErrorOptions<TData> = ErrorOptions & { | ||
| message?: string; | ||
| } & (undefined extends TData ? { | ||
| data?: TData; | ||
| } : { | ||
| data: TData; | ||
| }); | ||
| /** | ||
| * Typed error carrying a `code`, a `message`, and optional `data`. | ||
| * Throw it from handlers or middleware to produce typed error responses on the client. | ||
| * | ||
| * @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class} | ||
| */ | ||
| declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error { | ||
| /** | ||
| * @remarks | ||
| * **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish | ||
| * an `ORPCError` instance from plain objects with a similar structure. | ||
| */ | ||
| readonly name: "ORPCError" & { | ||
| __branch: "ORPCError"; | ||
| }; | ||
| /** | ||
| * Indicates whether the error matches a definition in the procedure's `.errors` map. | ||
| */ | ||
| readonly defined: boolean; | ||
| /** | ||
| * Indicates whether the error's type is inferable at the TypeScript level. | ||
| * This is typically true when the error is explicitly defined or returned within a handler. | ||
| */ | ||
| readonly inferable: boolean; | ||
| code: TCode; | ||
| data: TData; | ||
| constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>); | ||
| toJSON(): ORPCErrorJSON<TCode, TData>; | ||
| /** | ||
| * Workaround for Next.js where different contexts use separate | ||
| * dependency graphs, causing multiple ORPCError constructors existing and breaking | ||
| * `instanceof` checks across contexts. | ||
| * | ||
| * This is particularly problematic with "Optimized SSR", where orpc-client | ||
| * executes in one context but is invoked from another. When an error is thrown | ||
| * in the execution context, `instanceof ORPCError` checks fail in the | ||
| * invocation context due to separate class constructors. | ||
| * | ||
| * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue. | ||
| */ | ||
| static [Symbol.hasInstance](instance: unknown): boolean; | ||
| } | ||
| interface ORPCErrorJSON<TCode extends string, TData> extends Pick<ORPCError<TCode, TData>, 'code' | 'message' | 'data'> { | ||
| /** | ||
| * remove readonly | ||
| */ | ||
| defined: boolean; | ||
| /** | ||
| * remove readonly | ||
| */ | ||
| inferable: boolean; | ||
| } | ||
| type AnyORPCError = ORPCError<any, any>; | ||
| type AnyORPCErrorJSON = ORPCErrorJSON<any, any>; | ||
| export { ORPCError as g, COMMON_ERROR_STATUS_MAP as j }; | ||
| export type { AnyORPCError as A, ClientContext as C, FriendlyClientOptions as F, InferClientContext as I, NestedClient as N, ORPCErrorCode as O, ClientOptions as a, ClientLink as b, AnyNestedClient as c, InferClientError as d, Client as e, ClientRest as f, ORPCErrorJSON as h, AnyORPCErrorJSON as i, InferClientBodyInputs as k, InferClientBodyOutputs as l, InferClientErrors as m, InferClientInputs as n, InferClientOutputs as o, ORPCErrorOptions as p }; |
210670
0.31%3169
0.22%+ Added
- Removed
Updated