@trpc/client
Version:
370 lines • 16.6 kB
text/typescript
import { t as TRPCConnectionState } from "./subscriptions-DcqRZc4h.cjs";
import { a as OperationResultEnvelope, c as TRPCClientRuntime, d as TRPCClientError, f as TRPCClientErrorBase, g as NativeFetchEsque, h as FetchEsque, i as OperationLink, l as TRPCFetch, m as isTRPCClientError, n as Operation, o as OperationResultObservable, p as TRPCClientErrorLike, r as OperationContext, s as OperationResultObserver, t as HTTPHeaders, u as TRPCLink, v as TRPCProcedureOptions } from "./types-BrCJd1zp.cjs";
import { n as TransformerOptions } from "./unstable-internals-CNoyg7Yf.cjs";
import { n as HTTPBatchLinkOptions, t as httpBatchLink } from "./httpBatchLink-CRRfyw0c.cjs";
import { n as httpLink, t as HTTPLinkOptions } from "./httpLink-Bc4oLWCJ.cjs";
import { n as loggerLink, t as LoggerLinkOptions } from "./loggerLink-BEMtA7V5.cjs";
import { t as splitLink } from "./splitLink-i7EskO_m.cjs";
import { a as WebSocketClientOptions, c as jsonEncoder, i as createWSClient, n as wsLink, o as UrlOptionsWithConnectionParams, r as TRPCWebSocketClient, s as Encoder, t as WebSocketLinkOptions } from "./wsLink-CPkrJOns.cjs";
import { AnyClientTypes, AnyProcedure, AnyRouter, ErrorHandlerOptions, EventSourceLike, InferrableClientTypes, ProcedureType, RouterRecord, TypeError, inferAsyncIterableYield, inferClientTypes, inferProcedureErrorShape, inferProcedureInput, inferRouterContext, inferTransformedProcedureOutput } from "@trpc/server/unstable-core-do-not-import";
import { Unsubscribable } from "@trpc/server/observable";
import { AnyRouter as AnyRouter$1 } from "@trpc/server";
//#region src/links/internals/contentTypes.d.ts
/** Whether an input is binary: a `Uint8Array`, `Blob` or `File`. */
export declare function isOctetType(input: unknown): input is Uint8Array<ArrayBuffer> | Blob;
/** Whether an input is `FormData`. */
export declare function isFormData(input: unknown): input is FormData;
/**
* Whether an input can't be sent as JSON: binary data or `FormData`. Use
* it in a `splitLink` to send such inputs with `httpLink`.
* @see https://trpc.io/docs/server/non-json-content-types#client-setup
*/
export declare function isNonJsonSerializable(input: unknown): input is Blob | FormData | Uint8Array<ArrayBuffer>;
//#endregion
//#region src/internals/TRPCUntypedClient.d.ts
/** The options of a call made with the untyped client. */
interface TRPCRequestOptions {
/**
* Context for the links, such as a flag a `splitLink` reads.
* @see https://trpc.io/docs/client/links#managing-context
*/
context?: OperationContext;
/**
* Aborts the call. With `httpBatchLink`, the request is only aborted once
* every call in its batch is, so an aborted call can still get a result.
*/
signal?: AbortSignal;
}
/** The callbacks a subscription takes on the client. */
interface TRPCSubscriptionObserver<TValue, TError> {
/** Called when the link sends a `started` result. */
onStarted: (opts: {
context: OperationContext | undefined;
}) => void;
/** Called with each event. */
onData: (value: inferAsyncIterableYield<TValue>) => void;
/** Called when the subscription ends with an error. */
onError: (err: TError) => void;
/**
* Called when the link sends a `stopped` result. Not every link sends
* one; `localLink` doesn't.
*/
onStopped: () => void;
/** Called when the subscription's observable completes, for any reason. */
onComplete: () => void;
/** Called when the connection connects, drops or reconnects. */
onConnectionStateChange: (state: TRPCConnectionState<TError>) => void;
}
/**
* The options of `createTRPCClient`.
* @internal
*/
type CreateTRPCClientOptions<TRouter extends InferrableClientTypes> = {
/**
* The links each call goes through, in order. The last one must send
* the call, such as `httpBatchLink`.
* @see https://trpc.io/docs/client/links
*/
links: TRPCLink<TRouter>[];
transformer?: TypeError<'The transformer property has moved to httpLink/httpBatchLink/wsLink'>;
};
/**
* A client that calls procedures by path string, without types.
* `createTRPCClient` wraps one.
*/
export declare class TRPCUntypedClient<TInferrable extends InferrableClientTypes> {
private readonly links;
readonly runtime: TRPCClientRuntime;
private requestId;
constructor(opts: CreateTRPCClientOptions<TInferrable>);
private $request;
private requestAsPromise;
/** Calls a query. */
query(path: string, input?: unknown, opts?: TRPCRequestOptions): Promise<unknown>;
/** Calls a mutation. */
mutation(path: string, input?: unknown, opts?: TRPCRequestOptions): Promise<unknown>;
/** Starts a subscription. Returns what stops it. */
subscription(path: string, input: unknown, opts: Partial<TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>> & TRPCRequestOptions): Unsubscribable;
}
//#endregion
//#region src/createTRPCUntypedClient.d.ts
/**
* Creates a client that calls procedures by path string, without types.
* Meant for libraries built on tRPC; apps should use `createTRPCClient`.
*/
export declare function createTRPCUntypedClient<TRouter extends AnyRouter>(opts: CreateTRPCClientOptions<TRouter>): TRPCUntypedClient<TRouter>;
//#endregion
//#region src/safe.d.ts
/**
* @internal
*/
declare const errorShapeTag: unique symbol;
/**
* The promise a client's `.query()` or `.mutate()` returns, tagged with
* the procedure's error shape for `safe()`.
*/
type TRPCTaggedPromise<TData, TErrorShape> = Promise<TData> & {
readonly [errorShapeTag]: TErrorShape;
};
/**
* @internal
*/
type inferSafeError<TErrorShape> = TRPCClientError<{
errorShape: TErrorShape;
transformer: boolean;
}>;
/**
* What `safe()` resolves to: `[data, undefined]` or `[undefined, error]`.
* @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe
*/
type SafeResult<TData, TErrorShape> = readonly [data: TData, error: undefined] | readonly [data: undefined, error: inferSafeError<TErrorShape>];
/**
* Awaits a client `.query()` or `.mutate()` call without throwing, and
* returns a `[data, error]` pair typed with the procedure's error shape.
*
* @example
* ```ts
* const [post, error] = await safe(client.post.byId.query({ id }));
* if (error) {
* console.error(error);
* }
*
* const id = post.id;
* ```
* @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe
*/
export declare function safe<TData, TErrorShape>(promise: TRPCTaggedPromise<TData, TErrorShape>): Promise<SafeResult<TData, TErrorShape>>;
//#endregion
//#region src/createTRPCClient.d.ts
/**
* The type of a client for a router.
* @deprecated Use {@link TRPCClient} instead. This will be removed in v12.
* @public
**/
export type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;
/**
* The type of a client for a router.
* @deprecated Use {@link TRPCClient} instead. This will be removed in v12.
* @public
**/
export type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;
declare const untypedClientSymbol: unique symbol;
/**
* A typed client for a router, as `createTRPCClient` returns it. Each
* procedure has `.query()`, `.mutate()` or `.subscribe()`.
* @see https://trpc.io/docs/client/vanilla/infer-types
* @public
**/
export type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<{
transformer: TRouter['_def']['_config']['$types']['transformer'];
errorShape: TRouter['_def']['_config']['$types']['errorShape'];
}, TRouter['_def']['record']> & {
[untypedClientSymbol]: TRPCUntypedClient<TRouter>;
};
/**
* A procedure's types, as the client sees them.
* @internal
*/
export type TRPCResolverDef = {
input: any;
output: any;
transformer: boolean;
errorShape: any;
};
type coerceAsyncGeneratorToIterable<T> = T extends AsyncGenerator<infer $T, infer $Return, infer $Next> ? AsyncIterable<$T, $Return, $Next> : T;
/**
* The `.query()` or `.mutate()` of a procedure on the client.
* @internal
*/
export type Resolver<TDef extends TRPCResolverDef> = (input: TDef['input'], opts?: TRPCProcedureOptions) => TRPCTaggedPromise<coerceAsyncGeneratorToIterable<TDef['output']>, TDef['errorShape']>;
/**
* The `.subscribe()` of a subscription procedure on the client.
* @internal
*/
export type SubscriptionResolver<TDef extends TRPCResolverDef> = (input: TDef['input'], opts: Partial<TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>> & TRPCProcedureOptions) => Unsubscribable;
type DecorateProcedure<TType extends ProcedureType, TDef extends TRPCResolverDef> = TType extends 'query' ? {
query: Resolver<TDef>;
} : TType extends 'mutation' ? {
mutate: Resolver<TDef>;
} : TType extends 'subscription' ? {
subscribe: SubscriptionResolver<TDef>;
} : never;
/**
* @internal
*/
type DecoratedProcedureRecord<TRoot extends InferrableClientTypes, TRecord extends RouterRecord> = { [TKey in keyof TRecord]: TRecord[TKey] extends (infer $Value) ? $Value extends AnyProcedure ? DecorateProcedure<$Value['_def']['type'], {
input: inferProcedureInput<$Value>;
output: inferTransformedProcedureOutput<inferClientTypes<TRoot>, $Value>;
errorShape: inferProcedureErrorShape<TRoot, $Value>;
transformer: inferClientTypes<TRoot>['transformer'];
}> : $Value extends RouterRecord ? DecoratedProcedureRecord<TRoot, $Value> : never : never; };
/**
* The procedure type of a client method: `query`, `mutate` or `subscribe`.
* @internal
*/
export declare const clientCallTypeToProcedureType: (clientCallType: string) => ProcedureType;
/**
* Wraps an untyped client in the typed proxy `createTRPCClient` returns.
* @internal
*/
export declare function createTRPCClientProxy<TRouter extends AnyRouter>(client: TRPCUntypedClient<TRouter>): TRPCClient<TRouter>;
/**
* Creates a typed client for a router. Pass the router's type, and the
* links that send its calls.
* @example
* ```ts
* const client = createTRPCClient<AppRouter>({
* links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],
* });
* const post = await client.post.byId.query({ id: '1' });
* ```
* @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client
*/
export declare function createTRPCClient<TRouter extends AnyRouter>(opts: CreateTRPCClientOptions<TRouter>): TRPCClient<TRouter>;
/**
* The untyped client behind a typed client, which calls procedures by
* path string.
* @internal
*/
export declare function getUntypedClient<TRouter extends AnyRouter>(client: TRPCClient<TRouter>): TRPCUntypedClient<TRouter>;
//#endregion
//#region src/getFetch.d.ts
/**
* The `fetch` to use: `customFetchImpl` if given, or else the global one.
* Throws if there's none.
*/
export declare function getFetch(customFetchImpl?: FetchEsque | NativeFetchEsque): FetchEsque;
//#endregion
//#region src/links/httpBatchStreamLink.d.ts
/**
* Options for {@link httpBatchStreamLink}. Takes the same options as
* `httpBatchLink`, plus `streamHeader`.
*
* @see https://trpc.io/docs/client/links/httpBatchStreamLink#options
*/
export type HTTPBatchStreamLinkOptions<TRoot extends AnyClientTypes> = HTTPBatchLinkOptions<TRoot> & {
/**
* Which header to use to signal the server that the client wants a streaming response.
* - `'trpc-accept'` (default): sends `trpc-accept: application/jsonl` header
* - `'accept'`: sends `Accept: application/jsonl` header, which can avoid CORS preflight for cross-origin streaming queries. Be aware that `application/jsonl` is not an official MIME type and so this is not completely spec-compliant - you should test that your infrastructure supports this value.
* @default 'trpc-accept'
*/
streamHeader?: 'trpc-accept' | 'accept';
};
/**
* A terminating link that batches calls like `httpBatchLink`, but streams each
* response back as soon as it is ready.
*
* @see https://trpc.io/docs/client/links/httpBatchStreamLink
*/
export declare function httpBatchStreamLink<TRouter extends AnyRouter$1>(opts: HTTPBatchStreamLinkOptions<TRouter['_def']['_config']['$types']>): TRPCLink<TRouter>;
/**
* @deprecated Use {@link httpBatchStreamLink} instead.
*/
export declare const unstable_httpBatchStreamLink: typeof httpBatchStreamLink;
//#endregion
//#region src/links/httpSubscriptionLink.d.ts
/**
* @see https://trpc.io/docs/client/links/httpSubscriptionLink#httpsubscriptionlink-options
*/
type HTTPSubscriptionLinkOptions<TRoot extends AnyClientTypes, TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource> = {
/**
* The `EventSource` class to use, for runtimes that don't have one.
* @see https://trpc.io/docs/client/links/httpSubscriptionLink#custom-headers-through-ponyfill
*/
EventSource?: TEventSource;
/**
* Options passed to the `EventSource`, or a function that returns them for
* each subscription.
*/
eventSourceOptions?: EventSourceLike.InitDictOf<TEventSource> | ((opts: {
op: Operation;
}) => EventSourceLike.InitDictOf<TEventSource> | Promise<EventSourceLike.InitDictOf<TEventSource>>);
} & TransformerOptions<TRoot> & UrlOptionsWithConnectionParams;
/**
* A terminating link that runs subscriptions over Server-Sent Events.
*
* @see https://trpc.io/docs/client/links/httpSubscriptionLink
*/
export declare function httpSubscriptionLink<TInferrable extends InferrableClientTypes, TEventSource extends EventSourceLike.AnyConstructor>(opts: HTTPSubscriptionLinkOptions<inferClientTypes<TInferrable>, TEventSource>): TRPCLink<TInferrable>;
/**
* @deprecated Use {@link httpSubscriptionLink} instead.
*/
export declare const unstable_httpSubscriptionLink: typeof httpSubscriptionLink;
//#endregion
//#region src/links/retryLink.d.ts
interface RetryLinkOptions<TInferrable extends InferrableClientTypes> {
/**
* The retry function
*/
retry: (opts: RetryFnOptions<TInferrable>) => boolean;
/**
* The delay between retries in ms (defaults to 0)
*/
retryDelayMs?: (attempt: number) => number;
}
interface RetryFnOptions<TInferrable extends InferrableClientTypes> {
/**
* The operation that failed
*/
op: Operation;
/**
* The error that occurred
*/
error: TRPCClientError<TInferrable>;
/**
* The number of attempts that have been made (including the first call)
*/
attempts: number;
}
/**
* Retries failed operations. Subscriptions resume from the last tracked event
* id.
*
* @see https://trpc.io/docs/client/links/retryLink
*/
export declare function retryLink<TInferrable extends InferrableClientTypes>(opts: RetryLinkOptions<TInferrable>): TRPCLink<TInferrable>;
//#endregion
//#region src/links/localLink.d.ts
/**
* Options for {@link localLink}.
*
* @see https://trpc.io/docs/client/links/localLink#options
*/
export type LocalLinkOptions<TRouter extends AnyRouter> = {
/**
* The router to call.
* @see https://trpc.io/docs/client/links/localLink#router
*/
router: TRouter;
/**
* Creates the context for each call.
* @see https://trpc.io/docs/client/links/localLink#createcontext
*/
createContext: () => Promise<inferRouterContext<TRouter>>;
/**
* Called when a procedure throws.
* @see https://trpc.io/docs/client/links/localLink#onerror
*/
onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;
} & TransformerOptions<inferClientTypes<TRouter>>;
/**
* A terminating link that calls procedures on a router in the same process,
* without HTTP.
*
* @see https://trpc.io/docs/client/links/localLink
*/
export declare function localLink<TRouter extends AnyRouter>(opts: LocalLinkOptions<TRouter>): TRPCLink<TRouter>;
/**
* @deprecated Use {@link localLink} instead.
* @function
*/
export declare const unstable_localLink: typeof localLink;
/**
* @deprecated Use {@link localLink} instead. This alias will be removed in a
* future major release.
*/
export declare const experimental_localLink: typeof localLink;
//#endregion
export { type CreateTRPCClientOptions, type Encoder, HTTPBatchLinkOptions, HTTPHeaders, HTTPLinkOptions, LoggerLinkOptions, Operation, OperationContext, OperationLink, OperationResultEnvelope, OperationResultObservable, OperationResultObserver, type SafeResult, TRPCClientError, TRPCClientErrorBase, TRPCClientErrorLike, TRPCClientRuntime, TRPCFetch, TRPCLink, type TRPCProcedureOptions, type TRPCTaggedPromise as TRPCPromise, type TRPCRequestOptions, type TRPCWebSocketClient, type WebSocketClientOptions, WebSocketLinkOptions, createTRPCClient as createTRPCProxyClient, createWSClient, httpBatchLink, httpLink, type inferRouterClient as inferRouterProxyClient, isTRPCClientError, jsonEncoder, loggerLink, splitLink, wsLink };
//# sourceMappingURL=index.d.cts.map