@trpc/client 11.32.1 → 11.33.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.
Files changed (76) hide show
  1. package/dist/httpBatchLink-DRitkRBC.mjs.map +1 -1
  2. package/dist/{httpBatchLink-DbD4ZGAM.d.cts → httpBatchLink-DaVHWlLU.d.mts} +6 -4
  3. package/dist/{httpBatchLink-DbD4ZGAM.d.cts.map → httpBatchLink-DaVHWlLU.d.mts.map} +1 -1
  4. package/dist/{httpBatchLink-Dk3_n5pP.d.mts → httpBatchLink-_bkMj4mk.d.cts} +6 -4
  5. package/dist/{httpBatchLink-Dk3_n5pP.d.mts.map → httpBatchLink-_bkMj4mk.d.cts.map} +1 -1
  6. package/dist/httpLink-Cmg_mV7L.mjs.map +1 -1
  7. package/dist/{httpLink-BjZdBzr6.d.mts → httpLink-DN_Ana7a.d.mts} +6 -4
  8. package/dist/httpLink-DN_Ana7a.d.mts.map +1 -0
  9. package/dist/{httpUtils-CxgZ3W-1.d.cts → httpUtils-1z6dzl3V.d.cts} +2 -2
  10. package/dist/{httpUtils-CxgZ3W-1.d.cts.map → httpUtils-1z6dzl3V.d.cts.map} +1 -1
  11. package/dist/{httpUtils-gZ7bAQ6T.d.mts → httpUtils-BAs5frdP.d.mts} +2 -2
  12. package/dist/{httpUtils-gZ7bAQ6T.d.mts.map → httpUtils-BAs5frdP.d.mts.map} +1 -1
  13. package/dist/index.cjs +22 -14
  14. package/dist/index.d.cts +93 -21
  15. package/dist/index.d.cts.map +1 -1
  16. package/dist/index.d.mts +96 -24
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.mjs +22 -15
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/links/httpBatchLink.d.cts +1 -1
  21. package/dist/links/httpBatchLink.d.mts +1 -1
  22. package/dist/links/httpLink.d.cts +5 -3
  23. package/dist/links/httpLink.d.cts.map +1 -1
  24. package/dist/links/httpLink.d.mts +1 -1
  25. package/dist/links/loggerLink.d.cts +4 -2
  26. package/dist/links/loggerLink.d.cts.map +1 -1
  27. package/dist/links/loggerLink.d.mts +1 -1
  28. package/dist/links/loggerLink.mjs.map +1 -1
  29. package/dist/links/splitLink.cjs +1 -1
  30. package/dist/links/splitLink.d.cts +21 -8
  31. package/dist/links/splitLink.d.cts.map +1 -1
  32. package/dist/links/splitLink.d.mts +1 -1
  33. package/dist/links/splitLink.mjs +1 -1
  34. package/dist/links/wsLink/wsLink.d.cts +1 -1
  35. package/dist/links/wsLink/wsLink.d.mts +1 -1
  36. package/dist/{loggerLink-CBPx95zm.d.mts → loggerLink-CiVinJOG.d.mts} +5 -3
  37. package/dist/loggerLink-CiVinJOG.d.mts.map +1 -0
  38. package/dist/{splitLink-BBLj14Dv.cjs → splitLink-BQoYcpdp.cjs} +3 -0
  39. package/dist/splitLink-ClFN_nbg.d.mts +35 -0
  40. package/dist/splitLink-ClFN_nbg.d.mts.map +1 -0
  41. package/dist/{splitLink-PFsRy7Mf.mjs → splitLink-IUbsOwO6.mjs} +4 -1
  42. package/dist/splitLink-IUbsOwO6.mjs.map +1 -0
  43. package/dist/{types-BhHxuBsu.d.cts → types-DMe6B4SV.d.cts} +65 -8
  44. package/dist/types-DMe6B4SV.d.cts.map +1 -0
  45. package/dist/{types-BG-3kpeg.d.mts → types-DW0iJUBU.d.mts} +65 -8
  46. package/dist/types-DW0iJUBU.d.mts.map +1 -0
  47. package/dist/wsLink-C_Zg2yXV.mjs.map +1 -1
  48. package/dist/{wsLink-DU5wj6kH.d.mts → wsLink-DX5fv7-H.d.mts} +5 -3
  49. package/dist/{wsLink-BlAMQb0i.d.cts.map → wsLink-DX5fv7-H.d.mts.map} +1 -1
  50. package/dist/{wsLink-BlAMQb0i.d.cts → wsLink-DuyXOEPt.d.cts} +5 -3
  51. package/dist/{wsLink-DU5wj6kH.d.mts.map → wsLink-DuyXOEPt.d.cts.map} +1 -1
  52. package/package.json +3 -3
  53. package/skills/client-setup/SKILL.md +1 -1
  54. package/skills/links/SKILL.md +58 -1
  55. package/skills/superjson/SKILL.md +1 -1
  56. package/src/createTRPCClient.ts +88 -21
  57. package/src/index.ts +1 -0
  58. package/src/internals/types.ts +8 -5
  59. package/src/links/httpBatchLink.ts +6 -2
  60. package/src/links/httpBatchStreamLink.ts +6 -2
  61. package/src/links/httpLink.ts +6 -1
  62. package/src/links/httpSubscriptionLink.ts +6 -2
  63. package/src/links/localLink.ts +1 -1
  64. package/src/links/loggerLink.ts +11 -2
  65. package/src/links/retryLink.ts +6 -2
  66. package/src/links/splitLink.ts +52 -10
  67. package/src/links/types.ts +109 -3
  68. package/src/links/wsLink/wsLink.ts +1 -1
  69. package/src/routerType.ts +31 -0
  70. package/dist/httpLink-BjZdBzr6.d.mts.map +0 -1
  71. package/dist/loggerLink-CBPx95zm.d.mts.map +0 -1
  72. package/dist/splitLink-BtPz7lCB.d.mts +0 -23
  73. package/dist/splitLink-BtPz7lCB.d.mts.map +0 -1
  74. package/dist/splitLink-PFsRy7Mf.mjs.map +0 -1
  75. package/dist/types-BG-3kpeg.d.mts.map +0 -1
  76. package/dist/types-BhHxuBsu.d.cts.map +0 -1
