@trpc/client 11.33.0 → 11.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{httpBatchLink-_bkMj4mk.d.cts → httpBatchLink-50xXDyIp.d.cts} +3 -3
- package/dist/{httpBatchLink-DaVHWlLU.d.mts.map → httpBatchLink-50xXDyIp.d.cts.map} +1 -1
- package/dist/{httpBatchLink-DaVHWlLU.d.mts → httpBatchLink-D4shlyQy.d.mts} +3 -3
- package/dist/{httpBatchLink-_bkMj4mk.d.cts.map → httpBatchLink-D4shlyQy.d.mts.map} +1 -1
- package/dist/{httpLink-DN_Ana7a.d.mts → httpLink-Bb6hOyBN.d.mts} +3 -3
- package/dist/{httpLink-DN_Ana7a.d.mts.map → httpLink-Bb6hOyBN.d.mts.map} +1 -1
- package/dist/{httpUtils-BAs5frdP.d.mts → httpUtils-BbinScxw.d.mts} +2 -2
- package/dist/{httpUtils-1z6dzl3V.d.cts.map → httpUtils-BbinScxw.d.mts.map} +1 -1
- package/dist/{httpUtils-1z6dzl3V.d.cts → httpUtils-dB1XeokQ.d.cts} +2 -2
- package/dist/{httpUtils-BAs5frdP.d.mts.map → httpUtils-dB1XeokQ.d.cts.map} +1 -1
- package/dist/index.cjs +4 -3
- package/dist/index.d.cts +34 -11
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +37 -14
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +4 -3
- package/dist/index.mjs.map +1 -1
- package/dist/links/httpBatchLink.d.cts +1 -1
- package/dist/links/httpBatchLink.d.mts +1 -1
- package/dist/links/httpLink.d.cts +2 -2
- package/dist/links/httpLink.d.mts +1 -1
- package/dist/links/loggerLink.d.cts +1 -1
- package/dist/links/loggerLink.d.mts +1 -1
- package/dist/links/splitLink.cjs +1 -1
- package/dist/links/splitLink.d.cts +29 -8
- package/dist/links/splitLink.d.cts.map +1 -1
- package/dist/links/splitLink.d.mts +1 -1
- package/dist/links/splitLink.mjs +1 -1
- package/dist/links/wsLink/wsLink.d.cts +1 -1
- package/dist/links/wsLink/wsLink.d.mts +1 -1
- package/dist/{loggerLink-CiVinJOG.d.mts → loggerLink-y1x7WTWX.d.mts} +2 -2
- package/dist/{loggerLink-CiVinJOG.d.mts.map → loggerLink-y1x7WTWX.d.mts.map} +1 -1
- package/dist/splitLink-BGLTgm1a.d.mts +56 -0
- package/dist/splitLink-BGLTgm1a.d.mts.map +1 -0
- package/dist/{splitLink-IUbsOwO6.mjs → splitLink-C8U8vvLl.mjs} +10 -12
- package/dist/splitLink-C8U8vvLl.mjs.map +1 -0
- package/dist/{splitLink-BQoYcpdp.cjs → splitLink-NqS85b92.cjs} +9 -11
- package/dist/{types-DW0iJUBU.d.mts → types-BZH1P86I.d.mts} +3 -3
- package/dist/types-BZH1P86I.d.mts.map +1 -0
- package/dist/{types-DMe6B4SV.d.cts → types-CGS36fjk.d.cts} +3 -3
- package/dist/{types-DMe6B4SV.d.cts.map → types-CGS36fjk.d.cts.map} +1 -1
- package/dist/{wsLink-DX5fv7-H.d.mts → wsLink-CFh-pvQG.d.mts} +2 -2
- package/dist/{wsLink-DX5fv7-H.d.mts.map → wsLink-CFh-pvQG.d.mts.map} +1 -1
- package/dist/{wsLink-DuyXOEPt.d.cts → wsLink-CJT5pqFt.d.cts} +2 -2
- package/dist/{wsLink-DuyXOEPt.d.cts.map → wsLink-CJT5pqFt.d.cts.map} +1 -1
- package/package.json +3 -3
- package/skills/client-setup/SKILL.md +1 -1
- package/skills/links/SKILL.md +3 -3
- package/skills/links/references/client-links-retryLink.md +28 -0
- package/skills/links/references/client-links-splitLink.md +22 -6
- package/skills/superjson/SKILL.md +1 -1
- package/src/createTRPCClient.ts +5 -2
- package/src/links/retryLink.ts +41 -10
- package/src/links/splitLink.ts +85 -14
- package/src/links/types.ts +5 -2
- package/dist/splitLink-ClFN_nbg.d.mts +0 -35
- package/dist/splitLink-ClFN_nbg.d.mts.map +0 -1
- package/dist/splitLink-IUbsOwO6.mjs.map +0 -1
- package/dist/types-DW0iJUBU.d.mts.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/internals/TRPCUntypedClient.ts","../src/createTRPCUntypedClient.ts","../src/createTRPCClient.ts","../src/routerType.ts","../src/links/httpBatchStreamLink.ts","../src/internals/inputWithTrackedEventId.ts","../src/links/httpSubscriptionLink.ts","../src/links/retryLink.ts","../src/links/localLink.ts","../src/safe.ts"],"sourcesContent":["import type {\n inferObservableValue,\n Unsubscribable,\n} from '@trpc/server/observable';\nimport {\n observable,\n observableToAsyncIterable,\n observableToPromise,\n share,\n} from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferAsyncIterableYield,\n InferrableClientTypes,\n Maybe,\n TypeError,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { createChain } from '../links/internals/createChain';\nimport type { TRPCConnectionState } from '../links/internals/subscriptions';\nimport type {\n OperationContext,\n OperationLink,\n TRPCClientRuntime,\n TRPCLink,\n} from '../links/types';\nimport { TRPCClientError } from '../TRPCClientError';\n\ntype TRPCType = 'mutation' | 'query' | 'subscription';\n/** The options of a call made with the untyped client. */\nexport interface TRPCRequestOptions {\n /**\n * Context for the links, such as a flag a `splitLink` reads.\n * @see https://trpc.io/docs/client/links#managing-context\n */\n context?: OperationContext;\n /**\n * Aborts the call. With `httpBatchLink`, the request is only aborted once\n * every call in its batch is, so an aborted call can still get a result.\n */\n signal?: AbortSignal;\n}\n\n/** The callbacks a subscription takes on the client. */\nexport interface TRPCSubscriptionObserver<TValue, TError> {\n /** Called when the link sends a `started` result. */\n onStarted: (opts: { context: OperationContext | undefined }) => void;\n /** Called with each event. */\n onData: (value: inferAsyncIterableYield<TValue>) => void;\n /** Called when the subscription ends with an error. */\n onError: (err: TError) => void;\n /**\n * Called when the link sends a `stopped` result. Not every link sends\n * one; `localLink` doesn't.\n */\n onStopped: () => void;\n /** Called when the subscription's observable completes, for any reason. */\n onComplete: () => void;\n /** Called when the connection connects, drops or reconnects. */\n onConnectionStateChange: (state: TRPCConnectionState<TError>) => void;\n}\n\ntype ObserverKey = keyof TRPCSubscriptionObserver<unknown, unknown>;\n\n/**\n * Subscription options without callbacks: `TOpts` must not have any of the\n * callback keys, not even set to `undefined`.\n * @internal\n */\nexport type TRPCSubscriptionWithoutCallbacks<TOpts> = TOpts & {\n // `keyof` a union only has its shared keys, so this one catches each member\n [TKey in ObserverKey]?: never;\n} & {\n [TKey in keyof TOpts & ObserverKey]: never;\n};\n\n/**\n * Subscription callbacks, at least one of which is defined.\n * @internal\n */\nexport type TRPCSubscriptionCallbacks<TValue, TError> = Partial<\n TRPCSubscriptionObserver<TValue, TError>\n> &\n {\n [TKey in ObserverKey]: Pick<TRPCSubscriptionObserver<TValue, TError>, TKey>;\n }[ObserverKey];\n\nconst observerKeys: ObserverKey[] = [\n 'onStarted',\n 'onData',\n 'onError',\n 'onStopped',\n 'onComplete',\n 'onConnectionStateChange',\n];\n\n/**\n * The options of `createTRPCClient`.\n * @internal\n */\nexport type CreateTRPCClientOptions<TRouter extends InferrableClientTypes> = {\n /**\n * The links each call goes through, in order. The last one must send\n * the call, such as `httpBatchLink`.\n * @see https://trpc.io/docs/client/links\n */\n links: TRPCLink<TRouter>[];\n transformer?: TypeError<'The transformer property has moved to httpLink/httpBatchLink/wsLink'>;\n};\n\n/**\n * A client that calls procedures by path string, without types.\n * `createTRPCClient` wraps one.\n */\nexport class TRPCUntypedClient<TInferrable extends InferrableClientTypes> {\n private readonly links: OperationLink<TInferrable>[];\n public readonly runtime: TRPCClientRuntime;\n private requestId: number;\n\n constructor(opts: CreateTRPCClientOptions<TInferrable>) {\n this.requestId = 0;\n\n this.runtime = {};\n\n // Initialize the links\n this.links = opts.links.map((link) => link(this.runtime));\n }\n\n private $request<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }) {\n const chain$ = createChain<AnyRouter, TInput, TOutput>({\n links: this.links as OperationLink<any, any, any>[],\n op: {\n ...opts,\n context: opts.context ?? {},\n id: ++this.requestId,\n },\n });\n return chain$.pipe(share());\n }\n\n private async requestAsPromise<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }): Promise<TOutput> {\n try {\n const req$ = this.$request<TInput, TOutput>(opts);\n type TValue = inferObservableValue<typeof req$>;\n\n const envelope = await observableToPromise<TValue>(req$);\n const data = (envelope.result as any).data;\n return data;\n } catch (err) {\n throw TRPCClientError.from(err as Error);\n }\n }\n /** Calls a query. */\n public query(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'query',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n /** Calls a mutation. */\n public mutation(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'mutation',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n /**\n * Starts a subscription. With callbacks, returns what stops it. Without,\n * returns an async iterator to read it with `for await`, which `signal`,\n * `break` or `return()` stops. It can be iterated once.\n * @see https://trpc.io/docs/client/vanilla/setup#5-use-subscriptions\n */\n public subscription(\n path: string,\n input: unknown,\n opts: TRPCSubscriptionCallbacks<unknown, TRPCClientError<AnyRouter>> &\n TRPCRequestOptions,\n ): Unsubscribable;\n public subscription<\n TOpts extends TRPCRequestOptions &\n Partial<TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>> =\n TRPCRequestOptions,\n >(\n path: string,\n input: unknown,\n opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,\n ): AsyncIterableIterator<unknown>;\n public subscription(\n path: string,\n input: unknown,\n opts: Partial<\n TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>\n > &\n TRPCRequestOptions = {},\n ): Unsubscribable | AsyncIterableIterator<unknown> {\n const hasCallbacks = observerKeys.some(\n (key) => typeof opts[key] === 'function',\n );\n const observable$ = this.$request({\n type: 'subscription',\n path,\n input,\n context: opts.context,\n signal: opts.signal,\n });\n if (!hasCallbacks) {\n const data$ = observable<unknown, TRPCClientError<AnyRouter>>(\n (observer) =>\n observable$.subscribe({\n next(envelope) {\n if (\n envelope.result.type === 'data' ||\n envelope.result.type === undefined\n ) {\n observer.next(envelope.result.data);\n }\n },\n error: (err) => observer.error(err),\n complete: () => observer.complete(),\n }),\n );\n const iterator = observableToAsyncIterable(\n data$,\n opts.signal ?? new AbortController().signal,\n );\n // a second loop over the same iterator would split the data with the\n // first, or end straight away once the first has left\n let iterated = false;\n iterator[Symbol.asyncIterator] = () => {\n if (iterated) {\n throw new Error(\n 'A subscription can only be iterated once. Call subscribe() again for another loop.',\n );\n }\n iterated = true;\n return iterator;\n };\n return iterator;\n }\n return observable$.subscribe({\n next(envelope) {\n switch (envelope.result.type) {\n case 'state': {\n opts.onConnectionStateChange?.(envelope.result);\n break;\n }\n case 'started': {\n opts.onStarted?.({\n context: envelope.context,\n });\n break;\n }\n case 'stopped': {\n opts.onStopped?.();\n break;\n }\n case 'data':\n case undefined: {\n opts.onData?.(envelope.result.data);\n break;\n }\n }\n },\n error(err) {\n opts.onError?.(err);\n },\n complete() {\n opts.onComplete?.();\n },\n });\n }\n}\n","import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n\n/**\n * Creates a client that calls procedures by path string, without types.\n * Meant for libraries built on tRPC; apps should use `createTRPCClient`.\n */\nexport function createTRPCUntypedClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return new TRPCUntypedClient(opts);\n}\n\nexport type {\n CreateTRPCClientOptions,\n TRPCRequestOptions,\n} from './internals/TRPCUntypedClient';\nexport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n","/* oxlint-disable typescript/no-non-null-assertion */\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport type {\n AnyProcedure,\n AnyRouter,\n inferAsyncIterableYield,\n inferClientTypes,\n inferProcedureErrorShape,\n inferProcedureInput,\n InferrableClientTypes,\n inferTransformedProcedureOutput,\n ProcedureType,\n RouterRecord,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n createFlatProxy,\n createRecursiveProxy,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './createTRPCUntypedClient';\nimport type {\n TRPCSubscriptionCallbacks,\n TRPCSubscriptionObserver,\n TRPCSubscriptionWithoutCallbacks,\n} from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\nimport type { TRPCProcedureOptions } from './internals/types';\nimport type { inferLinksContext, TRPCLink } from './links/types';\nimport type { RouterType } from './routerType';\nimport type { TRPCTaggedPromise } from './safe';\nimport type { TRPCClientError } from './TRPCClientError';\n\n/**\n * The type of a client for a router.\n * @deprecated Use {@link TRPCClient} instead. This will be removed in v12.\n * @public\n **/\nexport type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\n/**\n * The type of a client for a router.\n * @deprecated Use {@link TRPCClient} instead. This will be removed in v12.\n * @public\n **/\nexport type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\nconst untypedClientSymbol = Symbol.for('trpc_untypedClient');\n\n/**\n * A typed client for a router, as `createTRPCClient` returns it. Each\n * procedure has `.query()`, `.mutate()` or `.subscribe()`.\n *\n * `TContext` is the `context` calls take; `createTRPCClient({ router,\n * links })` infers it from the links.\n * @see https://trpc.io/docs/client/vanilla/infer-types\n * @public\n **/\nexport type TRPCClient<\n TRouter extends AnyRouter,\n TContext extends object = Record<string, unknown>,\n> = DecoratedProcedureRecord<\n {\n transformer: TRouter['_def']['_config']['$types']['transformer'];\n errorShape: TRouter['_def']['_config']['$types']['errorShape'];\n },\n TRouter['_def']['record'],\n TContext\n> & {\n [untypedClientSymbol]: TRPCUntypedClient<TRouter>;\n};\n\n/**\n * A procedure's types, as the client sees them.\n * @internal\n */\nexport type TRPCResolverDef = {\n input: any;\n output: any;\n transformer: boolean;\n errorShape: any;\n};\n\ntype coerceAsyncGeneratorToIterable<T> =\n T extends AsyncGenerator<infer $T, infer $Return, infer $Next>\n ? AsyncIterable<$T, $Return, $Next>\n : T;\n\n/**\n * The `.query()` or `.mutate()` of a procedure on the client.\n * @internal\n */\nexport type Resolver<\n TDef extends TRPCResolverDef,\n TContext extends object = Record<string, unknown>,\n> = (\n input: TDef['input'],\n opts?: TRPCProcedureOptions<TContext>,\n) => TRPCTaggedPromise<\n coerceAsyncGeneratorToIterable<TDef['output']>,\n TDef['errorShape']\n>;\n\n/**\n * The `.subscribe()` of a subscription procedure on the client.\n * @internal\n */\nexport type SubscriptionResolver<\n TDef extends TRPCResolverDef,\n TContext extends object = Record<string, unknown>,\n> = {\n (\n input: TDef['input'],\n opts: TRPCSubscriptionCallbacks<TDef['output'], TRPCClientError<TDef>> &\n TRPCProcedureOptions<TContext>,\n ): Unsubscribable;\n <\n TOpts extends TRPCProcedureOptions<TContext> &\n Partial<TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>> =\n TRPCProcedureOptions<TContext>,\n >(\n input: TDef['input'],\n opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,\n ): AsyncIterableIterator<inferAsyncIterableYield<TDef['output']>>;\n};\n\ntype DecorateProcedure<\n TType extends ProcedureType,\n TDef extends TRPCResolverDef,\n TContext extends object,\n> = TType extends 'query'\n ? { query: Resolver<TDef, TContext> }\n : TType extends 'mutation'\n ? { mutate: Resolver<TDef, TContext> }\n : TType extends 'subscription'\n ? { subscribe: SubscriptionResolver<TDef, TContext> }\n : never;\n\n/**\n * @internal\n */\ntype DecoratedProcedureRecord<\n TRoot extends InferrableClientTypes,\n TRecord extends RouterRecord,\n TContext extends object,\n> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<\n $Value['_def']['type'],\n {\n input: inferProcedureInput<$Value>;\n output: inferTransformedProcedureOutput<\n inferClientTypes<TRoot>,\n $Value\n >;\n errorShape: inferProcedureErrorShape<TRoot, $Value>;\n transformer: inferClientTypes<TRoot>['transformer'];\n },\n TContext\n >\n : $Value extends RouterRecord\n ? DecoratedProcedureRecord<TRoot, $Value, TContext>\n : never\n : never;\n};\n\nconst clientCallTypeMap: Record<\n keyof DecorateProcedure<any, any, any>,\n ProcedureType\n> = {\n query: 'query',\n mutate: 'mutation',\n subscribe: 'subscription',\n};\n\n/**\n * The procedure type of a client method: `query`, `mutate` or `subscribe`.\n * @internal\n */\nexport const clientCallTypeToProcedureType = (\n clientCallType: string,\n): ProcedureType => {\n return clientCallTypeMap[clientCallType as keyof typeof clientCallTypeMap];\n};\n\n/**\n * Wraps an untyped client in the typed proxy `createTRPCClient` returns.\n * @internal\n */\nexport function createTRPCClientProxy<TRouter extends AnyRouter>(\n client: TRPCUntypedClient<TRouter>,\n): TRPCClient<TRouter> {\n const proxy = createRecursiveProxy<TRPCClient<TRouter>>(({ path, args }) => {\n const pathCopy = [...path];\n const procedureType = clientCallTypeToProcedureType(pathCopy.pop()!);\n\n const fullPath = pathCopy.join('.');\n\n return (client[procedureType] as any)(fullPath, ...(args as any));\n });\n return createFlatProxy<TRPCClient<TRouter>>((key) => {\n if (key === untypedClientSymbol) {\n return client;\n }\n return proxy[key];\n });\n}\n\n/**\n * The options of `createTRPCClient` with the router's type passed as\n * `router: routerType<AppRouter>()`.\n * @public\n */\nexport type CreateTRPCClientWithRouterOptions<\n TRouter extends AnyRouter,\n TLinks extends readonly TRPCLink<TRouter, any>[] = TRPCLink<TRouter>[],\n> = Omit<CreateTRPCClientOptions<TRouter>, 'links'> & {\n /**\n * The router's type, from `routerType<AppRouter>()`. It's a type only:\n * nothing about the router is sent or bundled.\n */\n router: RouterType<TRouter>;\n /**\n * The links each call goes through, in order. The last one must send\n * the call, such as `httpBatchLink`. What they declare types each call's\n * `context`, and which methods the client has. Pass them inline or\n * `as const`: in an array declared without it, TypeScript can merge the\n * links' types and drop what one declares.\n * @see https://trpc.io/docs/client/links\n */\n links: TLinks;\n};\n\n/**\n * Creates a typed client for a router. Pass the router's type with\n * `routerType`, and the links that send its calls. What the links declare\n * types each call's `context`.\n * @example\n * ```ts\n * const client = createTRPCClient({\n * router: routerType<AppRouter>(),\n * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n * });\n * const post = await client.post.byId.query({ id: '1' });\n * ```\n * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n */\nexport function createTRPCClient<\n TRouter extends AnyRouter,\n // with an explicit router type, the links aren't inferred\n const TLinks extends readonly TRPCLink<TRouter, any>[] = TRPCLink<TRouter>[],\n>(\n opts: CreateTRPCClientWithRouterOptions<TRouter, TLinks>,\n): TRPCClient<TRouter, inferLinksContext<TLinks>>;\n/**\n * Creates a typed client for a router. Pass the router's type, and the\n * links that send its calls.\n * @example\n * ```ts\n * const client = createTRPCClient<AppRouter>({\n * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n * });\n * const post = await client.post.byId.query({ id: '1' });\n * ```\n * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n */\n// Kept last: `ReturnType<typeof createTRPCClient>` reads the last overload.\nexport function createTRPCClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCClient<TRouter>;\nexport function createTRPCClient<TRouter extends AnyRouter>(\n opts: Omit<CreateTRPCClientOptions<TRouter>, 'links'> & {\n links: readonly TRPCLink<TRouter, any>[];\n },\n): TRPCClient<TRouter> {\n // `router` is a type only, so the untyped client ignores it\n const client = new TRPCUntypedClient<TRouter>({\n links: [...opts.links],\n });\n const proxy = createTRPCClientProxy<TRouter>(client);\n return proxy;\n}\n\n/**\n * The untyped client behind a typed client, which calls procedures by\n * path string.\n * @internal\n */\nexport function getUntypedClient<TRouter extends AnyRouter>(\n client: TRPCClient<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return client[untypedClientSymbol];\n}\n","import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\n\ndeclare const routerTypeBrand: unique symbol;\n\n/**\n * A value that carries a router's type and nothing else. Made by\n * {@link routerType}.\n * @public\n */\nexport interface RouterType<TRouter extends AnyRouter> {\n readonly [routerTypeBrand]: TRouter;\n}\n\n/**\n * Passes a router's type to `createTRPCClient({ router })` as a normal\n * option, instead of a type argument. Nothing about the router exists at\n * runtime, so it's safe to import the router's type only.\n *\n * @example\n * ```ts\n * const client = createTRPCClient({\n * router: routerType<AppRouter>(),\n * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n * });\n * ```\n * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n * @public\n */\nexport function routerType<TRouter extends AnyRouter>(): RouterType<TRouter> {\n return {} as RouterType<TRouter>;\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResponse } from '@trpc/server/rpc';\nimport type { AnyClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { jsonlStreamConsumer } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport {\n allAbortSignals,\n raceAbortSignals,\n raceAbortSignalsWithCleanup,\n} from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n fetchHTTPResponse,\n getBody,\n getUrl,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { AugmentedOperationContext, Operation, TRPCLink } from './types';\n\n/**\n * Options for {@link httpBatchStreamLink}. Takes the same options as\n * `httpBatchLink`, plus `streamHeader`.\n *\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink#options\n */\nexport type HTTPBatchStreamLinkOptions<TRoot extends AnyClientTypes> =\n HTTPBatchLinkOptions<TRoot> & {\n /**\n * Which header to use to signal the server that the client wants a streaming response.\n * - `'trpc-accept'` (default): sends `trpc-accept: application/jsonl` header\n * - `'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.\n * @default 'trpc-accept'\n */\n streamHeader?: 'trpc-accept' | 'accept';\n };\n\ntype BatchStreamOperation = Operation & {\n releaseSignal: () => void;\n /** Aborts the op's signal once its response has nothing left to stream */\n settle: () => void;\n};\n\n/**\n * A terminating link that batches calls like `httpBatchLink`, but streams each\n * response back as soon as it is ready.\n *\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink\n */\nexport function httpBatchStreamLink<TRouter extends AnyRouter>(\n opts: HTTPBatchStreamLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<\n TRouter,\n // its callbacks may read the fields added to `OperationContext`\n { context: AugmentedOperationContext }\n> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<BatchStreamOperation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const batchSignals = allAbortSignals(\n ...batchOps.map((op) => op.signal),\n );\n const abortController = new AbortController();\n abortController.signal.addEventListener(\n 'abort',\n () => {\n for (const op of batchOps) {\n op.releaseSignal();\n }\n },\n { once: true },\n );\n\n const responsePromise = fetchHTTPResponse({\n ...resolvedOpts,\n signal: raceAbortSignals(batchSignals, abortController.signal),\n type,\n contentTypeHeader: 'application/json',\n trpcAcceptHeader: 'application/jsonl',\n trpcAcceptHeaderKey: opts.streamHeader ?? 'trpc-accept',\n getUrl,\n getBody,\n inputs,\n path,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<BatchStreamOperation>,\n });\n }\n return opts.headers;\n },\n });\n\n const res = await responsePromise;\n\n if (!res.ok) {\n // Server returned a non-2xx response (e.g. batching disabled).\n // The body is plain JSON, not JSONL, so parse it directly and\n // propagate the same error to every operation in the batch.\n const json = (await res.json()) as TRPCResponse;\n if ('error' in json) {\n json.error = resolvedOpts.transformer.output.deserialize(\n json.error,\n );\n }\n\n return batchOps.map((): Promise<HTTPResult> =>\n Promise.resolve({\n json,\n meta: {\n response: res,\n },\n }),\n );\n }\n\n const [head] = await jsonlStreamConsumer<\n Record<string, Promise<any>>\n >({\n // oxlint-disable-next-line typescript/no-non-null-assertion\n from: res.body!,\n deserialize: (data) =>\n resolvedOpts.transformer.output.deserialize(data),\n onError: () => abortController.abort(),\n // An op with nothing left to stream must not hold the batch open.\n onSettled: (settled) => batchOps[Number(settled.key)]?.settle(),\n formatError(opts) {\n const error = opts.error as TRPCErrorShape;\n return TRPCClientError.from({\n error,\n });\n },\n abortController,\n });\n const promises = Object.keys(batchOps).map(\n async (key): Promise<HTTPResult> => {\n let json: TRPCResponse = await Promise.resolve(head[key]);\n\n if ('result' in json) {\n /**\n * Not very pretty, but we need to unwrap nested data as promises\n * Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n */\n const result = await Promise.resolve(json.result);\n json = {\n result: {\n data: await Promise.resolve(result.data),\n },\n };\n }\n\n return {\n json,\n meta: {\n response: res,\n },\n };\n },\n );\n return promises;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const { signal, cleanup } = raceAbortSignalsWithCleanup(\n op.signal,\n ac.signal,\n );\n const promise = loader.load({\n ...op,\n signal,\n releaseSignal: cleanup,\n settle: () => ac.abort(),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n if ('error' in res.json) {\n // A failed op has nothing left to stream, so it must not hold the batch open.\n ac.abort();\n observer.error(\n TRPCClientError.from(res.json, {\n meta: res.meta,\n }),\n );\n return;\n } else if ('result' in res.json) {\n observer.next({\n context: res.meta,\n result: res.json.result,\n });\n observer.complete();\n return;\n }\n\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n ac.abort();\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n\n/**\n * @deprecated Use {@link httpBatchStreamLink} instead.\n */\nexport const unstable_httpBatchStreamLink = httpBatchStreamLink;\n","import { isPlainObject } from '@trpc/server/unstable-core-do-not-import';\n\nexport function inputWithTrackedEventId(\n input: unknown,\n lastEventId: string | undefined,\n) {\n if (!lastEventId) {\n return input;\n }\n // Spreading an array, a `Date` or a class instance would corrupt it, so only\n // a plain object can carry the id.\n if (input != null && !isPlainObject(input)) {\n return input;\n }\n return {\n ...(input ?? {}),\n lastEventId,\n };\n}\n","import { behaviorSubject, observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResult } from '@trpc/server/rpc';\nimport type {\n AnyClientTypes,\n EventSourceLike,\n inferClientTypes,\n InferrableClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n resolvePathSeparator,\n retryableRpcCodes,\n run,\n sseStreamConsumer,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport { raceAbortSignals } from '../internals/signals';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from '../unstable-internals';\nimport { getTransformer, type TransformerOptions } from '../unstable-internals';\nimport { getUrl, type HTTPLinkBaseOptions } from './internals/httpUtils';\nimport {\n resultOf,\n type UrlOptionsWithConnectionParams,\n} from './internals/urlWithConnectionParams';\nimport type { AugmentedOperationContext, Operation, TRPCLink } from './types';\n\nasync function urlWithConnectionParams(\n opts: UrlOptionsWithConnectionParams,\n): Promise<string> {\n let url = await resultOf(opts.url);\n if (opts.connectionParams) {\n const params = await resultOf(opts.connectionParams);\n\n const prefix = url.includes('?') ? '&' : '?';\n url +=\n prefix + 'connectionParams=' + encodeURIComponent(JSON.stringify(params));\n }\n\n return url;\n}\n\n/**\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink#httpsubscriptionlink-options\n */\ntype HTTPSubscriptionLinkOptions<\n TRoot extends AnyClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource,\n> = {\n /**\n * The `EventSource` class to use, for runtimes that don't have one.\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink#custom-headers-through-ponyfill\n */\n EventSource?: TEventSource;\n /**\n * Options passed to the `EventSource`, or a function that returns them for\n * each subscription.\n */\n eventSourceOptions?:\n | EventSourceLike.InitDictOf<TEventSource>\n | ((opts: {\n op: Operation;\n }) =>\n | EventSourceLike.InitDictOf<TEventSource>\n | Promise<EventSourceLike.InitDictOf<TEventSource>>);\n} & Pick<HTTPLinkBaseOptions<TRoot>, 'pathSeparator'> &\n TransformerOptions<TRoot> &\n UrlOptionsWithConnectionParams;\n\n/**\n * A terminating link that runs subscriptions over Server-Sent Events.\n *\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink\n */\nexport function httpSubscriptionLink<\n TInferrable extends InferrableClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor,\n>(\n opts: HTTPSubscriptionLinkOptions<\n inferClientTypes<TInferrable>,\n TEventSource\n >,\n): TRPCLink<\n TInferrable,\n // its callbacks may read the fields added to `OperationContext`\n { context: AugmentedOperationContext }\n> {\n const transformer = getTransformer(opts.transformer);\n const pathSeparator = resolvePathSeparator(opts.pathSeparator);\n\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n const { type, path, input } = op;\n\n /* istanbul ignore if -- @preserve */\n if (type !== 'subscription') {\n throw new Error('httpSubscriptionLink only supports subscriptions');\n }\n\n let lastEventId: string | undefined = undefined;\n const ac = new AbortController();\n const signal = raceAbortSignals(op.signal, ac.signal);\n const eventSourceStream = sseStreamConsumer<{\n EventSource: TEventSource;\n data: Partial<{\n id?: string;\n data: unknown;\n }>;\n error: TRPCErrorShape;\n }>({\n url: async () =>\n getUrl({\n transformer,\n url: await urlWithConnectionParams(opts),\n input: inputWithTrackedEventId(input, lastEventId),\n path,\n pathSeparator,\n type,\n signal: null,\n }),\n init: () => resultOf(opts.eventSourceOptions, { op }),\n signal,\n deserialize: (data) => transformer.output.deserialize(data),\n EventSource: opts.EventSource ?? (globalThis.EventSource as never),\n });\n\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n run(async () => {\n for await (const chunk of eventSourceStream) {\n switch (chunk.type) {\n case 'ping':\n // do nothing\n break;\n case 'data':\n const chunkData = chunk.data;\n\n let result: TRPCResult<unknown>;\n if (chunkData.id) {\n // if the `tracked()`-helper is used, we always have an `id` field\n lastEventId = chunkData.id;\n result = {\n id: chunkData.id,\n data: chunkData,\n };\n } else {\n result = {\n data: chunkData.data,\n };\n }\n\n observer.next({\n result,\n context: {\n eventSource: chunk.eventSource,\n },\n });\n break;\n case 'connected': {\n observer.next({\n result: {\n type: 'started',\n },\n context: {\n eventSource: chunk.eventSource,\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n break;\n }\n case 'serialized-error': {\n const error = TRPCClientError.from({ error: chunk.error });\n\n if (retryableRpcCodes.includes(chunk.error.code)) {\n //\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n //\n // non-retryable error, cancel the subscription\n throw error;\n }\n case 'connecting': {\n const lastState = connectionState.get();\n\n const error = chunk.event && TRPCClientError.from(chunk.event);\n if (!error && lastState.state === 'connecting') {\n break;\n }\n\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n case 'timeout': {\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: new TRPCClientError(\n `Timeout of ${chunk.ms}ms reached while waiting for a response`,\n ),\n });\n }\n }\n }\n observer.next({\n result: {\n type: 'stopped',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n observer.complete();\n }).catch((error) => {\n observer.error(TRPCClientError.from(error));\n });\n\n return () => {\n observer.complete();\n ac.abort();\n connectionSub.unsubscribe();\n };\n });\n };\n };\n}\n\n/**\n * @deprecated Use {@link httpSubscriptionLink} instead.\n */\nexport const unstable_httpSubscriptionLink = httpSubscriptionLink;\n","/* istanbul ignore file -- @preserve */\n// We're not actually exporting this link\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport { observable } from '@trpc/server/observable';\nimport type { InferrableClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport type { TRPCClientError } from '../TRPCClientError';\nimport type { AugmentedOperationContext, Operation, TRPCLink } from './types';\n\ninterface RetryLinkOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The retry function\n */\n retry: (opts: RetryFnOptions<TInferrable>) => boolean;\n /**\n * The delay between retries in ms (defaults to 0)\n */\n retryDelayMs?: (attempt: number) => number;\n}\n\ninterface RetryFnOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The operation that failed\n */\n op: Operation;\n /**\n * The error that occurred\n */\n error: TRPCClientError<TInferrable>;\n /**\n * The number of attempts that have been made (including the first call)\n */\n attempts: number;\n}\n\n/**\n * Retries failed operations. Subscriptions resume from the last tracked event\n * id.\n *\n * @see https://trpc.io/docs/client/links/retryLink\n */\nexport function retryLink<TInferrable extends InferrableClientTypes>(\n opts: RetryLinkOptions<TInferrable>,\n): TRPCLink<\n TInferrable,\n // its callbacks may read the fields added to `OperationContext`\n { context: AugmentedOperationContext }\n> {\n // initialized config\n return () => {\n // initialized in app\n return (callOpts) => {\n // initialized for request\n return observable((observer) => {\n let next$: Unsubscribable;\n let currentAttempt = 0;\n let disposed = false;\n let callNextTimeout: ReturnType<typeof setTimeout> | undefined =\n undefined;\n\n let lastEventId: string | undefined = undefined;\n\n attempt(1);\n\n function opWithLastEventId() {\n const op = callOpts.op;\n if (!lastEventId) {\n return op;\n }\n\n return {\n ...op,\n input: inputWithTrackedEventId(op.input, lastEventId),\n };\n }\n\n function attempt(attempts: number) {\n if (disposed) {\n return;\n }\n currentAttempt = attempts;\n const op = opWithLastEventId();\n\n const subscription = callOpts.next(op).subscribe({\n error(error) {\n const shouldRetry = opts.retry({\n op,\n attempts,\n error,\n });\n if (disposed) {\n return;\n }\n if (!shouldRetry) {\n observer.error(error);\n return;\n }\n const delayMs = opts.retryDelayMs?.(attempts) ?? 0;\n if (disposed) {\n return;\n }\n\n if (delayMs <= 0) {\n attempt(attempts + 1);\n return;\n }\n callNextTimeout = setTimeout(\n () => attempt(attempts + 1),\n delayMs,\n );\n },\n next(envelope) {\n //\n if (\n (!envelope.result.type || envelope.result.type === 'data') &&\n envelope.result.id\n ) {\n //\n lastEventId = envelope.result.id;\n }\n\n observer.next(envelope);\n },\n complete() {\n observer.complete();\n },\n });\n\n // A synchronous error may have already subscribed the next attempt.\n if (disposed) {\n subscription.unsubscribe();\n } else if (currentAttempt === attempts) {\n next$ = subscription;\n }\n }\n return () => {\n disposed = true;\n next$.unsubscribe();\n clearTimeout(callNextTimeout);\n };\n });\n };\n };\n}\n","import {\n getTRPCErrorFromUnknown,\n getTRPCErrorShape,\n isTrackedEnvelope,\n} from '@trpc/server';\nimport {\n behaviorSubject,\n isObservable,\n observable,\n observableToAsyncIterable,\n} from '@trpc/server/observable';\nimport { TRPC_ERROR_CODES_BY_KEY, type TRPCResult } from '@trpc/server/rpc';\nimport {\n callProcedure,\n isAbortError,\n isAsyncIterable,\n iteratorResource,\n makeResource,\n retryableRpcCodes,\n run,\n type AnyRouter,\n type ErrorHandlerOptions,\n type inferClientTypes,\n type inferRouterContext,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport {\n abortSignalToPromise,\n raceAbortSignals,\n throwIfAborted,\n} from '../internals/signals';\nimport { getTransformer } from '../internals/transformer';\nimport type { TransformerOptions } from '../internals/transformer';\nimport { isTRPCClientError, TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from './internals/subscriptions';\nimport type { TRPCLink } from './types';\n\n/**\n * Passed to {@link LocalLinkOptions.createContext}.\n */\nexport type LocalLinkCreateContextOptions = {\n /**\n * What tRPC knows about the call, like the `info` that adapters pass to\n * their `createContext`.\n */\n info: {\n /**\n * Aborts when the call is cancelled or unsubscribed. Pass it on to work\n * that creating the context starts, such as `fetch()` calls.\n */\n signal: AbortSignal;\n };\n};\n\n/**\n * Options for {@link localLink}.\n *\n * @see https://trpc.io/docs/client/links/localLink#options\n */\nexport type LocalLinkOptions<TRouter extends AnyRouter> = {\n /**\n * The router to call.\n * @see https://trpc.io/docs/client/links/localLink#router\n */\n router: TRouter;\n /**\n * Creates the context for each call. `info.signal` aborts when the call\n * is cancelled.\n * @see https://trpc.io/docs/client/links/localLink#createcontext\n */\n createContext: (\n opts: LocalLinkCreateContextOptions,\n ) => Promise<inferRouterContext<TRouter>>;\n /**\n * Called when a procedure throws.\n * @see https://trpc.io/docs/client/links/localLink#onerror\n */\n onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\n/**\n * A terminating link that calls procedures on a router in the same process,\n * without HTTP.\n *\n * @see https://trpc.io/docs/client/links/localLink\n */\nexport function localLink<TRouter extends AnyRouter>(\n opts: LocalLinkOptions<TRouter>,\n): TRPCLink<TRouter, { context: {} }> {\n const transformer = getTransformer(opts.transformer);\n\n const transformChunk = (chunk: unknown) => {\n if (opts.transformer) {\n // assume transformer will do the right thing\n return chunk;\n }\n // Special case for undefined, because `JSON.stringify(undefined)` throws\n if (chunk === undefined) {\n return chunk;\n }\n const serialized = JSON.stringify(transformer.input.serialize(chunk));\n const deserialized = JSON.parse(transformer.output.deserialize(serialized));\n return deserialized;\n };\n\n return () =>\n ({ op }) =>\n observable((observer) => {\n let ctx: inferRouterContext<TRouter> | undefined = undefined;\n const ac = new AbortController();\n\n const signal = raceAbortSignals(op.signal, ac.signal);\n const signalPromise = abortSignalToPromise(signal);\n\n signalPromise.catch(() => {\n // prevent unhandled rejection\n });\n\n let input = op.input;\n async function runProcedure(newInput: unknown): Promise<unknown> {\n input = newInput;\n\n // don't start work for a call that was cancelled before it ran\n throwIfAborted(signal);\n ctx = await opts.createContext({ info: { signal } });\n throwIfAborted(signal);\n\n return callProcedure({\n router: opts.router,\n path: op.path,\n getRawInput: async () => newInput,\n ctx,\n type: op.type,\n signal,\n batchIndex: 0,\n });\n }\n\n function onErrorCallback(cause: unknown) {\n if (isAbortError(cause)) {\n return;\n }\n opts.onError?.({\n error: getTRPCErrorFromUnknown(cause),\n type: op.type,\n path: op.path,\n input,\n ctx,\n });\n }\n\n function coerceToTRPCClientError(cause: unknown) {\n if (isTRPCClientError<TRouter>(cause)) {\n return cause;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n const shape = getTRPCErrorShape({\n config: opts.router._def._config,\n ctx,\n error,\n input,\n path: op.path,\n type: op.type,\n });\n return TRPCClientError.from(\n { error: transformChunk(shape) },\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n run(async () => {\n switch (op.type) {\n case 'query':\n case 'mutation': {\n const result = await Promise.race([\n runProcedure(op.input),\n signalPromise,\n ]);\n if (!isAsyncIterable(result)) {\n observer.next({\n result: { data: transformChunk(result) },\n });\n observer.complete();\n break;\n }\n\n observer.next({\n result: {\n data: (async function* () {\n await using iterator = iteratorResource(result);\n using _finally = makeResource({}, () => {\n observer.complete();\n });\n try {\n while (true) {\n const res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n if (res.done) {\n return transformChunk(res.value);\n }\n yield transformChunk(res.value);\n }\n } catch (cause) {\n onErrorCallback(cause);\n throw coerceToTRPCClientError(cause);\n }\n })(),\n },\n });\n break;\n }\n case 'subscription': {\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n let lastEventId: string | undefined = undefined;\n\n using _finally = makeResource({}, async () => {\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n connectionSub.unsubscribe();\n });\n\n // returning from here means the stream ended, so this completes\n // below - a throw is left to the `.catch()`, which needs the\n // observer to still be open by the time it runs\n await run(async () => {\n while (true) {\n const procedureResult = await runProcedure(\n inputWithTrackedEventId(op.input, lastEventId),\n );\n const result = isObservable(procedureResult)\n ? observableToAsyncIterable(procedureResult, signal)\n : procedureResult;\n if (!isAsyncIterable(result)) {\n throw new Error('Expected an async iterable');\n }\n await using iterator = iteratorResource(result);\n\n observer.next({\n result: {\n type: 'started',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n\n // Use a while loop to handle errors and reconnects\n while (true) {\n let res;\n try {\n res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n } catch (cause) {\n if (isAbortError(cause)) {\n return;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n if (\n !retryableRpcCodes.includes(\n TRPC_ERROR_CODES_BY_KEY[error.code],\n )\n ) {\n throw coerceToTRPCClientError(error);\n }\n\n onErrorCallback(error);\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: coerceToTRPCClientError(error),\n });\n\n break;\n }\n\n if (res.done) {\n return;\n }\n let chunk: TRPCResult<unknown>;\n if (isTrackedEnvelope(res.value)) {\n lastEventId = res.value[0];\n\n chunk = {\n id: res.value[0],\n data: {\n id: res.value[0],\n data: res.value[1],\n },\n };\n } else {\n chunk = {\n data: res.value,\n };\n }\n\n observer.next({\n result: {\n ...chunk,\n data: transformChunk(chunk.data),\n },\n });\n }\n }\n });\n\n observer.complete();\n break;\n }\n }\n }).catch((cause) => {\n onErrorCallback(cause);\n observer.error(coerceToTRPCClientError(cause));\n });\n\n return () => {\n ac.abort();\n };\n });\n}\n\n/**\n * @deprecated Use {@link localLink} instead.\n * @function\n */\nexport const unstable_localLink = localLink;\n\n/**\n * @deprecated Use {@link localLink} instead. This alias will be removed in a\n * future major release.\n */\nexport const experimental_localLink = localLink;\n","import type { TRPCClientError } from './TRPCClientError';\n\n/**\n * @internal\n */\nexport declare const errorShapeTag: unique symbol;\n\n/**\n * The promise a client's `.query()` or `.mutate()` returns, tagged with\n * the procedure's error shape for `safe()`.\n */\nexport type TRPCTaggedPromise<TData, TErrorShape> = Promise<TData> & {\n readonly [errorShapeTag]: TErrorShape;\n};\n\n/**\n * @internal\n */\nexport type inferSafeError<TErrorShape> = TRPCClientError<{\n errorShape: TErrorShape;\n transformer: boolean;\n}>;\n\n/**\n * What `safe()` resolves to: `[data, undefined]` or `[undefined, error]`.\n * @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n */\nexport type SafeResult<TData, TErrorShape> =\n | readonly [data: TData, error: undefined]\n | readonly [data: undefined, error: inferSafeError<TErrorShape>];\n\n/**\n * Awaits a client `.query()` or `.mutate()` call without throwing, and\n * returns a `[data, error]` pair typed with the procedure's error shape.\n *\n * @example\n * ```ts\n * const [post, error] = await safe(client.post.byId.query({ id }));\n * if (error) {\n * console.error(error);\n * }\n *\n * const id = post.id;\n * ```\n * @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n */\nexport async function safe<TData, TErrorShape>(\n promise: TRPCTaggedPromise<TData, TErrorShape>,\n): Promise<SafeResult<TData, TErrorShape>> {\n try {\n return [await promise, undefined];\n } catch (cause) {\n return [undefined, cause as inferSafeError<TErrorShape>];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsFA,MAAM,eAA8B;CAClC;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAoBA,IAAa,oBAAb,MAA0E;CAKxE,YAAY,MAA4C;EAJvC,gBAAA,MAAA,SAAA,KAAA,CAAA;EACD,gBAAA,MAAA,WAAA,KAAA,CAAA;EACR,gBAAA,MAAA,aAAA,KAAA,CAAA;EAGN,KAAK,YAAY;EAEjB,KAAK,UAAU,CAAC;EAGhB,KAAK,QAAQ,KAAK,MAAM,KAAK,SAAS,KAAK,KAAK,OAAO,CAAC;CAC1D;CAEA,SAAsD,MAMnD;;EASD,OARe,YAAwC;GACrD,OAAO,KAAK;GACZ,IAAA,eAAA,eAAA,CAAA,GACK,IAAA,GAAA,CAAA,GAAA;IACH,UAAA,gBAAS,KAAK,aAAA,QAAA,kBAAA,KAAA,IAAA,gBAAW,CAAC;IAC1B,IAAI,EAAE,KAAK;GACb,CAAA;EACF,CACY,CAAC,CAAC,KAAK,MAAM,CAAC;CAC5B;CAEA,MAAc,iBAAsD,MAM/C;EACnB,IAAI;GACF,MAAM,OAAO,KAAK,SAA0B,IAAI;GAKhD,QADc,MADS,oBAA4B,IAAI,EAAA,CAChC,OAAe;EAExC,SAAS,KAAK;GACZ,MAAM,gBAAgB,KAAK,GAAY;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"index.mjs","names":[],"sources":["../src/internals/TRPCUntypedClient.ts","../src/createTRPCUntypedClient.ts","../src/createTRPCClient.ts","../src/routerType.ts","../src/links/httpBatchStreamLink.ts","../src/internals/inputWithTrackedEventId.ts","../src/links/httpSubscriptionLink.ts","../src/links/retryLink.ts","../src/links/localLink.ts","../src/safe.ts"],"sourcesContent":["import type {\n inferObservableValue,\n Unsubscribable,\n} from '@trpc/server/observable';\nimport {\n observable,\n observableToAsyncIterable,\n observableToPromise,\n share,\n} from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferAsyncIterableYield,\n InferrableClientTypes,\n Maybe,\n TypeError,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { createChain } from '../links/internals/createChain';\nimport type { TRPCConnectionState } from '../links/internals/subscriptions';\nimport type {\n OperationContext,\n OperationLink,\n TRPCClientRuntime,\n TRPCLink,\n} from '../links/types';\nimport { TRPCClientError } from '../TRPCClientError';\n\ntype TRPCType = 'mutation' | 'query' | 'subscription';\n/** The options of a call made with the untyped client. */\nexport interface TRPCRequestOptions {\n /**\n * Context for the links, such as a flag a `splitLink` reads.\n * @see https://trpc.io/docs/client/links#managing-context\n */\n context?: OperationContext;\n /**\n * Aborts the call. With `httpBatchLink`, the request is only aborted once\n * every call in its batch is, so an aborted call can still get a result.\n */\n signal?: AbortSignal;\n}\n\n/** The callbacks a subscription takes on the client. */\nexport interface TRPCSubscriptionObserver<TValue, TError> {\n /** Called when the link sends a `started` result. */\n onStarted: (opts: { context: OperationContext | undefined }) => void;\n /** Called with each event. */\n onData: (value: inferAsyncIterableYield<TValue>) => void;\n /** Called when the subscription ends with an error. */\n onError: (err: TError) => void;\n /**\n * Called when the link sends a `stopped` result. Not every link sends\n * one; `localLink` doesn't.\n */\n onStopped: () => void;\n /** Called when the subscription's observable completes, for any reason. */\n onComplete: () => void;\n /** Called when the connection connects, drops or reconnects. */\n onConnectionStateChange: (state: TRPCConnectionState<TError>) => void;\n}\n\ntype ObserverKey = keyof TRPCSubscriptionObserver<unknown, unknown>;\n\n/**\n * Subscription options without callbacks: `TOpts` must not have any of the\n * callback keys, not even set to `undefined`.\n * @internal\n */\nexport type TRPCSubscriptionWithoutCallbacks<TOpts> = TOpts & {\n // `keyof` a union only has its shared keys, so this one catches each member\n [TKey in ObserverKey]?: never;\n} & {\n [TKey in keyof TOpts & ObserverKey]: never;\n};\n\n/**\n * Subscription callbacks, at least one of which is defined.\n * @internal\n */\nexport type TRPCSubscriptionCallbacks<TValue, TError> = Partial<\n TRPCSubscriptionObserver<TValue, TError>\n> &\n {\n [TKey in ObserverKey]: Pick<TRPCSubscriptionObserver<TValue, TError>, TKey>;\n }[ObserverKey];\n\nconst observerKeys: ObserverKey[] = [\n 'onStarted',\n 'onData',\n 'onError',\n 'onStopped',\n 'onComplete',\n 'onConnectionStateChange',\n];\n\n/**\n * The options of `createTRPCClient`.\n * @internal\n */\nexport type CreateTRPCClientOptions<TRouter extends InferrableClientTypes> = {\n /**\n * The links each call goes through, in order. The last one must send\n * the call, such as `httpBatchLink`.\n * @see https://trpc.io/docs/client/links\n */\n links: TRPCLink<TRouter>[];\n transformer?: TypeError<'The transformer property has moved to httpLink/httpBatchLink/wsLink'>;\n};\n\n/**\n * A client that calls procedures by path string, without types.\n * `createTRPCClient` wraps one.\n */\nexport class TRPCUntypedClient<TInferrable extends InferrableClientTypes> {\n private readonly links: OperationLink<TInferrable>[];\n public readonly runtime: TRPCClientRuntime;\n private requestId: number;\n\n constructor(opts: CreateTRPCClientOptions<TInferrable>) {\n this.requestId = 0;\n\n this.runtime = {};\n\n // Initialize the links\n this.links = opts.links.map((link) => link(this.runtime));\n }\n\n private $request<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }) {\n const chain$ = createChain<AnyRouter, TInput, TOutput>({\n links: this.links as OperationLink<any, any, any>[],\n op: {\n ...opts,\n context: opts.context ?? {},\n id: ++this.requestId,\n },\n });\n return chain$.pipe(share());\n }\n\n private async requestAsPromise<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }): Promise<TOutput> {\n try {\n const req$ = this.$request<TInput, TOutput>(opts);\n type TValue = inferObservableValue<typeof req$>;\n\n const envelope = await observableToPromise<TValue>(req$);\n const data = (envelope.result as any).data;\n return data;\n } catch (err) {\n throw TRPCClientError.from(err as Error);\n }\n }\n /** Calls a query. */\n public query(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'query',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n /** Calls a mutation. */\n public mutation(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'mutation',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n /**\n * Starts a subscription. With callbacks, returns what stops it. Without,\n * returns an async iterator to read it with `for await`, which `signal`,\n * `break` or `return()` stops. It can be iterated once.\n * @see https://trpc.io/docs/client/vanilla/setup#5-use-subscriptions\n */\n public subscription(\n path: string,\n input: unknown,\n opts: TRPCSubscriptionCallbacks<unknown, TRPCClientError<AnyRouter>> &\n TRPCRequestOptions,\n ): Unsubscribable;\n public subscription<\n TOpts extends TRPCRequestOptions &\n Partial<TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>> =\n TRPCRequestOptions,\n >(\n path: string,\n input: unknown,\n opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,\n ): AsyncIterableIterator<unknown>;\n public subscription(\n path: string,\n input: unknown,\n opts: Partial<\n TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>\n > &\n TRPCRequestOptions = {},\n ): Unsubscribable | AsyncIterableIterator<unknown> {\n const hasCallbacks = observerKeys.some(\n (key) => typeof opts[key] === 'function',\n );\n const observable$ = this.$request({\n type: 'subscription',\n path,\n input,\n context: opts.context,\n signal: opts.signal,\n });\n if (!hasCallbacks) {\n const data$ = observable<unknown, TRPCClientError<AnyRouter>>(\n (observer) =>\n observable$.subscribe({\n next(envelope) {\n if (\n envelope.result.type === 'data' ||\n envelope.result.type === undefined\n ) {\n observer.next(envelope.result.data);\n }\n },\n error: (err) => observer.error(err),\n complete: () => observer.complete(),\n }),\n );\n const iterator = observableToAsyncIterable(\n data$,\n opts.signal ?? new AbortController().signal,\n );\n // a second loop over the same iterator would split the data with the\n // first, or end straight away once the first has left\n let iterated = false;\n iterator[Symbol.asyncIterator] = () => {\n if (iterated) {\n throw new Error(\n 'A subscription can only be iterated once. Call subscribe() again for another loop.',\n );\n }\n iterated = true;\n return iterator;\n };\n return iterator;\n }\n return observable$.subscribe({\n next(envelope) {\n switch (envelope.result.type) {\n case 'state': {\n opts.onConnectionStateChange?.(envelope.result);\n break;\n }\n case 'started': {\n opts.onStarted?.({\n context: envelope.context,\n });\n break;\n }\n case 'stopped': {\n opts.onStopped?.();\n break;\n }\n case 'data':\n case undefined: {\n opts.onData?.(envelope.result.data);\n break;\n }\n }\n },\n error(err) {\n opts.onError?.(err);\n },\n complete() {\n opts.onComplete?.();\n },\n });\n }\n}\n","import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n\n/**\n * Creates a client that calls procedures by path string, without types.\n * Meant for libraries built on tRPC; apps should use `createTRPCClient`.\n */\nexport function createTRPCUntypedClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return new TRPCUntypedClient(opts);\n}\n\nexport type {\n CreateTRPCClientOptions,\n TRPCRequestOptions,\n} from './internals/TRPCUntypedClient';\nexport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n","/* oxlint-disable typescript/no-non-null-assertion */\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport type {\n AnyProcedure,\n AnyRouter,\n inferAsyncIterableYield,\n inferClientTypes,\n inferProcedureErrorShape,\n inferProcedureInput,\n InferrableClientTypes,\n inferTransformedProcedureOutput,\n ProcedureType,\n RouterRecord,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n createFlatProxy,\n createRecursiveProxy,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './createTRPCUntypedClient';\nimport type {\n TRPCSubscriptionCallbacks,\n TRPCSubscriptionObserver,\n TRPCSubscriptionWithoutCallbacks,\n} from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\nimport type { TRPCProcedureOptions } from './internals/types';\nimport type { inferLinksContext, TRPCLink } from './links/types';\nimport type { RouterType } from './routerType';\nimport type { TRPCTaggedPromise } from './safe';\nimport type { TRPCClientError } from './TRPCClientError';\n\n/**\n * The type of a client for a router.\n * @deprecated Use {@link TRPCClient} instead. This will be removed in v12.\n * @public\n **/\nexport type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\n/**\n * The type of a client for a router.\n * @deprecated Use {@link TRPCClient} instead. This will be removed in v12.\n * @public\n **/\nexport type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\nconst untypedClientSymbol = Symbol.for('trpc_untypedClient');\n\n/**\n * A typed client for a router, as `createTRPCClient` returns it. Each\n * procedure has `.query()`, `.mutate()` or `.subscribe()`.\n *\n * `TContext` is the `context` calls take; `createTRPCClient({ router,\n * links })` infers it from the links.\n * @see https://trpc.io/docs/client/vanilla/infer-types\n * @public\n **/\nexport type TRPCClient<\n TRouter extends AnyRouter,\n TContext extends object = Record<string, unknown>,\n> = DecoratedProcedureRecord<\n {\n transformer: TRouter['_def']['_config']['$types']['transformer'];\n errorShape: TRouter['_def']['_config']['$types']['errorShape'];\n },\n TRouter['_def']['record'],\n TContext\n> & {\n [untypedClientSymbol]: TRPCUntypedClient<TRouter>;\n};\n\n/**\n * A procedure's types, as the client sees them.\n * @internal\n */\nexport type TRPCResolverDef = {\n input: any;\n output: any;\n transformer: boolean;\n errorShape: any;\n};\n\ntype coerceAsyncGeneratorToIterable<T> =\n T extends AsyncGenerator<infer $T, infer $Return, infer $Next>\n ? AsyncIterable<$T, $Return, $Next>\n : T;\n\n/**\n * The `.query()` or `.mutate()` of a procedure on the client.\n * @internal\n */\nexport type Resolver<\n TDef extends TRPCResolverDef,\n TContext extends object = Record<string, unknown>,\n> = (\n input: TDef['input'],\n opts?: TRPCProcedureOptions<TContext>,\n) => TRPCTaggedPromise<\n coerceAsyncGeneratorToIterable<TDef['output']>,\n TDef['errorShape']\n>;\n\n/**\n * The `.subscribe()` of a subscription procedure on the client.\n * @internal\n */\nexport type SubscriptionResolver<\n TDef extends TRPCResolverDef,\n TContext extends object = Record<string, unknown>,\n> = {\n (\n input: TDef['input'],\n opts: TRPCSubscriptionCallbacks<TDef['output'], TRPCClientError<TDef>> &\n TRPCProcedureOptions<TContext>,\n ): Unsubscribable;\n <\n TOpts extends TRPCProcedureOptions<TContext> &\n Partial<TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>> =\n TRPCProcedureOptions<TContext>,\n >(\n input: TDef['input'],\n opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,\n ): AsyncIterableIterator<inferAsyncIterableYield<TDef['output']>>;\n};\n\ntype DecorateProcedure<\n TType extends ProcedureType,\n TDef extends TRPCResolverDef,\n TContext extends object,\n> = TType extends 'query'\n ? { query: Resolver<TDef, TContext> }\n : TType extends 'mutation'\n ? { mutate: Resolver<TDef, TContext> }\n : TType extends 'subscription'\n ? { subscribe: SubscriptionResolver<TDef, TContext> }\n : never;\n\n/**\n * @internal\n */\ntype DecoratedProcedureRecord<\n TRoot extends InferrableClientTypes,\n TRecord extends RouterRecord,\n TContext extends object,\n> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<\n $Value['_def']['type'],\n {\n input: inferProcedureInput<$Value>;\n output: inferTransformedProcedureOutput<\n inferClientTypes<TRoot>,\n $Value\n >;\n errorShape: inferProcedureErrorShape<TRoot, $Value>;\n transformer: inferClientTypes<TRoot>['transformer'];\n },\n TContext\n >\n : $Value extends RouterRecord\n ? DecoratedProcedureRecord<TRoot, $Value, TContext>\n : never\n : never;\n};\n\nconst clientCallTypeMap: Record<\n keyof DecorateProcedure<any, any, any>,\n ProcedureType\n> = {\n query: 'query',\n mutate: 'mutation',\n subscribe: 'subscription',\n};\n\n/**\n * The procedure type of a client method: `query`, `mutate` or `subscribe`.\n * @internal\n */\nexport const clientCallTypeToProcedureType = (\n clientCallType: string,\n): ProcedureType => {\n return clientCallTypeMap[clientCallType as keyof typeof clientCallTypeMap];\n};\n\n/**\n * Wraps an untyped client in the typed proxy `createTRPCClient` returns.\n * @internal\n */\nexport function createTRPCClientProxy<TRouter extends AnyRouter>(\n client: TRPCUntypedClient<TRouter>,\n): TRPCClient<TRouter> {\n const proxy = createRecursiveProxy<TRPCClient<TRouter>>(({ path, args }) => {\n const pathCopy = [...path];\n const procedureType = clientCallTypeToProcedureType(pathCopy.pop()!);\n\n const fullPath = pathCopy.join('.');\n\n return (client[procedureType] as any)(fullPath, ...(args as any));\n });\n return createFlatProxy<TRPCClient<TRouter>>((key) => {\n if (key === untypedClientSymbol) {\n return client;\n }\n return proxy[key];\n });\n}\n\n/**\n * The options of `createTRPCClient` with the router's type passed as\n * `router: routerType<AppRouter>()`.\n * @public\n */\nexport type CreateTRPCClientWithRouterOptions<\n TRouter extends AnyRouter,\n TLinks extends readonly TRPCLink<TRouter, any>[] = TRPCLink<TRouter>[],\n> = Omit<CreateTRPCClientOptions<TRouter>, 'links'> & {\n /**\n * The router's type, from `routerType<AppRouter>()`. It's a type only:\n * nothing about the router is sent or bundled.\n */\n router: RouterType<TRouter>;\n /**\n * The links each call goes through, in order. The last one must send\n * the call, such as `httpBatchLink`. What they declare types each call's\n * `context`, and which methods the client has. Pass them inline or\n * `as const`: in an array declared without it, TypeScript can merge the\n * links' types and drop what one declares.\n * @see https://trpc.io/docs/client/links\n */\n links: TLinks;\n};\n\n/**\n * Creates a typed client for a router. Pass the router's type with\n * `routerType`, and the links that send its calls. What the links declare\n * types each call's `context`.\n * @example\n * ```ts\n * const client = createTRPCClient({\n * router: routerType<AppRouter>(),\n * links: [retryLink({ retry: () => false }), httpBatchLink({ url })],\n * });\n * const post = await client.post.byId.query(\n * { id: '1' },\n * { context: { retry: (opts) => opts.attempts <= 3 } },\n * );\n * ```\n * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n */\nexport function createTRPCClient<\n TRouter extends AnyRouter,\n // with an explicit router type, the links aren't inferred\n const TLinks extends readonly TRPCLink<TRouter, any>[] = TRPCLink<TRouter>[],\n>(\n opts: CreateTRPCClientWithRouterOptions<TRouter, TLinks>,\n): TRPCClient<TRouter, inferLinksContext<TLinks>>;\n/**\n * Creates a typed client for a router. Pass the router's type, and the\n * links that send its calls.\n * @example\n * ```ts\n * const client = createTRPCClient<AppRouter>({\n * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n * });\n * const post = await client.post.byId.query({ id: '1' });\n * ```\n * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n */\n// Kept last: `ReturnType<typeof createTRPCClient>` reads the last overload.\nexport function createTRPCClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCClient<TRouter>;\nexport function createTRPCClient<TRouter extends AnyRouter>(\n opts: Omit<CreateTRPCClientOptions<TRouter>, 'links'> & {\n links: readonly TRPCLink<TRouter, any>[];\n },\n): TRPCClient<TRouter> {\n // `router` is a type only, so the untyped client ignores it\n const client = new TRPCUntypedClient<TRouter>({\n links: [...opts.links],\n });\n const proxy = createTRPCClientProxy<TRouter>(client);\n return proxy;\n}\n\n/**\n * The untyped client behind a typed client, which calls procedures by\n * path string.\n * @internal\n */\nexport function getUntypedClient<TRouter extends AnyRouter>(\n client: TRPCClient<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return client[untypedClientSymbol];\n}\n","import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\n\ndeclare const routerTypeBrand: unique symbol;\n\n/**\n * A value that carries a router's type and nothing else. Made by\n * {@link routerType}.\n * @public\n */\nexport interface RouterType<TRouter extends AnyRouter> {\n readonly [routerTypeBrand]: TRouter;\n}\n\n/**\n * Passes a router's type to `createTRPCClient({ router })` as a normal\n * option, instead of a type argument. Nothing about the router exists at\n * runtime, so it's safe to import the router's type only.\n *\n * @example\n * ```ts\n * const client = createTRPCClient({\n * router: routerType<AppRouter>(),\n * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n * });\n * ```\n * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n * @public\n */\nexport function routerType<TRouter extends AnyRouter>(): RouterType<TRouter> {\n return {} as RouterType<TRouter>;\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResponse } from '@trpc/server/rpc';\nimport type { AnyClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { jsonlStreamConsumer } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport {\n allAbortSignals,\n raceAbortSignals,\n raceAbortSignalsWithCleanup,\n} from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n fetchHTTPResponse,\n getBody,\n getUrl,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { AugmentedOperationContext, Operation, TRPCLink } from './types';\n\n/**\n * Options for {@link httpBatchStreamLink}. Takes the same options as\n * `httpBatchLink`, plus `streamHeader`.\n *\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink#options\n */\nexport type HTTPBatchStreamLinkOptions<TRoot extends AnyClientTypes> =\n HTTPBatchLinkOptions<TRoot> & {\n /**\n * Which header to use to signal the server that the client wants a streaming response.\n * - `'trpc-accept'` (default): sends `trpc-accept: application/jsonl` header\n * - `'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.\n * @default 'trpc-accept'\n */\n streamHeader?: 'trpc-accept' | 'accept';\n };\n\ntype BatchStreamOperation = Operation & {\n releaseSignal: () => void;\n /** Aborts the op's signal once its response has nothing left to stream */\n settle: () => void;\n};\n\n/**\n * A terminating link that batches calls like `httpBatchLink`, but streams each\n * response back as soon as it is ready.\n *\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink\n */\nexport function httpBatchStreamLink<TRouter extends AnyRouter>(\n opts: HTTPBatchStreamLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<\n TRouter,\n // its callbacks may read the fields added to `OperationContext`\n { context: AugmentedOperationContext }\n> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<BatchStreamOperation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const batchSignals = allAbortSignals(\n ...batchOps.map((op) => op.signal),\n );\n const abortController = new AbortController();\n abortController.signal.addEventListener(\n 'abort',\n () => {\n for (const op of batchOps) {\n op.releaseSignal();\n }\n },\n { once: true },\n );\n\n const responsePromise = fetchHTTPResponse({\n ...resolvedOpts,\n signal: raceAbortSignals(batchSignals, abortController.signal),\n type,\n contentTypeHeader: 'application/json',\n trpcAcceptHeader: 'application/jsonl',\n trpcAcceptHeaderKey: opts.streamHeader ?? 'trpc-accept',\n getUrl,\n getBody,\n inputs,\n path,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<BatchStreamOperation>,\n });\n }\n return opts.headers;\n },\n });\n\n const res = await responsePromise;\n\n if (!res.ok) {\n // Server returned a non-2xx response (e.g. batching disabled).\n // The body is plain JSON, not JSONL, so parse it directly and\n // propagate the same error to every operation in the batch.\n const json = (await res.json()) as TRPCResponse;\n if ('error' in json) {\n json.error = resolvedOpts.transformer.output.deserialize(\n json.error,\n );\n }\n\n return batchOps.map((): Promise<HTTPResult> =>\n Promise.resolve({\n json,\n meta: {\n response: res,\n },\n }),\n );\n }\n\n const [head] = await jsonlStreamConsumer<\n Record<string, Promise<any>>\n >({\n // oxlint-disable-next-line typescript/no-non-null-assertion\n from: res.body!,\n deserialize: (data) =>\n resolvedOpts.transformer.output.deserialize(data),\n onError: () => abortController.abort(),\n // An op with nothing left to stream must not hold the batch open.\n onSettled: (settled) => batchOps[Number(settled.key)]?.settle(),\n formatError(opts) {\n const error = opts.error as TRPCErrorShape;\n return TRPCClientError.from({\n error,\n });\n },\n abortController,\n });\n const promises = Object.keys(batchOps).map(\n async (key): Promise<HTTPResult> => {\n let json: TRPCResponse = await Promise.resolve(head[key]);\n\n if ('result' in json) {\n /**\n * Not very pretty, but we need to unwrap nested data as promises\n * Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n */\n const result = await Promise.resolve(json.result);\n json = {\n result: {\n data: await Promise.resolve(result.data),\n },\n };\n }\n\n return {\n json,\n meta: {\n response: res,\n },\n };\n },\n );\n return promises;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const { signal, cleanup } = raceAbortSignalsWithCleanup(\n op.signal,\n ac.signal,\n );\n const promise = loader.load({\n ...op,\n signal,\n releaseSignal: cleanup,\n settle: () => ac.abort(),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n if ('error' in res.json) {\n // A failed op has nothing left to stream, so it must not hold the batch open.\n ac.abort();\n observer.error(\n TRPCClientError.from(res.json, {\n meta: res.meta,\n }),\n );\n return;\n } else if ('result' in res.json) {\n observer.next({\n context: res.meta,\n result: res.json.result,\n });\n observer.complete();\n return;\n }\n\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n ac.abort();\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n\n/**\n * @deprecated Use {@link httpBatchStreamLink} instead.\n */\nexport const unstable_httpBatchStreamLink = httpBatchStreamLink;\n","import { isPlainObject } from '@trpc/server/unstable-core-do-not-import';\n\nexport function inputWithTrackedEventId(\n input: unknown,\n lastEventId: string | undefined,\n) {\n if (!lastEventId) {\n return input;\n }\n // Spreading an array, a `Date` or a class instance would corrupt it, so only\n // a plain object can carry the id.\n if (input != null && !isPlainObject(input)) {\n return input;\n }\n return {\n ...(input ?? {}),\n lastEventId,\n };\n}\n","import { behaviorSubject, observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResult } from '@trpc/server/rpc';\nimport type {\n AnyClientTypes,\n EventSourceLike,\n inferClientTypes,\n InferrableClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n resolvePathSeparator,\n retryableRpcCodes,\n run,\n sseStreamConsumer,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport { raceAbortSignals } from '../internals/signals';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from '../unstable-internals';\nimport { getTransformer, type TransformerOptions } from '../unstable-internals';\nimport { getUrl, type HTTPLinkBaseOptions } from './internals/httpUtils';\nimport {\n resultOf,\n type UrlOptionsWithConnectionParams,\n} from './internals/urlWithConnectionParams';\nimport type { AugmentedOperationContext, Operation, TRPCLink } from './types';\n\nasync function urlWithConnectionParams(\n opts: UrlOptionsWithConnectionParams,\n): Promise<string> {\n let url = await resultOf(opts.url);\n if (opts.connectionParams) {\n const params = await resultOf(opts.connectionParams);\n\n const prefix = url.includes('?') ? '&' : '?';\n url +=\n prefix + 'connectionParams=' + encodeURIComponent(JSON.stringify(params));\n }\n\n return url;\n}\n\n/**\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink#httpsubscriptionlink-options\n */\ntype HTTPSubscriptionLinkOptions<\n TRoot extends AnyClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource,\n> = {\n /**\n * The `EventSource` class to use, for runtimes that don't have one.\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink#custom-headers-through-ponyfill\n */\n EventSource?: TEventSource;\n /**\n * Options passed to the `EventSource`, or a function that returns them for\n * each subscription.\n */\n eventSourceOptions?:\n | EventSourceLike.InitDictOf<TEventSource>\n | ((opts: {\n op: Operation;\n }) =>\n | EventSourceLike.InitDictOf<TEventSource>\n | Promise<EventSourceLike.InitDictOf<TEventSource>>);\n} & Pick<HTTPLinkBaseOptions<TRoot>, 'pathSeparator'> &\n TransformerOptions<TRoot> &\n UrlOptionsWithConnectionParams;\n\n/**\n * A terminating link that runs subscriptions over Server-Sent Events.\n *\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink\n */\nexport function httpSubscriptionLink<\n TInferrable extends InferrableClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor,\n>(\n opts: HTTPSubscriptionLinkOptions<\n inferClientTypes<TInferrable>,\n TEventSource\n >,\n): TRPCLink<\n TInferrable,\n // its callbacks may read the fields added to `OperationContext`\n { context: AugmentedOperationContext }\n> {\n const transformer = getTransformer(opts.transformer);\n const pathSeparator = resolvePathSeparator(opts.pathSeparator);\n\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n const { type, path, input } = op;\n\n /* istanbul ignore if -- @preserve */\n if (type !== 'subscription') {\n throw new Error('httpSubscriptionLink only supports subscriptions');\n }\n\n let lastEventId: string | undefined = undefined;\n const ac = new AbortController();\n const signal = raceAbortSignals(op.signal, ac.signal);\n const eventSourceStream = sseStreamConsumer<{\n EventSource: TEventSource;\n data: Partial<{\n id?: string;\n data: unknown;\n }>;\n error: TRPCErrorShape;\n }>({\n url: async () =>\n getUrl({\n transformer,\n url: await urlWithConnectionParams(opts),\n input: inputWithTrackedEventId(input, lastEventId),\n path,\n pathSeparator,\n type,\n signal: null,\n }),\n init: () => resultOf(opts.eventSourceOptions, { op }),\n signal,\n deserialize: (data) => transformer.output.deserialize(data),\n EventSource: opts.EventSource ?? (globalThis.EventSource as never),\n });\n\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n run(async () => {\n for await (const chunk of eventSourceStream) {\n switch (chunk.type) {\n case 'ping':\n // do nothing\n break;\n case 'data':\n const chunkData = chunk.data;\n\n let result: TRPCResult<unknown>;\n if (chunkData.id) {\n // if the `tracked()`-helper is used, we always have an `id` field\n lastEventId = chunkData.id;\n result = {\n id: chunkData.id,\n data: chunkData,\n };\n } else {\n result = {\n data: chunkData.data,\n };\n }\n\n observer.next({\n result,\n context: {\n eventSource: chunk.eventSource,\n },\n });\n break;\n case 'connected': {\n observer.next({\n result: {\n type: 'started',\n },\n context: {\n eventSource: chunk.eventSource,\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n break;\n }\n case 'serialized-error': {\n const error = TRPCClientError.from({ error: chunk.error });\n\n if (retryableRpcCodes.includes(chunk.error.code)) {\n //\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n //\n // non-retryable error, cancel the subscription\n throw error;\n }\n case 'connecting': {\n const lastState = connectionState.get();\n\n const error = chunk.event && TRPCClientError.from(chunk.event);\n if (!error && lastState.state === 'connecting') {\n break;\n }\n\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n case 'timeout': {\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: new TRPCClientError(\n `Timeout of ${chunk.ms}ms reached while waiting for a response`,\n ),\n });\n }\n }\n }\n observer.next({\n result: {\n type: 'stopped',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n observer.complete();\n }).catch((error) => {\n observer.error(TRPCClientError.from(error));\n });\n\n return () => {\n observer.complete();\n ac.abort();\n connectionSub.unsubscribe();\n };\n });\n };\n };\n}\n\n/**\n * @deprecated Use {@link httpSubscriptionLink} instead.\n */\nexport const unstable_httpSubscriptionLink = httpSubscriptionLink;\n","/* istanbul ignore file -- @preserve */\n// We're not actually exporting this link\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport { observable } from '@trpc/server/observable';\nimport type { InferrableClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport type { TRPCClientError } from '../TRPCClientError';\nimport type { AugmentedOperationContext, Operation, TRPCLink } from './types';\n\ntype RetryFn<TInferrable extends InferrableClientTypes> = (\n opts: RetryFnOptions<TInferrable>,\n) => boolean;\n\n/**\n * The `context` calls can pass through `retryLink`: the fields added to\n * `OperationContext` (`TAugmented`), which its callbacks may read, and\n * `retry`.\n * @public\n */\nexport type RetryLinkContext<\n TInferrable extends InferrableClientTypes,\n TAugmented extends object = AugmentedOperationContext,\n> = Omit<TAugmented, 'retry'> & {\n /**\n * Decides whether to retry this call, in place of the link's `retry`.\n * Anything else, such as a flag added to `OperationContext` that the\n * link's `retry` reads, is left to the link.\n * @example client.post.byId.query(input, { context: { retry: (opts) => opts.attempts <= 3 } })\n */\n retry?:\n | RetryFn<TInferrable>\n | ('retry' extends keyof TAugmented ? TAugmented['retry'] : never);\n};\n\ninterface RetryLinkOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The retry function. A call's `context.retry` replaces it for that call.\n */\n retry: RetryFn<TInferrable>;\n /**\n * The delay between retries in ms (defaults to 0)\n */\n retryDelayMs?: (attempt: number) => number;\n}\n\n/**\n * What a `retry` function is given.\n * @public\n */\nexport interface RetryFnOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The operation that failed\n */\n op: Operation;\n /**\n * The error that occurred\n */\n error: TRPCClientError<TInferrable>;\n /**\n * The number of attempts that have been made (including the first call)\n */\n attempts: number;\n}\n\n/**\n * Retries failed operations. Subscriptions resume from the last tracked event\n * id. A call can pass its own `retry` in `context`.\n *\n * @see https://trpc.io/docs/client/links/retryLink\n */\nexport function retryLink<TInferrable extends InferrableClientTypes>(\n opts: RetryLinkOptions<TInferrable>,\n): TRPCLink<TInferrable, { context: RetryLinkContext<TInferrable> }> {\n // initialized config\n return () => {\n // initialized in app\n return (callOpts) => {\n // initialized for request\n return observable((observer) => {\n let next$: Unsubscribable;\n let currentAttempt = 0;\n let disposed = false;\n let callNextTimeout: ReturnType<typeof setTimeout> | undefined =\n undefined;\n\n let lastEventId: string | undefined = undefined;\n\n attempt(1);\n\n function opWithLastEventId() {\n const op = callOpts.op;\n if (!lastEventId) {\n return op;\n }\n\n return {\n ...op,\n input: inputWithTrackedEventId(op.input, lastEventId),\n };\n }\n\n function attempt(attempts: number) {\n if (disposed) {\n return;\n }\n currentAttempt = attempts;\n const op = opWithLastEventId();\n\n const subscription = callOpts.next(op).subscribe({\n error(error) {\n const callRetry = op.context['retry'];\n // a `retry` that isn't a function is a flag for the link's own `retry`\n const retry =\n typeof callRetry === 'function'\n ? (callRetry as RetryFn<TInferrable>)\n : opts.retry;\n const shouldRetry = retry({\n op,\n attempts,\n error,\n });\n if (disposed) {\n return;\n }\n if (!shouldRetry) {\n observer.error(error);\n return;\n }\n const delayMs = opts.retryDelayMs?.(attempts) ?? 0;\n if (disposed) {\n return;\n }\n\n if (delayMs <= 0) {\n attempt(attempts + 1);\n return;\n }\n callNextTimeout = setTimeout(\n () => attempt(attempts + 1),\n delayMs,\n );\n },\n next(envelope) {\n //\n if (\n (!envelope.result.type || envelope.result.type === 'data') &&\n envelope.result.id\n ) {\n //\n lastEventId = envelope.result.id;\n }\n\n observer.next(envelope);\n },\n complete() {\n observer.complete();\n },\n });\n\n // A synchronous error may have already subscribed the next attempt.\n if (disposed) {\n subscription.unsubscribe();\n } else if (currentAttempt === attempts) {\n next$ = subscription;\n }\n }\n return () => {\n disposed = true;\n next$.unsubscribe();\n clearTimeout(callNextTimeout);\n };\n });\n };\n };\n}\n","import {\n getTRPCErrorFromUnknown,\n getTRPCErrorShape,\n isTrackedEnvelope,\n} from '@trpc/server';\nimport {\n behaviorSubject,\n isObservable,\n observable,\n observableToAsyncIterable,\n} from '@trpc/server/observable';\nimport { TRPC_ERROR_CODES_BY_KEY, type TRPCResult } from '@trpc/server/rpc';\nimport {\n callProcedure,\n isAbortError,\n isAsyncIterable,\n iteratorResource,\n makeResource,\n retryableRpcCodes,\n run,\n type AnyRouter,\n type ErrorHandlerOptions,\n type inferClientTypes,\n type inferRouterContext,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport {\n abortSignalToPromise,\n raceAbortSignals,\n throwIfAborted,\n} from '../internals/signals';\nimport { getTransformer } from '../internals/transformer';\nimport type { TransformerOptions } from '../internals/transformer';\nimport { isTRPCClientError, TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from './internals/subscriptions';\nimport type { TRPCLink } from './types';\n\n/**\n * Passed to {@link LocalLinkOptions.createContext}.\n */\nexport type LocalLinkCreateContextOptions = {\n /**\n * What tRPC knows about the call, like the `info` that adapters pass to\n * their `createContext`.\n */\n info: {\n /**\n * Aborts when the call is cancelled or unsubscribed. Pass it on to work\n * that creating the context starts, such as `fetch()` calls.\n */\n signal: AbortSignal;\n };\n};\n\n/**\n * Options for {@link localLink}.\n *\n * @see https://trpc.io/docs/client/links/localLink#options\n */\nexport type LocalLinkOptions<TRouter extends AnyRouter> = {\n /**\n * The router to call.\n * @see https://trpc.io/docs/client/links/localLink#router\n */\n router: TRouter;\n /**\n * Creates the context for each call. `info.signal` aborts when the call\n * is cancelled.\n * @see https://trpc.io/docs/client/links/localLink#createcontext\n */\n createContext: (\n opts: LocalLinkCreateContextOptions,\n ) => Promise<inferRouterContext<TRouter>>;\n /**\n * Called when a procedure throws.\n * @see https://trpc.io/docs/client/links/localLink#onerror\n */\n onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\n/**\n * A terminating link that calls procedures on a router in the same process,\n * without HTTP.\n *\n * @see https://trpc.io/docs/client/links/localLink\n */\nexport function localLink<TRouter extends AnyRouter>(\n opts: LocalLinkOptions<TRouter>,\n): TRPCLink<TRouter, { context: {} }> {\n const transformer = getTransformer(opts.transformer);\n\n const transformChunk = (chunk: unknown) => {\n if (opts.transformer) {\n // assume transformer will do the right thing\n return chunk;\n }\n // Special case for undefined, because `JSON.stringify(undefined)` throws\n if (chunk === undefined) {\n return chunk;\n }\n const serialized = JSON.stringify(transformer.input.serialize(chunk));\n const deserialized = JSON.parse(transformer.output.deserialize(serialized));\n return deserialized;\n };\n\n return () =>\n ({ op }) =>\n observable((observer) => {\n let ctx: inferRouterContext<TRouter> | undefined = undefined;\n const ac = new AbortController();\n\n const signal = raceAbortSignals(op.signal, ac.signal);\n const signalPromise = abortSignalToPromise(signal);\n\n signalPromise.catch(() => {\n // prevent unhandled rejection\n });\n\n let input = op.input;\n async function runProcedure(newInput: unknown): Promise<unknown> {\n input = newInput;\n\n // don't start work for a call that was cancelled before it ran\n throwIfAborted(signal);\n ctx = await opts.createContext({ info: { signal } });\n throwIfAborted(signal);\n\n return callProcedure({\n router: opts.router,\n path: op.path,\n getRawInput: async () => newInput,\n ctx,\n type: op.type,\n signal,\n batchIndex: 0,\n });\n }\n\n function onErrorCallback(cause: unknown) {\n if (isAbortError(cause)) {\n return;\n }\n opts.onError?.({\n error: getTRPCErrorFromUnknown(cause),\n type: op.type,\n path: op.path,\n input,\n ctx,\n });\n }\n\n function coerceToTRPCClientError(cause: unknown) {\n if (isTRPCClientError<TRouter>(cause)) {\n return cause;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n const shape = getTRPCErrorShape({\n config: opts.router._def._config,\n ctx,\n error,\n input,\n path: op.path,\n type: op.type,\n });\n return TRPCClientError.from(\n { error: transformChunk(shape) },\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n run(async () => {\n switch (op.type) {\n case 'query':\n case 'mutation': {\n const result = await Promise.race([\n runProcedure(op.input),\n signalPromise,\n ]);\n if (!isAsyncIterable(result)) {\n observer.next({\n result: { data: transformChunk(result) },\n });\n observer.complete();\n break;\n }\n\n observer.next({\n result: {\n data: (async function* () {\n await using iterator = iteratorResource(result);\n using _finally = makeResource({}, () => {\n observer.complete();\n });\n try {\n while (true) {\n const res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n if (res.done) {\n return transformChunk(res.value);\n }\n yield transformChunk(res.value);\n }\n } catch (cause) {\n onErrorCallback(cause);\n throw coerceToTRPCClientError(cause);\n }\n })(),\n },\n });\n break;\n }\n case 'subscription': {\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n let lastEventId: string | undefined = undefined;\n\n using _finally = makeResource({}, async () => {\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n connectionSub.unsubscribe();\n });\n\n // returning from here means the stream ended, so this completes\n // below - a throw is left to the `.catch()`, which needs the\n // observer to still be open by the time it runs\n await run(async () => {\n while (true) {\n const procedureResult = await runProcedure(\n inputWithTrackedEventId(op.input, lastEventId),\n );\n const result = isObservable(procedureResult)\n ? observableToAsyncIterable(procedureResult, signal)\n : procedureResult;\n if (!isAsyncIterable(result)) {\n throw new Error('Expected an async iterable');\n }\n await using iterator = iteratorResource(result);\n\n observer.next({\n result: {\n type: 'started',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n\n // Use a while loop to handle errors and reconnects\n while (true) {\n let res;\n try {\n res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n } catch (cause) {\n if (isAbortError(cause)) {\n return;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n if (\n !retryableRpcCodes.includes(\n TRPC_ERROR_CODES_BY_KEY[error.code],\n )\n ) {\n throw coerceToTRPCClientError(error);\n }\n\n onErrorCallback(error);\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: coerceToTRPCClientError(error),\n });\n\n break;\n }\n\n if (res.done) {\n return;\n }\n let chunk: TRPCResult<unknown>;\n if (isTrackedEnvelope(res.value)) {\n lastEventId = res.value[0];\n\n chunk = {\n id: res.value[0],\n data: {\n id: res.value[0],\n data: res.value[1],\n },\n };\n } else {\n chunk = {\n data: res.value,\n };\n }\n\n observer.next({\n result: {\n ...chunk,\n data: transformChunk(chunk.data),\n },\n });\n }\n }\n });\n\n observer.complete();\n break;\n }\n }\n }).catch((cause) => {\n onErrorCallback(cause);\n observer.error(coerceToTRPCClientError(cause));\n });\n\n return () => {\n ac.abort();\n };\n });\n}\n\n/**\n * @deprecated Use {@link localLink} instead.\n * @function\n */\nexport const unstable_localLink = localLink;\n\n/**\n * @deprecated Use {@link localLink} instead. This alias will be removed in a\n * future major release.\n */\nexport const experimental_localLink = localLink;\n","import type { TRPCClientError } from './TRPCClientError';\n\n/**\n * @internal\n */\nexport declare const errorShapeTag: unique symbol;\n\n/**\n * The promise a client's `.query()` or `.mutate()` returns, tagged with\n * the procedure's error shape for `safe()`.\n */\nexport type TRPCTaggedPromise<TData, TErrorShape> = Promise<TData> & {\n readonly [errorShapeTag]: TErrorShape;\n};\n\n/**\n * @internal\n */\nexport type inferSafeError<TErrorShape> = TRPCClientError<{\n errorShape: TErrorShape;\n transformer: boolean;\n}>;\n\n/**\n * What `safe()` resolves to: `[data, undefined]` or `[undefined, error]`.\n * @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n */\nexport type SafeResult<TData, TErrorShape> =\n | readonly [data: TData, error: undefined]\n | readonly [data: undefined, error: inferSafeError<TErrorShape>];\n\n/**\n * Awaits a client `.query()` or `.mutate()` call without throwing, and\n * returns a `[data, error]` pair typed with the procedure's error shape.\n *\n * @example\n * ```ts\n * const [post, error] = await safe(client.post.byId.query({ id }));\n * if (error) {\n * console.error(error);\n * }\n *\n * const id = post.id;\n * ```\n * @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n */\nexport async function safe<TData, TErrorShape>(\n promise: TRPCTaggedPromise<TData, TErrorShape>,\n): Promise<SafeResult<TData, TErrorShape>> {\n try {\n return [await promise, undefined];\n } catch (cause) {\n return [undefined, cause as inferSafeError<TErrorShape>];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsFA,MAAM,eAA8B;CAClC;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAoBA,IAAa,oBAAb,MAA0E;CAKxE,YAAY,MAA4C;EAJvC,gBAAA,MAAA,SAAA,KAAA,CAAA;EACD,gBAAA,MAAA,WAAA,KAAA,CAAA;EACR,gBAAA,MAAA,aAAA,KAAA,CAAA;EAGN,KAAK,YAAY;EAEjB,KAAK,UAAU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;QAGF,SAAS,KAAK,EACZ,QAAA,eAAA,eAAA,CAAA,GACK,KAAA,GAAA,CAAA,GAAA,EACH,MAAM,eAAe,MAAM,IAAI,EAAA,CACjC,EACF,CAAC;OACH;;;;;;KAEJ,CAAC;KAED,SAAS,SAAS;KAClB;;;;;;GAEJ;EACF,CAAC,CAAC,CAAC,OAAO,UAAU;GAClB,gBAAgB,KAAK;GACrB,SAAS,MAAM,wBAAwB,KAAK,CAAC;EAC/C,CAAC;EAED,aAAa;GACX,GAAG,MAAM;EACX;CACF,CAAC;AACP;;;;;AAMA,MAAa,qBAAqB;;;;;AAMlC,MAAa,yBAAyB;;;;;;;;;;;;;;;;;ACrTtC,eAAsB,KACpB,SACyC;CACzC,IAAI;EACF,OAAO,CAAC,MAAM,SAAS,KAAA,CAAS;CAClC,SAAS,OAAO;EACd,OAAO,CAAC,KAAA,GAAW,KAAoC;CACzD;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as httpBatchLink } from "../httpBatchLink-
|
|
1
|
+
import { t as httpBatchLink } from "../httpBatchLink-50xXDyIp.cjs";
|
|
2
2
|
export { httpBatchLink };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as httpBatchLink } from "../httpBatchLink-
|
|
1
|
+
import { t as httpBatchLink } from "../httpBatchLink-D4shlyQy.mjs";
|
|
2
2
|
export { httpBatchLink };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as HTTPLinkBaseOptions } from "../httpUtils-
|
|
2
|
-
import { a as Operation, n as HTTPHeaders, p as TRPCLink, t as AugmentedOperationContext } from "../types-
|
|
1
|
+
import { t as HTTPLinkBaseOptions } from "../httpUtils-dB1XeokQ.cjs";
|
|
2
|
+
import { a as Operation, n as HTTPHeaders, p as TRPCLink, t as AugmentedOperationContext } from "../types-CGS36fjk.cjs";
|
|
3
3
|
import { AnyClientTypes, AnyRouter } from "@trpc/server/unstable-core-do-not-import";
|
|
4
4
|
/**
|
|
5
5
|
* The options of `httpLink`.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as httpLink, t as HTTPLinkOptions } from "../httpLink-
|
|
1
|
+
import { n as httpLink, t as HTTPLinkOptions } from "../httpLink-Bb6hOyBN.mjs";
|
|
2
2
|
export { HTTPLinkOptions, httpLink };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as Operation, c as OperationResultEnvelope, p as TRPCLink, t as AugmentedOperationContext, y as TRPCClientError } from "../types-
|
|
1
|
+
import { a as Operation, c as OperationResultEnvelope, p as TRPCLink, t as AugmentedOperationContext, y as TRPCClientError } from "../types-CGS36fjk.cjs";
|
|
2
2
|
import { AnyRouter, InferrableClientTypes } from "@trpc/server/unstable-core-do-not-import";
|
|
3
3
|
type ConsoleEsque = {
|
|
4
4
|
log: (...args: any[]) => void;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as loggerLink, t as LoggerLinkOptions } from "../loggerLink-
|
|
1
|
+
import { n as loggerLink, t as LoggerLinkOptions } from "../loggerLink-y1x7WTWX.mjs";
|
|
2
2
|
export { LoggerLinkOptions, loggerLink };
|
package/dist/links/splitLink.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as Operation, h as inferLinksDeclaredContext, p as TRPCLink, t as AugmentedOperationContext } from "../types-
|
|
1
|
+
import { a as Operation, h as inferLinksDeclaredContext, o as OperationContext, p as TRPCLink, t as AugmentedOperationContext } from "../types-CGS36fjk.cjs";
|
|
2
2
|
import { AnyRouter } from "@trpc/server/unstable-core-do-not-import";
|
|
3
3
|
/**
|
|
4
4
|
* A `splitLink` branch: one link or a chain of them.
|
|
@@ -6,11 +6,11 @@ import { AnyRouter } from "@trpc/server/unstable-core-do-not-import";
|
|
|
6
6
|
*/
|
|
7
7
|
type SplitLinkBranch<TRouter extends AnyRouter> = TRPCLink<TRouter, any> | readonly TRPCLink<TRouter, any>[];
|
|
8
8
|
type asLinks<TBranch> = TBranch extends readonly unknown[] ? TBranch : [TBranch];
|
|
9
|
-
interface SplitLinkOptions<TRouter extends AnyRouter, TTrue extends SplitLinkBranch<TRouter>, TFalse extends SplitLinkBranch<TRouter
|
|
9
|
+
interface SplitLinkOptions<TRouter extends AnyRouter, TTrue extends SplitLinkBranch<TRouter>, TFalse extends SplitLinkBranch<TRouter>, TContext extends object> {
|
|
10
10
|
/**
|
|
11
11
|
* Picks the chain for an operation.
|
|
12
12
|
*/
|
|
13
|
-
condition: (op: Operation) => boolean;
|
|
13
|
+
condition: (op: Operation<unknown, TContext>) => boolean;
|
|
14
14
|
/**
|
|
15
15
|
* The link to execute next if the test function returns `true`.
|
|
16
16
|
*/
|
|
@@ -20,16 +20,37 @@ interface SplitLinkOptions<TRouter extends AnyRouter, TTrue extends SplitLinkBra
|
|
|
20
20
|
*/
|
|
21
21
|
false: TFalse;
|
|
22
22
|
}
|
|
23
|
+
type fitBranchContext<TContext, TTrue, TFalse> = inferLinksDeclaredContext<[...asLinks<TTrue>, ...asLinks<TFalse>]> extends (infer $Branches) ? { [TKey in keyof TContext & keyof $Branches]: $Branches[TKey]; } : never;
|
|
24
|
+
type SplitLink<TRouter extends AnyRouter, TTrue extends SplitLinkBranch<TRouter>, TFalse extends SplitLinkBranch<TRouter>, TContext extends object> = TRPCLink<TRouter, {
|
|
25
|
+
context: TContext & inferLinksDeclaredContext<[...asLinks<TTrue>, ...asLinks<TFalse>]>;
|
|
26
|
+
}>;
|
|
23
27
|
/**
|
|
24
28
|
* Sends each operation down one of two link chains, based on `condition`.
|
|
25
29
|
*
|
|
26
|
-
* Calls take the `context` both chains read. `
|
|
27
|
-
* fields
|
|
30
|
+
* Calls take the `context` both chains read. Give `context` defaults to
|
|
31
|
+
* declare the fields `condition` reads; without them, `condition` reads
|
|
32
|
+
* the fields added to `OperationContext`.
|
|
33
|
+
* @example
|
|
34
|
+
* splitLink({
|
|
35
|
+
* context: { skipBatch: false },
|
|
36
|
+
* condition: (op) => op.context.skipBatch,
|
|
37
|
+
* true: httpLink({ url }),
|
|
38
|
+
* false: httpBatchLink({ url }),
|
|
39
|
+
* })
|
|
28
40
|
*
|
|
29
41
|
* @see https://trpc.io/docs/client/links/splitLink
|
|
30
42
|
*/
|
|
31
|
-
export declare function splitLink<TRouter extends AnyRouter = AnyRouter, const TTrue extends SplitLinkBranch<TRouter> = SplitLinkBranch<TRouter>, const TFalse extends SplitLinkBranch<TRouter> = SplitLinkBranch<TRouter>>(opts: SplitLinkOptions<TRouter, TTrue, TFalse>
|
|
32
|
-
context
|
|
33
|
-
}>;
|
|
43
|
+
export declare function splitLink<TRouter extends AnyRouter = AnyRouter, const TTrue extends SplitLinkBranch<TRouter> = SplitLinkBranch<TRouter>, const TFalse extends SplitLinkBranch<TRouter> = SplitLinkBranch<TRouter>>(opts: SplitLinkOptions<TRouter, TTrue, TFalse, OperationContext> & {
|
|
44
|
+
context?: never;
|
|
45
|
+
}): SplitLink<TRouter, TTrue, TFalse, AugmentedOperationContext>;
|
|
46
|
+
export declare function splitLink<TRouter extends AnyRouter, const TTrue extends SplitLinkBranch<TRouter>, const TFalse extends SplitLinkBranch<TRouter>, TContext extends object>(opts: SplitLinkOptions<TRouter, TTrue, TFalse, TContext> & {
|
|
47
|
+
/**
|
|
48
|
+
* Values for the `context` fields `condition` reads, used when a call
|
|
49
|
+
* leaves one out. Their types are the fields calls can pass. A field a
|
|
50
|
+
* call passes replaces its default whole: nested objects aren't merged.
|
|
51
|
+
* A field the branches' links also read must fit their type.
|
|
52
|
+
*/
|
|
53
|
+
context: TContext & fitBranchContext<TContext, TTrue, TFalse>;
|
|
54
|
+
}): SplitLink<TRouter, TTrue, TFalse, TContext>;
|
|
34
55
|
export {};
|
|
35
56
|
//# sourceMappingURL=splitLink.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitLink.d.cts","names":[],"sources":["../../src/links/splitLink.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"splitLink.d.cts","names":[],"sources":["../../src/links/splitLink.ts"],"mappings":";;;;;;KAgCK,gBAAgB,gBAAgB,aACjC,SAAS,yBACA,SAAS;KAGjB,QAAQ,WAAW,qCACpB,WACC;UAEK,iBACR,gBAAgB,WAChB,cAAc,gBAAgB,UAC9B,eAAe,gBAAgB,UAC/B;;;;EAKA,YAAY,IAAI,mBAAmB;;;;EAInC,MAAM;;;;EAIN,OAAO;;KAKJ,iBAAiB,UAAU,OAAO,UACrC,8BACM,QAAQ,WAAW,QAAQ,yBACjB,gBACT,cAAc,iBAAiB,YAAY,UAAU;KAGzD,UACH,gBAAgB,WAChB,cAAc,gBAAgB,UAC9B,eAAe,gBAAgB,UAC/B,2BACE,SACF;EAEE,SAAS,WACP,8BAA8B,QAAQ,WAAW,QAAQ;;;;;;;;;;;;;;;;;;wBAoB/C,UACd,gBAAgB,YAAY,iBAEtB,cAAc,gBAAgB,WAAW,gBAAgB,gBACzD,eAAe,gBAAgB,WAAW,gBAAgB,UAEhE,MAAM,iBAAiB,SAAS,OAAO,QAAQ;EAC7C;IAGD,UAAU,SAAS,OAAO,QAAQ;wBACrB,UACd,gBAAgB,iBACV,cAAc,gBAAgB,gBAC9B,eAAe,gBAAgB,UACrC,yBAEA,MAAM,iBAAiB,SAAS,OAAO,QAAQ;;;;;;;EAO7C,SAAS,WAAW,iBAAiB,UAAU,OAAO;IAEvD,UAAU,SAAS,OAAO,QAAQ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as splitLink } from "../splitLink-
|
|
1
|
+
import { t as splitLink } from "../splitLink-BGLTgm1a.mjs";
|
|
2
2
|
export { splitLink };
|
package/dist/links/splitLink.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as splitLink } from "../splitLink-
|
|
1
|
+
export { t as splitLink } from "../splitLink-C8U8vvLl.mjs";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as WebSocketClientOptions, c as jsonEncoder, i as createWSClient, n as wsLink, r as TRPCWebSocketClient, s as Encoder, t as WebSocketLinkOptions } from "../../wsLink-
|
|
1
|
+
import { a as WebSocketClientOptions, c as jsonEncoder, i as createWSClient, n as wsLink, r as TRPCWebSocketClient, s as Encoder, t as WebSocketLinkOptions } from "../../wsLink-CJT5pqFt.cjs";
|
|
2
2
|
export { type Encoder, type TRPCWebSocketClient, type WebSocketClientOptions, WebSocketLinkOptions, createWSClient, jsonEncoder, wsLink };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as WebSocketClientOptions, c as jsonEncoder, i as createWSClient, n as wsLink, r as TRPCWebSocketClient, s as Encoder, t as WebSocketLinkOptions } from "../../wsLink-
|
|
1
|
+
import { a as WebSocketClientOptions, c as jsonEncoder, i as createWSClient, n as wsLink, r as TRPCWebSocketClient, s as Encoder, t as WebSocketLinkOptions } from "../../wsLink-CFh-pvQG.mjs";
|
|
2
2
|
export { type Encoder, type TRPCWebSocketClient, type WebSocketClientOptions, WebSocketLinkOptions, createWSClient, jsonEncoder, wsLink };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as Operation, c as OperationResultEnvelope, g as TRPCClientError, p as TRPCLink, t as AugmentedOperationContext } from "./types-
|
|
1
|
+
import { a as Operation, c as OperationResultEnvelope, g as TRPCClientError, p as TRPCLink, t as AugmentedOperationContext } from "./types-BZH1P86I.mjs";
|
|
2
2
|
import { AnyRouter, InferrableClientTypes } from "@trpc/server/unstable-core-do-not-import";
|
|
3
3
|
type ConsoleEsque = {
|
|
4
4
|
log: (...args: any[]) => void;
|
|
@@ -66,4 +66,4 @@ declare function loggerLink<TRouter extends AnyRouter = AnyRouter>(opts?: Logger
|
|
|
66
66
|
context: AugmentedOperationContext;
|
|
67
67
|
}>;
|
|
68
68
|
export { loggerLink as n, LoggerLinkOptions as t };
|
|
69
|
-
//# sourceMappingURL=loggerLink-
|
|
69
|
+
//# sourceMappingURL=loggerLink-y1x7WTWX.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loggerLink-
|
|
1
|
+
{"version":3,"file":"loggerLink-y1x7WTWX.d.mts","names":[],"sources":["../src/links/loggerLink.ts"],"mappings":";;KAoBK;EACH,SAAS;EACT,WAAW;;KAGR,gBAAgB,gBAAgB;EAE/B;EACA,QACI,iCAAiC,gBAAgB,YACjD,gBAAgB;KAErB;EACC;;KAED,UAAU,gBAAgB,cAC7B,MAAM,gBAAgB;KAGnB,oBAAoB,gBAAgB,aAAa;;;;EAM9C;EACA,QACI,iCAAiC,gBAAgB,YACjD,gBAAgB;EACpB;;;;;EAMA;;KAIH,aAAa,gBAAgB,cAChC,MAAM,oBAAoB;KAGvB;;;;;;UAOY,kBAAkB,gBAAgB;;;;;EAKjD,SAAS,aAAa;;;;;EAKtB,UAAU,UAAU;;;;EAIpB,UAAU;;;;;EAKV,YAAY;;;;EAKZ;;;;;;;;iBA4Ic,WAAW,gBAAgB,YAAY,WACrD,OAAM,kBAAkB,WACvB,SACD;EAEE,SAAS"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { a as Operation, h as inferLinksDeclaredContext, o as OperationContext, p as TRPCLink, t as AugmentedOperationContext } from "./types-BZH1P86I.mjs";
|
|
2
|
+
import { AnyRouter } from "@trpc/server/unstable-core-do-not-import";
|
|
3
|
+
/**
|
|
4
|
+
* A `splitLink` branch: one link or a chain of them.
|
|
5
|
+
* @internal
|
|
6
|
+
*/
|
|
7
|
+
type SplitLinkBranch<TRouter extends AnyRouter> = TRPCLink<TRouter, any> | readonly TRPCLink<TRouter, any>[];
|
|
8
|
+
type asLinks<TBranch> = TBranch extends readonly unknown[] ? TBranch : [TBranch];
|
|
9
|
+
interface SplitLinkOptions<TRouter extends AnyRouter, TTrue extends SplitLinkBranch<TRouter>, TFalse extends SplitLinkBranch<TRouter>, TContext extends object> {
|
|
10
|
+
/**
|
|
11
|
+
* Picks the chain for an operation.
|
|
12
|
+
*/
|
|
13
|
+
condition: (op: Operation<unknown, TContext>) => boolean;
|
|
14
|
+
/**
|
|
15
|
+
* The link to execute next if the test function returns `true`.
|
|
16
|
+
*/
|
|
17
|
+
true: TTrue;
|
|
18
|
+
/**
|
|
19
|
+
* The link to execute next if the test function returns `false`.
|
|
20
|
+
*/
|
|
21
|
+
false: TFalse;
|
|
22
|
+
}
|
|
23
|
+
type fitBranchContext<TContext, TTrue, TFalse> = inferLinksDeclaredContext<[...asLinks<TTrue>, ...asLinks<TFalse>]> extends (infer $Branches) ? { [TKey in keyof TContext & keyof $Branches]: $Branches[TKey]; } : never;
|
|
24
|
+
type SplitLink<TRouter extends AnyRouter, TTrue extends SplitLinkBranch<TRouter>, TFalse extends SplitLinkBranch<TRouter>, TContext extends object> = TRPCLink<TRouter, {
|
|
25
|
+
context: TContext & inferLinksDeclaredContext<[...asLinks<TTrue>, ...asLinks<TFalse>]>;
|
|
26
|
+
}>;
|
|
27
|
+
/**
|
|
28
|
+
* Sends each operation down one of two link chains, based on `condition`.
|
|
29
|
+
*
|
|
30
|
+
* Calls take the `context` both chains read. Give `context` defaults to
|
|
31
|
+
* declare the fields `condition` reads; without them, `condition` reads
|
|
32
|
+
* the fields added to `OperationContext`.
|
|
33
|
+
* @example
|
|
34
|
+
* splitLink({
|
|
35
|
+
* context: { skipBatch: false },
|
|
36
|
+
* condition: (op) => op.context.skipBatch,
|
|
37
|
+
* true: httpLink({ url }),
|
|
38
|
+
* false: httpBatchLink({ url }),
|
|
39
|
+
* })
|
|
40
|
+
*
|
|
41
|
+
* @see https://trpc.io/docs/client/links/splitLink
|
|
42
|
+
*/
|
|
43
|
+
declare function splitLink<TRouter extends AnyRouter = AnyRouter, const TTrue extends SplitLinkBranch<TRouter> = SplitLinkBranch<TRouter>, const TFalse extends SplitLinkBranch<TRouter> = SplitLinkBranch<TRouter>>(opts: SplitLinkOptions<TRouter, TTrue, TFalse, OperationContext> & {
|
|
44
|
+
context?: never;
|
|
45
|
+
}): SplitLink<TRouter, TTrue, TFalse, AugmentedOperationContext>;
|
|
46
|
+
declare function splitLink<TRouter extends AnyRouter, const TTrue extends SplitLinkBranch<TRouter>, const TFalse extends SplitLinkBranch<TRouter>, TContext extends object>(opts: SplitLinkOptions<TRouter, TTrue, TFalse, TContext> & {
|
|
47
|
+
/**
|
|
48
|
+
* Values for the `context` fields `condition` reads, used when a call
|
|
49
|
+
* leaves one out. Their types are the fields calls can pass. A field a
|
|
50
|
+
* call passes replaces its default whole: nested objects aren't merged.
|
|
51
|
+
* A field the branches' links also read must fit their type.
|
|
52
|
+
*/
|
|
53
|
+
context: TContext & fitBranchContext<TContext, TTrue, TFalse>;
|
|
54
|
+
}): SplitLink<TRouter, TTrue, TFalse, TContext>;
|
|
55
|
+
export { splitLink as t };
|
|
56
|
+
//# sourceMappingURL=splitLink-BGLTgm1a.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"splitLink-BGLTgm1a.d.mts","names":[],"sources":["../src/links/splitLink.ts"],"mappings":";;;;;;KAgCK,gBAAgB,gBAAgB,aACjC,SAAS,yBACA,SAAS;KAGjB,QAAQ,WAAW,qCACpB,WACC;UAEK,iBACR,gBAAgB,WAChB,cAAc,gBAAgB,UAC9B,eAAe,gBAAgB,UAC/B;;;;EAKA,YAAY,IAAI,mBAAmB;;;;EAInC,MAAM;;;;EAIN,OAAO;;KAKJ,iBAAiB,UAAU,OAAO,UACrC,8BACM,QAAQ,WAAW,QAAQ,yBACjB,gBACT,cAAc,iBAAiB,YAAY,UAAU;KAGzD,UACH,gBAAgB,WAChB,cAAc,gBAAgB,UAC9B,eAAe,gBAAgB,UAC/B,2BACE,SACF;EAEE,SAAS,WACP,8BAA8B,QAAQ,WAAW,QAAQ;;;;;;;;;;;;;;;;;;iBAoB/C,UACd,gBAAgB,YAAY,iBAEtB,cAAc,gBAAgB,WAAW,gBAAgB,gBACzD,eAAe,gBAAgB,WAAW,gBAAgB,UAEhE,MAAM,iBAAiB,SAAS,OAAO,QAAQ;EAC7C;IAGD,UAAU,SAAS,OAAO,QAAQ;iBACrB,UACd,gBAAgB,iBACV,cAAc,gBAAgB,gBAC9B,eAAe,gBAAgB,UACrC,yBAEA,MAAM,iBAAiB,SAAS,OAAO,QAAQ;;;;;;;EAO7C,SAAS,WAAW,iBAAiB,UAAU,OAAO;IAEvD,UAAU,SAAS,OAAO,QAAQ"}
|