@@ -24,6 +24,8 @@ import type {
24
24
  } from './internals/TRPCUntypedClient';
25
25
  import { TRPCUntypedClient } from './internals/TRPCUntypedClient';
26
26
  import type { TRPCProcedureOptions } from './internals/types';
27
+ import type { inferLinksContext, TRPCLink } from './links/types';
28
+ import type { RouterType } from './routerType';
27
29
  import type { TRPCTaggedPromise } from './safe';
28
30
  import type { TRPCClientError } from './TRPCClientError';
29
31
 
@@ -46,15 +48,22 @@ const untypedClientSymbol = Symbol.for('trpc_untypedClient');
46
48
  /**
47
49
  * A typed client for a router, as `createTRPCClient` returns it. Each
48
50
  * procedure has `.query()`, `.mutate()` or `.subscribe()`.
51
+ *
52
+ * `TContext` is the `context` calls take; `createTRPCClient({ router,
53
+ * links })` infers it from the links.
49
54
  * @see https://trpc.io/docs/client/vanilla/infer-types
50
55
  * @public
51
56
  **/
52
- export type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<
57
+ export type TRPCClient<
58
+ TRouter extends AnyRouter,
59
+ TContext extends object = Record<string, unknown>,
60
+ > = DecoratedProcedureRecord<
53
61
  {
54
62
  transformer: TRouter['_def']['_config']['$types']['transformer'];
55
63
  errorShape: TRouter['_def']['_config']['$types']['errorShape'];
56
64
  },
57
- TRouter['_def']['record']
65
+ TRouter['_def']['record'],
66
+ TContext
58
67
  > & {
59
68
  [untypedClientSymbol]: TRPCUntypedClient<TRouter>;
60
69
  };
@@ -79,9 +88,12 @@ type coerceAsyncGeneratorToIterable<T> =
79
88
  * The `.query()` or `.mutate()` of a procedure on the client.
80
89
  * @internal
81
90
  */
82
- export type Resolver<TDef extends TRPCResolverDef> = (
91
+ export type Resolver<
92
+ TDef extends TRPCResolverDef,
93
+ TContext extends object = Record<string, unknown>,
94
+ > = (
83
95
  input: TDef['input'],
84
- opts?: TRPCProcedureOptions,
96
+ opts?: TRPCProcedureOptions<TContext>,
85
97
  ) => TRPCTaggedPromise<
86
98
  coerceAsyncGeneratorToIterable<TDef['output']>,
87
99
  TDef['errorShape']
@@ -91,16 +103,19 @@ export type Resolver<TDef extends TRPCResolverDef> = (
91
103
  * The `.subscribe()` of a subscription procedure on the client.
92
104
  * @internal
93
105
  */
94
- export type SubscriptionResolver<TDef extends TRPCResolverDef> = {
106
+ export type SubscriptionResolver<
107
+ TDef extends TRPCResolverDef,
108
+ TContext extends object = Record<string, unknown>,
109
+ > = {
95
110
  (
96
111
  input: TDef['input'],
97
112
  opts: TRPCSubscriptionCallbacks<TDef['output'], TRPCClientError<TDef>> &
98
- TRPCProcedureOptions,
113
+ TRPCProcedureOptions<TContext>,
99
114
  ): Unsubscribable;
100
115
  <
101
- TOpts extends TRPCProcedureOptions &
116
+ TOpts extends TRPCProcedureOptions<TContext> &
102
117
  Partial<TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>> =
103
- TRPCProcedureOptions,
118
+ TRPCProcedureOptions<TContext>,
104
119
  >(
105
120
  input: TDef['input'],
106
121
  opts?: TRPCSubscriptionWithoutCallbacks<TOpts>,
@@ -110,18 +125,13 @@ export type SubscriptionResolver<TDef extends TRPCResolverDef> = {
110
125
  type DecorateProcedure<
111
126
  TType extends ProcedureType,
112
127
  TDef extends TRPCResolverDef,
128
+ TContext extends object,
113
129
  > = TType extends 'query'
114
- ? {
115
- query: Resolver<TDef>;
116
- }
130
+ ? { query: Resolver<TDef, TContext> }
117
131
  : TType extends 'mutation'
118
- ? {
119
- mutate: Resolver<TDef>;
120
- }
132
+ ? { mutate: Resolver<TDef, TContext> }
121
133
  : TType extends 'subscription'
122
- ? {
123
- subscribe: SubscriptionResolver<TDef>;
124
- }
134
+ ? { subscribe: SubscriptionResolver<TDef, TContext> }
125
135
  : never;
126
136
 
127
137
  /**
@@ -130,6 +140,7 @@ type DecorateProcedure<
130
140
  type DecoratedProcedureRecord<
131
141
  TRoot extends InferrableClientTypes,
132
142
  TRecord extends RouterRecord,
143
+ TContext extends object,
133
144
  > = {
134
145
  [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value
135
146
  ? $Value extends AnyProcedure
@@ -143,16 +154,17 @@ type DecoratedProcedureRecord<
143
154
  >;
144
155
  errorShape: inferProcedureErrorShape<TRoot, $Value>;
145
156
  transformer: inferClientTypes<TRoot>['transformer'];
146
- }
157
+ },
158
+ TContext
147
159
  >
148
160
  : $Value extends RouterRecord
149
- ? DecoratedProcedureRecord<TRoot, $Value>
161
+ ? DecoratedProcedureRecord<TRoot, $Value, TContext>
150
162
  : never
151
163
  : never;
152
164
  };
153
165
 
154
166
  const clientCallTypeMap: Record<
155
- keyof DecorateProcedure<any, any>,
167
+ keyof DecorateProcedure<any, any, any>,
156
168
  ProcedureType
157
169
  > = {
158
170
  query: 'query',
@@ -193,6 +205,52 @@ export function createTRPCClientProxy<TRouter extends AnyRouter>(
193
205
  });
194
206
  }
195
207
 
208
+ /**
209
+ * The options of `createTRPCClient` with the router's type passed as
210
+ * `router: routerType<AppRouter>()`.
211
+ * @public
212
+ */
213
+ export type CreateTRPCClientWithRouterOptions<
214
+ TRouter extends AnyRouter,
215
+ TLinks extends readonly TRPCLink<TRouter, any>[] = TRPCLink<TRouter>[],
216
+ > = Omit<CreateTRPCClientOptions<TRouter>, 'links'> & {
217
+ /**
218
+ * The router's type, from `routerType<AppRouter>()`. It's a type only:
219
+ * nothing about the router is sent or bundled.
220
+ */
221
+ router: RouterType<TRouter>;
222
+ /**
223
+ * The links each call goes through, in order. The last one must send
224
+ * the call, such as `httpBatchLink`. What they declare types each call's
225
+ * `context`, and which methods the client has. Pass them inline or
226
+ * `as const`: in an array declared without it, TypeScript can merge the
227
+ * links' types and drop what one declares.
228
+ * @see https://trpc.io/docs/client/links
229
+ */
230
+ links: TLinks;
231
+ };
232
+
233
+ /**
234
+ * Creates a typed client for a router. Pass the router's type with
235
+ * `routerType`, and the links that send its calls. What the links declare
236
+ * types each call's `context`.
237
+ * @example
238
+ * ```ts
239
+ * const client = createTRPCClient({
240
+ * router: routerType<AppRouter>(),
241
+ * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],
242
+ * });
243
+ * const post = await client.post.byId.query({ id: '1' });
244
+ * ```
245
+ * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client
246
+ */
247
+ export function createTRPCClient<
248
+ TRouter extends AnyRouter,
249
+ // with an explicit router type, the links aren't inferred
250
+ const TLinks extends readonly TRPCLink<TRouter, any>[] = TRPCLink<TRouter>[],
251
+ >(
252
+ opts: CreateTRPCClientWithRouterOptions<TRouter, TLinks>,
253
+ ): TRPCClient<TRouter, inferLinksContext<TLinks>>;
196
254
  /**
197
255
  * Creates a typed client for a router. Pass the router's type, and the
198
256
  * links that send its calls.
@@ -205,10 +263,19 @@ export function createTRPCClientProxy<TRouter extends AnyRouter>(
205
263
  * ```
206
264
  * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client
207
265
  */
266
+ // Kept last: `ReturnType<typeof createTRPCClient>` reads the last overload.
208
267
  export function createTRPCClient<TRouter extends AnyRouter>(
209
268
  opts: CreateTRPCClientOptions<TRouter>,
269
+ ): TRPCClient<TRouter>;
270
+ export function createTRPCClient<TRouter extends AnyRouter>(
271
+ opts: Omit<CreateTRPCClientOptions<TRouter>, 'links'> & {
272
+ links: readonly TRPCLink<TRouter, any>[];
273
+ },
210
274
  ): TRPCClient<TRouter> {
211
- const client = new TRPCUntypedClient(opts);
275
+ // `router` is a type only, so the untyped client ignores it
276
+ const client = new TRPCUntypedClient<TRouter>({
277
+ links: [...opts.links],
278
+ });
212
279
  const proxy = createTRPCClientProxy<TRouter>(client);
213
280
  return proxy;
214
281
  }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  export * from './createTRPCUntypedClient';
4
4
  export * from './createTRPCClient';
5
+ export * from './routerType';
5
6
  export * from './getFetch';
6
7
  export * from './TRPCClientError';
7
8
  export * from './links';
@@ -88,19 +88,22 @@ export interface ResponseEsque {
88
88
  */
89
89
  export type NonEmptyArray<TItem> = [TItem, ...TItem[]];
90
90
 
91
- type ClientContext = Record<string, unknown>;
92
-
93
91
  /**
94
92
  * The options of a call made with the client, such as
95
- * `client.post.byId.query(input, opts)`.
93
+ * `client.post.byId.query(input, opts)`. `TContext` is what the client's
94
+ * links read, when it was created with `router: routerType<AppRouter>()`.
96
95
  * @public
97
96
  */
98
- export interface TRPCProcedureOptions {
97
+ // The default is written out, not aliased, so declaration files that name
98
+ // a client's type don't need a reference to an internal alias.
99
+ export interface TRPCProcedureOptions<
100
+ TContext extends object = Record<string, unknown>,
101
+ > {
99
102
  /**
100
103
  * Context for the links, such as a flag a `splitLink` reads.
101
104
  * @see https://trpc.io/docs/client/links#managing-context
102
105
  */
103
- context?: ClientContext;
106
+ context?: TContext;
104
107
  /**
105
108
  * Aborts the call. With `httpBatchLink`, the request is only aborted once
106
109
  * every call in its batch is, so an aborted call can still get a result.
@@ -16,7 +16,7 @@ import {
16
16
  jsonHttpRequester,
17
17
  resolveHTTPLinkOptions,
18
18
  } from './internals/httpUtils';
19
- import type { Operation, TRPCLink } from './types';
19
+ import type { AugmentedOperationContext, Operation, TRPCLink } from './types';
20
20
 
21
21
  /**
22
22
  * A terminating link that batches calls made in the same tick into one HTTP
@@ -26,7 +26,11 @@ import type { Operation, TRPCLink } from './types';
26
26
  */
27
27
  export function httpBatchLink<TRouter extends AnyRouter>(
28
28
  opts: HTTPBatchLinkOptions<TRouter['_def']['_config']['$types']>,
29
- ): TRPCLink<TRouter> {
29
+ ): TRPCLink<
30
+ TRouter,
31
+ // its callbacks may read the fields added to `OperationContext`
32
+ { context: AugmentedOperationContext }
33
+ > {
30
34
  const resolvedOpts = resolveHTTPLinkOptions(opts);
31
35
  const maxURLLength = opts.maxURLLength ?? Infinity;
32
36
  const maxItems = opts.maxItems ?? Infinity;
@@ -20,7 +20,7 @@ import {
20
20
  getUrl,
21
21
  resolveHTTPLinkOptions,
22
22
  } from './internals/httpUtils';
23
- import type { Operation, TRPCLink } from './types';
23
+ import type { AugmentedOperationContext, Operation, TRPCLink } from './types';
24
24
 
25
25
  /**
26
26
  * Options for {@link httpBatchStreamLink}. Takes the same options as
@@ -53,7 +53,11 @@ type BatchStreamOperation = Operation & {
53
53
  */
54
54
  export function httpBatchStreamLink<TRouter extends AnyRouter>(
55
55
  opts: HTTPBatchStreamLinkOptions<TRouter['_def']['_config']['$types']>,
56
- ): TRPCLink<TRouter> {
56
+ ): TRPCLink<
57
+ TRouter,
58
+ // its callbacks may read the fields added to `OperationContext`
59
+ { context: AugmentedOperationContext }
60
+ > {
57
61
  const resolvedOpts = resolveHTTPLinkOptions(opts);
58
62
  const maxURLLength = opts.maxURLLength ?? Infinity;
59
63
  const maxItems = opts.maxItems ?? Infinity;
@@ -22,6 +22,7 @@ import {
22
22
  isOctetType,
23
23
  type HTTPHeaders,
24
24
  type Operation,
25
+ type AugmentedOperationContext,
25
26
  type TRPCLink,
26
27
  } from './types';
27
28
 
@@ -82,7 +83,11 @@ const universalRequester: Requester = (opts) => {
82
83
  */
83
84
  export function httpLink<TRouter extends AnyRouter = AnyRouter>(
84
85
  opts: HTTPLinkOptions<TRouter['_def']['_config']['$types']>,
85
- ): TRPCLink<TRouter> {
86
+ ): TRPCLink<
87
+ TRouter,
88
+ // its callbacks may read the fields added to `OperationContext`
89
+ { context: AugmentedOperationContext }
90
+ > {
86
91
  const resolvedOpts = resolveHTTPLinkOptions(opts);
87
92
  return () => {
88
93
  return (operationOpts) => {
@@ -22,7 +22,7 @@ import {
22
22
  resultOf,
23
23
  type UrlOptionsWithConnectionParams,
24
24
  } from './internals/urlWithConnectionParams';
25
- import type { Operation, TRPCLink } from './types';
25
+ import type { AugmentedOperationContext, Operation, TRPCLink } from './types';
26
26
 
27
27
  async function urlWithConnectionParams(
28
28
  opts: UrlOptionsWithConnectionParams,
@@ -79,7 +79,11 @@ export function httpSubscriptionLink<
79
79
  inferClientTypes<TInferrable>,
80
80
  TEventSource
81
81
  >,
82
- ): TRPCLink<TInferrable> {
82
+ ): TRPCLink<
83
+ TInferrable,
84
+ // its callbacks may read the fields added to `OperationContext`
85
+ { context: AugmentedOperationContext }
86
+ > {
83
87
  const transformer = getTransformer(opts.transformer);
84
88
  const pathSeparator = resolvePathSeparator(opts.pathSeparator);
85
89
 
@@ -86,7 +86,7 @@ export type LocalLinkOptions<TRouter extends AnyRouter> = {
86
86
  */
87
87
  export function localLink<TRouter extends AnyRouter>(
88
88
  opts: LocalLinkOptions<TRouter>,
89
- ): TRPCLink<TRouter> {
89
+ ): TRPCLink<TRouter, { context: {} }> {
90
90
  const transformer = getTransformer(opts.transformer);
91
91
 
92
92
  const transformChunk = (chunk: unknown) => {
@@ -11,7 +11,12 @@ import type {
11
11
  InferrableClientTypes,
12
12
  } from '@trpc/server/unstable-core-do-not-import';
13
13
  import type { TRPCClientError } from '../TRPCClientError';
14
- import type { Operation, OperationResultEnvelope, TRPCLink } from './types';
14
+ import type {
15
+ Operation,
16
+ AugmentedOperationContext,
17
+ OperationResultEnvelope,
18
+ TRPCLink,
19
+ } from './types';
15
20
 
16
21
  type ConsoleEsque = {
17
22
  log: (...args: any[]) => void;
@@ -229,7 +234,11 @@ const defaultLogger =
229
234
  */
230
235
  export function loggerLink<TRouter extends AnyRouter = AnyRouter>(
231
236
  opts: LoggerLinkOptions<TRouter> = {},
232
- ): TRPCLink<TRouter> {
237
+ ): TRPCLink<
238
+ TRouter,
239
+ // its callbacks may read the fields added to `OperationContext`
240
+ { context: AugmentedOperationContext }
241
+ > {
233
242
  const { enabled = () => true } = opts;
234
243
 
235
244
  const colorMode =
@@ -5,7 +5,7 @@ import { observable } from '@trpc/server/observable';
5
5
  import type { InferrableClientTypes } from '@trpc/server/unstable-core-do-not-import';
6
6
  import { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';
7
7
  import type { TRPCClientError } from '../TRPCClientError';
8
- import type { Operation, TRPCLink } from './types';
8
+ import type { AugmentedOperationContext, Operation, TRPCLink } from './types';
9
9
 
10
10
  interface RetryLinkOptions<TInferrable extends InferrableClientTypes> {
11
11
  /**
@@ -41,7 +41,11 @@ interface RetryFnOptions<TInferrable extends InferrableClientTypes> {
41
41
  */
42
42
  export function retryLink<TInferrable extends InferrableClientTypes>(
43
43
  opts: RetryLinkOptions<TInferrable>,
44
- ): TRPCLink<TInferrable> {
44
+ ): TRPCLink<
45
+ TInferrable,
46
+ // its callbacks may read the fields added to `OperationContext`
47
+ { context: AugmentedOperationContext }
48
+ > {
45
49
  // initialized config
46
50
  return () => {
47
51
  // initialized in app
@@ -1,17 +1,35 @@
1
1
  import { observable } from '@trpc/server/observable';
2
2
  import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';
3
3
  import { createChain } from './internals/createChain';
4
- import type { Operation, TRPCLink } from './types';
4
+ import type {
5
+ AugmentedOperationContext,
6
+ inferLinksDeclaredContext,
7
+ Operation,
8
+ TRPCLink,
9
+ } from './types';
5
10
 
6
- function asArray<TType>(value: TType | TType[]) {
7
- return Array.isArray(value) ? value : [value];
11
+ function asArray<TType>(value: TType | readonly TType[]): readonly TType[] {
12
+ return Array.isArray(value) ? value : [value as TType];
8
13
  }
14
+
9
15
  /**
10
- * Sends each operation down one of two link chains, based on `condition`.
11
- *
12
- * @see https://trpc.io/docs/client/links/splitLink
16
+ * A `splitLink` branch: one link or a chain of them.
17
+ * @internal
13
18
  */
14
- export function splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {
19
+ type SplitLinkBranch<TRouter extends AnyRouter> =
20
+ | TRPCLink<TRouter, any>
21
+ | readonly TRPCLink<TRouter, any>[];
22
+
23
+ // a tuple, so links whose declarations nest aren't merged into one
24
+ type asLinks<TBranch> = TBranch extends readonly unknown[]
25
+ ? TBranch
26
+ : [TBranch];
27
+
28
+ interface SplitLinkOptions<
29
+ TRouter extends AnyRouter,
30
+ TTrue extends SplitLinkBranch<TRouter>,
31
+ TFalse extends SplitLinkBranch<TRouter>,
32
+ > {
15
33
  /**
16
34
  * Picks the chain for an operation.
17
35
  */
@@ -19,12 +37,36 @@ export function splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {
19
37
  /**
20
38
  * The link to execute next if the test function returns `true`.
21
39
  */
22
- true: TRPCLink<TRouter> | TRPCLink<TRouter>[];
40
+ true: TTrue;
23
41
  /**
24
42
  * The link to execute next if the test function returns `false`.
25
43
  */
26
- false: TRPCLink<TRouter> | TRPCLink<TRouter>[];
27
- }): TRPCLink<TRouter> {
44
+ false: TFalse;
45
+ }
46
+
47
+ /**
48
+ * Sends each operation down one of two link chains, based on `condition`.
49
+ *
50
+ * Calls take the `context` both chains read. `condition` may read the
51
+ * fields added to `OperationContext`.
52
+ *
53
+ * @see https://trpc.io/docs/client/links/splitLink
54
+ */
55
+ export function splitLink<
56
+ TRouter extends AnyRouter = AnyRouter,
57
+ // with an explicit router type, a branch is still a link or an array
58
+ const TTrue extends SplitLinkBranch<TRouter> = SplitLinkBranch<TRouter>,
59
+ const TFalse extends SplitLinkBranch<TRouter> = SplitLinkBranch<TRouter>,
60
+ >(
61
+ opts: SplitLinkOptions<TRouter, TTrue, TFalse>,
62
+ ): TRPCLink<
63
+ TRouter,
64
+ {
65
+ // `condition` may read the fields added to `OperationContext`
66
+ context: AugmentedOperationContext &
67
+ inferLinksDeclaredContext<[...asLinks<TTrue>, ...asLinks<TFalse>]>;
68
+ }
69
+ > {
28
70
  return (runtime) => {
29
71
  const yes = asArray(opts.true).map((link) => link(runtime));
30
72
  const no = asArray(opts.false).map((link) => link(runtime));
@@ -2,6 +2,7 @@ import type { Observable, Observer } from '@trpc/server/observable';
2
2
  import type {
3
3
  InferrableClientTypes,
4
4
  Maybe,
5
+ Simplify,
5
6
  TRPCResultMessage,
6
7
  TRPCSuccessResponse,
7
8
  } from '@trpc/server/unstable-core-do-not-import';
@@ -22,6 +23,19 @@ export {
22
23
  */
23
24
  export interface OperationContext extends Record<string, unknown> {}
24
25
 
26
+ /**
27
+ * The fields added to `OperationContext` with module augmentation, without
28
+ * its `[key: string]: unknown`. Links that hand the operation to your code
29
+ * declare these, so calls take only fields something declared.
30
+ * @see https://trpc.io/docs/client/links#managing-context
31
+ * @public
32
+ */
33
+ export type AugmentedOperationContext = {
34
+ [
35
+ TKey in keyof OperationContext as string extends TKey ? never : TKey
36
+ ]: OperationContext[TKey];
37
+ };
38
+
25
39
  /**
26
40
  * A procedure call as it goes through the links.
27
41
  * @internal
@@ -115,12 +129,104 @@ export type OperationLink<
115
129
  ) => OperationResultObservable<TInferrable, TOutput>;
116
130
  }) => OperationResultObservable<TInferrable, TOutput>;
117
131
 
132
+ /**
133
+ * What a link declares about itself, for clients created with
134
+ * `createTRPCClient({ router: routerType<AppRouter>(), links })`.
135
+ * @see https://trpc.io/docs/client/links#typing-call-options
136
+ * @public
137
+ */
138
+ export interface LinkDecl {
139
+ /**
140
+ * The fields the link reads from `op.context`. Calls can pass them, typed,
141
+ * as `.query(input, { context })`. `{}` declares that the link reads none.
142
+ */
143
+ context?: object;
144
+ }
145
+
118
146
  /**
119
147
  * A link: a step every call goes through, such as logging or sending it
120
148
  * over HTTP. It's called once when the client is created.
149
+ *
150
+ * `TDecl` says what it reads from `op.context`. A link that doesn't
151
+ * declare it may read any context.
121
152
  * @see https://trpc.io/docs/client/links#creating-a-custom-link
122
153
  * @public
123
154
  */
124
- export type TRPCLink<TInferrable extends InferrableClientTypes> = (
125
- opts: TRPCClientRuntime,
126
- ) => OperationLink<TInferrable>;
155
+ export type TRPCLink<
156
+ TInferrable extends InferrableClientTypes,
157
+ TDecl extends LinkDecl = LinkDecl,
158
+ > = ((opts: TRPCClientRuntime) => OperationLink<TInferrable>) & {
159
+ /** Type-only: what the link declares. Never set. */
160
+ readonly '~decl'?: TDecl;
161
+ };
162
+
163
+ type UnionToIntersection<TUnion> = (
164
+ TUnion extends any ? (arg: TUnion) => void : never
165
+ ) extends (arg: infer TIntersection) => void
166
+ ? TIntersection
167
+ : never;
168
+
169
+ // A function with no `~decl`, such as an inline `() => ({ op, next }) =>
170
+ // next(op)`, declares nothing either.
171
+ type inferLinkDecl<TLink> = TLink extends unknown
172
+ ? '~decl' extends keyof TLink
173
+ ? NonNullable<TLink['~decl' & keyof TLink]>
174
+ : LinkDecl
175
+ : never;
176
+
177
+ type inferDeclContext<TDecl> = TDecl extends unknown
178
+ ? // a link that declares nothing may read any context
179
+ LinkDecl extends TDecl
180
+ ? OperationContext
181
+ : TDecl extends { context: infer $Context }
182
+ ? $Context
183
+ : {}
184
+ : never;
185
+
186
+ declare const noLinkReadsContext: unique symbol;
187
+
188
+ /**
189
+ * The call options' `context` when no link reads one: passing any field is
190
+ * an error.
191
+ * @public
192
+ */
193
+ // A type literal, not an interface: like `Record<string, unknown>`, it
194
+ // then fits where any context is taken, so procedures and handles from
195
+ // clients typed both ways stay compatible.
196
+ export type NoLinkReadsContext = {
197
+ readonly [noLinkReadsContext]?: never;
198
+ };
199
+
200
+ /**
201
+ * The fields the links in `TLinks` declare they read, merged, for a link
202
+ * that wraps other links to declare.
203
+ * @public
204
+ */
205
+ export type inferLinksDeclaredContext<TLinks extends readonly unknown[]> =
206
+ // boxed per link, so a link that declares a union of contexts keeps it
207
+ // instead of having its alternatives intersected
208
+ UnionToIntersection<
209
+ TLinks[number] extends infer $Link
210
+ ? $Link extends unknown
211
+ ? { context: inferDeclContext<inferLinkDecl<$Link>> }
212
+ : never
213
+ : never
214
+ > extends { context: infer $Context }
215
+ ? $Context
216
+ : {};
217
+
218
+ /**
219
+ * The `context` calls can pass: the fields every link in `TLinks` reads,
220
+ * merged.
221
+ * @public
222
+ */
223
+ export type inferLinksContext<TLinks extends readonly unknown[]> =
224
+ inferLinksDeclaredContext<TLinks> extends infer $Context
225
+ ? // per alternative, so a union with no common keys keeps them
226
+ $Context extends unknown
227
+ ? keyof $Context extends never
228
+ ? NoLinkReadsContext
229
+ : // optional: a call can leave out its options altogether
230
+ Simplify<Partial<$Context>>
231
+ : never
232
+ : never;
@@ -34,7 +34,7 @@ export type WebSocketLinkOptions<TRouter extends AnyRouter> = {
34
34
  */
35
35
  export function wsLink<TRouter extends AnyRouter>(
36
36
  opts: WebSocketLinkOptions<TRouter>,
37
- ): TRPCLink<TRouter> {
37
+ ): TRPCLink<TRouter, { context: {} }> {
38
38
  const { client } = opts;
39
39
  const transformer = getTransformer(opts.transformer);
40
40
  return () => {
@@ -0,0 +1,31 @@
1
+ import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';
2
+
3
+ declare const routerTypeBrand: unique symbol;
4
+
5
+ /**
6
+ * A value that carries a router's type and nothing else. Made by
7
+ * {@link routerType}.
8
+ * @public
9
+ */
10
+ export interface RouterType<TRouter extends AnyRouter> {
11
+ readonly [routerTypeBrand]: TRouter;
12
+ }
13
+
14
+ /**
15
+ * Passes a router's type to `createTRPCClient({ router })` as a normal
16
+ * option, instead of a type argument. Nothing about the router exists at
17
+ * runtime, so it's safe to import the router's type only.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const client = createTRPCClient({
22
+ * router: routerType<AppRouter>(),
23
+ * links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],
24
+ * });
25
+ * ```
26
+ * @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client
27
+ * @public
28
+ */
29
+ export function routerType<TRouter extends AnyRouter>(): RouterType<TRouter> {
30
+ return {} as RouterType<TRouter>;
31
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"httpLink-BjZdBzr6.d.mts","names":[],"sources":["../src/links/httpLink.ts"],"mappings":";;;;;;;KA+BY,gBAAgB,cAAc,kBACxC,oBAAoB;;;;;;EAMlB,UACI,gBACE;IAAQ,IAAI;QAAgB,cAAc,QAAQ;;;;;;;iBA0C5C,SAAS,gBAAgB,YAAY,WACnD,MAAM,gBAAgB,wCACrB,SAAS"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"loggerLink-CBPx95zm.d.mts","names":[],"sources":["../src/links/loggerLink.ts"],"mappings":";;KAeK;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,SAAS"}
@@ -1,23 +0,0 @@
1
- import { n as Operation, u as TRPCLink } from "./types-BG-3kpeg.mjs";
2
- import { AnyRouter } from "@trpc/server/unstable-core-do-not-import";
3
- /**
4
- * Sends each operation down one of two link chains, based on `condition`.
5
- *
6
- * @see https://trpc.io/docs/client/links/splitLink
7
- */
8
- declare function splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {
9
- /**
10
- * Picks the chain for an operation.
11
- */
12
- condition: (op: Operation) => boolean;
13
- /**
14
- * The link to execute next if the test function returns `true`.
15
- */
16
- true: TRPCLink<TRouter> | TRPCLink<TRouter>[];
17
- /**
18
- * The link to execute next if the test function returns `false`.
19
- */
20
- false: TRPCLink<TRouter> | TRPCLink<TRouter>[];
21
- }): TRPCLink<TRouter>;
22
- export { splitLink as t };
23
- //# sourceMappingURL=splitLink-BtPz7lCB.d.mts.map