@trpc/client 11.22.2-canary.7.c01346ec8 → 11.23.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 (59) hide show
  1. package/README.md +0 -8
  2. package/dist/TRPCClientError-CxFRO7Js.mjs.map +1 -1
  3. package/dist/{httpBatchLink-DO3WQoxu.cjs → httpBatchLink-Cmao5uUF.cjs} +1 -1
  4. package/dist/{httpBatchLink-BMtWxLJV.mjs → httpBatchLink-DPypDRI1.mjs} +2 -2
  5. package/dist/httpBatchLink-DPypDRI1.mjs.map +1 -0
  6. package/dist/{httpLink-Tm93WWFA.mjs → httpLink--yqaZ9lA.mjs} +2 -2
  7. package/dist/{httpLink-Tm93WWFA.mjs.map → httpLink--yqaZ9lA.mjs.map} +1 -1
  8. package/dist/{httpLink-MDJTSlpi.cjs → httpLink-B6E1HSLY.cjs} +1 -1
  9. package/dist/{httpUtils-CB_100ND.mjs → httpUtils-CAZsqwOQ.mjs} +3 -2
  10. package/dist/httpUtils-CAZsqwOQ.mjs.map +1 -0
  11. package/dist/{httpUtils-cggqcHz0.cjs → httpUtils-CrSF2CZF.cjs} +2 -1
  12. package/dist/index.cjs +13 -7
  13. package/dist/index.d.cts +8 -3
  14. package/dist/index.d.cts.map +1 -1
  15. package/dist/index.d.mts +8 -3
  16. package/dist/index.d.mts.map +1 -1
  17. package/dist/index.mjs +13 -8
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/links/httpBatchLink.cjs +1 -1
  20. package/dist/links/httpBatchLink.mjs +1 -1
  21. package/dist/links/httpLink.cjs +1 -1
  22. package/dist/links/httpLink.mjs +1 -1
  23. package/dist/links/wsLink/wsLink.cjs +1 -1
  24. package/dist/links/wsLink/wsLink.mjs +1 -1
  25. package/dist/types-BxbMkv6C.d.cts.map +1 -1
  26. package/dist/types-CAPs7vhA.d.mts.map +1 -1
  27. package/dist/{wsLink-Bm5LKL6z.mjs → wsLink--7trqYPG.mjs} +2 -1
  28. package/dist/wsLink--7trqYPG.mjs.map +1 -0
  29. package/dist/wsLink-C3hsDLsL.d.cts.map +1 -1
  30. package/dist/{wsLink-CKAsNP9P.cjs → wsLink-CQGBu_VZ.cjs} +1 -0
  31. package/dist/wsLink-DnvK9sTv.d.mts.map +1 -1
  32. package/package.json +10 -21
  33. package/skills/client-setup/SKILL.md +240 -207
  34. package/skills/links/SKILL.md +98 -224
  35. package/skills/links/references/client-links-httpBatchLink.md +210 -0
  36. package/skills/links/references/client-links-httpBatchStreamLink.md +159 -0
  37. package/skills/links/references/client-links-httpLink.md +63 -0
  38. package/skills/links/references/client-links-httpSubscriptionLink.md +404 -0
  39. package/skills/links/references/client-links-localLink.md +78 -0
  40. package/skills/links/references/client-links-loggerLink.md +66 -0
  41. package/skills/links/references/client-links-retryLink.md +89 -0
  42. package/skills/links/references/client-links-splitLink.md +103 -0
  43. package/skills/links/references/client-links-wsLink.md +122 -0
  44. package/skills/superjson/SKILL.md +132 -183
  45. package/src/TRPCClientError.ts +2 -2
  46. package/src/createTRPCClient.ts +1 -1
  47. package/src/getFetch.ts +0 -1
  48. package/src/internals/dataLoader.ts +1 -1
  49. package/src/links/httpBatchStreamLink.ts +1 -1
  50. package/src/links/internals/httpUtils.ts +6 -1
  51. package/src/links/localLink.ts +10 -4
  52. package/src/links/types.ts +2 -1
  53. package/src/links/wsLink/wsClient/utils.ts +1 -1
  54. package/src/links/wsLink/wsClient/wsClient.ts +4 -0
  55. package/bin/intent.js +0 -20
  56. package/dist/httpBatchLink-BMtWxLJV.mjs.map +0 -1
  57. package/dist/httpUtils-CB_100ND.mjs.map +0 -1
  58. package/dist/wsLink-Bm5LKL6z.mjs.map +0 -1
  59. package/skills/links/references/link-options.md +0 -248
@@ -0,0 +1,78 @@
1
+ # Local Link
2
+
3
+ > A link for direct procedure calls without HTTP overhead
4
+
5
+ From https://trpc.io/docs/client/links/localLink
6
+
7
+ `localLink` is a [**terminating link**](https://trpc.io/docs/client/links#the-terminating-link) that allows you to make tRPC procedure calls directly in your application without going through HTTP.
8
+
9
+ > [!NOTE] Info
10
+ > We have prefixed this as `unstable_` as it's a new API, but you're safe to use it! [Read more](https://trpc.io/docs/faq#unstable).
11
+
12
+
13
+ ## Usage
14
+
15
+ ```tsx no-check
16
+ import { createTRPCClient, unstable_localLink } from '@trpc/client';
17
+ import type { AppRouter } from './server';
18
+ import { appRouter } from './server';
19
+
20
+ const client = createTRPCClient<AppRouter>({
21
+ links: [
22
+ unstable_localLink({
23
+ router: appRouter,
24
+ createContext: async () => {
25
+ // Create your context here
26
+ return {};
27
+ },
28
+ onError: (opts) => {
29
+ // Log errors here, similarly to how you would in an API route
30
+ console.error('Error:', opts.error);
31
+ },
32
+ }),
33
+ ],
34
+ });
35
+ ```
36
+
37
+ ## Features
38
+
39
+ - Direct procedure calls without HTTP overhead
40
+ - Full support for queries, mutations, and subscriptions
41
+ - Automatic error handling and transformation
42
+ - Support for abort signals
43
+ - Type-safe context creation
44
+
45
+ ## Options
46
+
47
+ The `localLink` accepts the following options:
48
+
49
+ ```ts no-check
50
+ type LocalLinkOptions<TRouter extends AnyRouter> = {
51
+ router: TRouter;
52
+ createContext: () => Promise<inferRouterContext<TRouter>>;
53
+ onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;
54
+ } & TransformerOptions<inferClientTypes<TRouter>>;
55
+ ```
56
+
57
+ ### router
58
+
59
+ The tRPC router instance to use for procedure calls.
60
+
61
+ ### createContext
62
+
63
+ A function that creates the context for each procedure call. This is called for each request and should return a promise that resolves to the context object.
64
+
65
+ ### onError
66
+
67
+ An optional error handler that is called when an error occurs during a procedure call. It receives the error, operation type, path, input, and context.
68
+
69
+ ### transformer
70
+
71
+ Optional input/output transformers for serialization/deserialization of data.
72
+
73
+ ## Notes
74
+
75
+ - It's recommended to use this link in scenarios where you need direct procedure calls without HTTP
76
+ - For most client-side applications, you should use the `httpLink` or other HTTP-based links instead
77
+ - The link supports all tRPC features including queries, mutations, and subscriptions
78
+ - Error handling and transformation are handled automatically, just like with HTTP-based links
@@ -0,0 +1,66 @@
1
+ # Logger Link
2
+
3
+ > A link that logs tRPC operations and their results
4
+
5
+ From https://trpc.io/docs/client/links/loggerLink
6
+
7
+ `loggerLink` is a link that lets you implement a logger for your tRPC client. It allows you to see more clearly what operations are queries, mutations, or subscriptions, their requests, and responses. The link, by default, prints a prettified log to the browser's console. However, you can customize the logging behavior and the way it prints to the console with your own implementations.
8
+
9
+ ## Usage
10
+
11
+ You can import and add the `loggerLink` to the `links` array as such:
12
+
13
+ ```ts no-check title="client/index.ts"
14
+ import { createTRPCClient, httpBatchLink, loggerLink } from '@trpc/client';
15
+ import type { AppRouter } from './server';
16
+
17
+ const client = createTRPCClient<AppRouter>({
18
+ links: [
19
+ /**
20
+ * The function passed to enabled is an example in case you want to the link to
21
+ * log to your console in development and only log errors in production
22
+ */
23
+ loggerLink({
24
+ enabled: (opts) =>
25
+ (process.env.NODE_ENV === 'development' &&
26
+ typeof window !== 'undefined') ||
27
+ (opts.direction === 'down' && opts.result instanceof Error),
28
+ }),
29
+ httpBatchLink({
30
+ url: 'http://localhost:3000',
31
+ }),
32
+ ],
33
+ });
34
+ ```
35
+
36
+ ## `loggerLink` Options
37
+
38
+ The `loggerLink` function takes an options object that has the `LoggerLinkOptions` shape:
39
+
40
+ ```ts no-check
41
+ type LoggerLinkOptions<TRouter extends AnyRouter> = {
42
+ logger?: LogFn<TRouter>;
43
+ /**
44
+ * It is a function that returns a condition that determines whether to enable the logger.
45
+ * It is true by default.
46
+ */
47
+ enabled?: EnabledFn<TRouter>;
48
+ /**
49
+ * Used in the built-in defaultLogger
50
+ */
51
+ console?: ConsoleEsque;
52
+ /**
53
+ * Color mode used in the default logger.
54
+ * @default typeof window === 'undefined' ? 'ansi' : 'css'
55
+ */
56
+ colorMode?: 'ansi' | 'css' | 'none';
57
+ /**
58
+ * Include context in the log - defaults to false unless colorMode is 'css'
59
+ */
60
+ withContext?: boolean;
61
+ };
62
+ ```
63
+
64
+ ## Reference
65
+
66
+ You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/loggerLink.ts)
@@ -0,0 +1,89 @@
1
+ # Retry Link
2
+
3
+ > A link that retries failed operations
4
+
5
+ From https://trpc.io/docs/client/links/retryLink
6
+
7
+ `retryLink` is a link that allows you to retry failed operations in your tRPC client. It provides a customizable way to handle transient errors, such as network failures or server errors, by automatically retrying the failed requests based on specified conditions.
8
+
9
+ > [!TIP]
10
+ > If you use `@trpc/react-query` you will generally **not** need this link as it's built into the `useQuery()` and the `useMutation()` hooks from `@tanstack/react-query`.
11
+
12
+
13
+ ## Usage
14
+
15
+ You can import and add the `retryLink` to the `links` array when creating your tRPC client. This link can be placed before or after other links in your setup, depending on your requirements.
16
+
17
+ ```ts no-check
18
+ import { createTRPCClient, httpBatchLink, retryLink } from '@trpc/client';
19
+ import type { AppRouter } from './server';
20
+
21
+ const client = createTRPCClient<AppRouter>({
22
+ links: [
23
+ retryLink({
24
+ retry(opts) {
25
+ if (
26
+ opts.error.data &&
27
+ opts.error.data.code !== 'INTERNAL_SERVER_ERROR'
28
+ ) {
29
+ // Don't retry on non-500s
30
+ return false;
31
+ }
32
+ if (opts.op.type !== 'query') {
33
+ // Only retry queries
34
+ return false;
35
+ }
36
+
37
+ // Retry up to 3 times
38
+ return opts.attempts <= 3;
39
+ },
40
+ // Double every attempt, with max of 30 seconds (starting at 1 second)
41
+ retryDelayMs: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
42
+ }),
43
+ httpBatchLink({
44
+ url: 'http://localhost:3000',
45
+ }),
46
+ ],
47
+ });
48
+ ```
49
+
50
+ In the example above, we add the `retryLink` before the `httpBatchLink`. The `retry` function is required and defines when to retry. In this example, it will:
51
+
52
+ - Retry the request if the error is a `TRPCClientError` with a status code of 500 or if we couldn't get a valid tRPC error.
53
+ - Retry the request up to 3 times.
54
+
55
+ ## Options
56
+
57
+ ```ts no-check
58
+ interface RetryLinkOptions<TInferrable extends InferrableClientTypes> {
59
+ /**
60
+ * The retry function
61
+ */
62
+ retry: (opts: RetryFnOptions<TInferrable>) => boolean;
63
+ /**
64
+ * The delay between retries in ms (defaults to 0)
65
+ */
66
+ retryDelayMs?: (attempt: number) => number;
67
+ }
68
+
69
+ interface RetryFnOptions<TInferrable extends InferrableClientTypes> {
70
+ /**
71
+ * The operation that failed
72
+ */
73
+ op: Operation;
74
+ /**
75
+ * The error that occurred
76
+ */
77
+ error: TRPCClientError<TInferrable>;
78
+ /**
79
+ * The number of attempts that have been made (including the first call)
80
+ */
81
+ attempts: number;
82
+ }
83
+ ```
84
+
85
+ ## Handling tracked() events
86
+
87
+ When using `retryLink` with subscriptions that use [`tracked()`](https://trpc.io/docs/server/subscriptions#tracked), the link will automatically include the last known event ID when retrying. This ensures that when a subscription reconnects, it can resume from where it left off without missing any events.
88
+
89
+ For example, if you're using Server-sent Events (SSE) with `httpSubscriptionLink`, the `retryLink` will automatically handle reconnecting with the last event ID when errors like `401 Unauthorized` occur.
@@ -0,0 +1,103 @@
1
+ # Split Link
2
+
3
+ > A link that routes each operation down one of two link chains based on a condition
4
+
5
+ From https://trpc.io/docs/client/links/splitLink
6
+
7
+ `splitLink` is a link that allows you to branch your link chain's execution depending on a given condition. Both the `true` and `false` branches are required. You can provide just one link, or multiple links per branch via an array.
8
+
9
+ It's important to note that when you provide links for `splitLink` to execute, `splitLink` will create an entirely new link chain based on the links you passed. Therefore, you need to use a [**terminating link**](https://trpc.io/docs/client/links#the-terminating-link) if you only provide one link or add the terminating link at the end of the array if you provide multiple links to be executed on a branch. Here's a visual representation of how `splitLink` works:
10
+
11
+ <div align="center" style="margin-bottom: 12px">
12
+ <img src="/v11/img/split-link-diagram.svg" alt="" style="width: 100%; height: 100%" />
13
+ </div>
14
+
15
+ ## Usage Example
16
+
17
+ ### Disable batching for certain requests
18
+
19
+ Let's say you're using `httpBatchLink` as the terminating link in your tRPC client config. This means request batching is enabled in every request. However, if you need to disable batching only for certain requests, you would need to change the terminating link in your tRPC client config dynamically between `httpLink` and `httpBatchLink`. This is a perfect opportunity for `splitLink` to be used:
20
+
21
+ #### 1. Configure client / `utils/trpc.ts`
22
+
23
+ ```ts no-check title="client/index.ts"
24
+ import {
25
+ createTRPCClient,
26
+ httpBatchLink,
27
+ httpLink,
28
+ splitLink,
29
+ } from '@trpc/client';
30
+ import type { AppRouter } from './server';
31
+
32
+ const url = `http://localhost:3000`;
33
+
34
+ const client = createTRPCClient<AppRouter>({
35
+ links: [
36
+ splitLink({
37
+ condition(op) {
38
+ // check for context property `skipBatch`
39
+ return Boolean(op.context.skipBatch);
40
+ },
41
+ // when condition is true, use normal request
42
+ true: httpLink({
43
+ url,
44
+ }),
45
+ // when condition is false, use batching
46
+ false: httpBatchLink({
47
+ url,
48
+ }),
49
+ }),
50
+ ],
51
+ });
52
+ ```
53
+
54
+ #### 2. Perform request without batching
55
+
56
+ ```ts no-check title="client.ts"
57
+ const postResult = proxy.posts.query(undefined, {
58
+ context: {
59
+ skipBatch: true,
60
+ },
61
+ });
62
+ ```
63
+
64
+ or:
65
+
66
+ ```tsx no-check title="MyComponent.tsx"
67
+ import { trpc } from './trpc';
68
+
69
+ export function MyComponent() {
70
+ const postsQuery = trpc.posts.useQuery(undefined, {
71
+ trpc: {
72
+ context: {
73
+ skipBatch: true,
74
+ },
75
+ }
76
+ });
77
+ return (
78
+ <pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>
79
+ )
80
+ }
81
+ ```
82
+
83
+ ## `splitLink` Options
84
+
85
+ The `splitLink` function takes an options object that has three fields: `condition`, `true`, and `false`.
86
+
87
+ ```ts no-check
88
+ declare function splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {
89
+ condition: (op: Operation) => boolean;
90
+ /**
91
+ * The link to execute next if the test function returns `true`.
92
+ */
93
+ true: TRPCLink<TRouter> | TRPCLink<TRouter>[];
94
+ /**
95
+ * The link to execute next if the test function returns `false`.
96
+ */
97
+ false: TRPCLink<TRouter> | TRPCLink<TRouter>[];
98
+ }): TRPCLink<TRouter>;
99
+ ```
100
+
101
+ ## Reference
102
+
103
+ You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/splitLink.ts)
@@ -0,0 +1,122 @@
1
+ # WebSocket Link
2
+
3
+ > A terminating link that sends tRPC operations over a WebSocket
4
+
5
+ From https://trpc.io/docs/client/links/wsLink
6
+
7
+ `wsLink` is a [**terminating link**](https://trpc.io/docs/client/links#the-terminating-link) that's used when using tRPC's WebSockets Client and Subscriptions, which you can learn more about [here](https://trpc.io/docs/server/subscriptions).
8
+
9
+ ## Usage
10
+
11
+ To use `wsLink`, you need to pass it a `TRPCWebSocketClient`, which you can create with `createWSClient`:
12
+
13
+ ```ts no-check title="client/index.ts"
14
+ import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
15
+ import type { AppRouter } from './server';
16
+
17
+ const wsClient = createWSClient({
18
+ url: 'ws://localhost:3000',
19
+ });
20
+
21
+ const trpcClient = createTRPCClient<AppRouter>({
22
+ links: [wsLink<AppRouter>({ client: wsClient })],
23
+ });
24
+ ```
25
+
26
+ ## Authentication / Connection params
27
+
28
+ [See more here](https://trpc.io/docs/server/websockets#connection-params)
29
+
30
+ ## `wsLink` / `createWSClient` Options
31
+
32
+ The `wsLink` function requires a `TRPCWebSocketClient` to be passed, which can be configured with the fields defined in `WebSocketClientOptions`:
33
+
34
+ ```ts no-check
35
+ export interface WebSocketLinkOptions {
36
+ client: TRPCWebSocketClient;
37
+ /**
38
+ * Data transformer
39
+ * @see https://trpc.io/docs/v11/data-transformers
40
+ **/
41
+ transformer?: DataTransformerOptions;
42
+ }
43
+
44
+ declare function createWSClient(opts: WebSocketClientOptions): TRPCWebSocketClient;
45
+
46
+
47
+ export interface WebSocketClientOptions {
48
+ /**
49
+ * The URL to connect to (can be a function that returns a URL)
50
+ */
51
+ url: string | (() => MaybePromise<string>);
52
+ /**
53
+ * Connection params that are available in `createContext()`
54
+ * These are sent as the first message
55
+ */
56
+ connectionParams?: Record<string, string> | null | (() => MaybePromise<Record<string, string> | null>);
57
+ /**
58
+ * Ponyfill which WebSocket implementation to use
59
+ */
60
+ WebSocket?: typeof WebSocket;
61
+ /**
62
+ * The number of milliseconds before a reconnect is attempted.
63
+ * @default {@link exponentialBackoff}
64
+ */
65
+ retryDelayMs?: typeof exponentialBackoff;
66
+ /**
67
+ * Triggered when a WebSocket connection is established
68
+ */
69
+ onOpen?: () => void;
70
+ /**
71
+ * Triggered when a WebSocket connection encounters an error
72
+ */
73
+ onError?: (evt?: Event) => void;
74
+ /**
75
+ * Triggered when a WebSocket connection is closed
76
+ */
77
+ onClose?: (cause?: { code?: number }) => void;
78
+ /**
79
+ * Lazy mode will close the WebSocket automatically after a period of inactivity (no messages sent or received and no pending requests)
80
+ */
81
+ lazy?: {
82
+ /**
83
+ * Enable lazy mode
84
+ * @default false
85
+ */
86
+ enabled: boolean;
87
+ /**
88
+ * Close the WebSocket after this many milliseconds
89
+ * @default 0
90
+ */
91
+ closeMs: number;
92
+ };
93
+ /**
94
+ * Send ping messages to the server and kill the connection if no pong message is returned
95
+ */
96
+ keepAlive?: {
97
+ /**
98
+ * @default false
99
+ */
100
+ enabled: boolean;
101
+ /**
102
+ * Send a ping message every this many milliseconds
103
+ * @default 5_000
104
+ */
105
+ intervalMs?: number;
106
+ /**
107
+ * Close the WebSocket after this many milliseconds if the server does not respond
108
+ * @default 1_000
109
+ */
110
+ pongTimeoutMs?: number;
111
+ };
112
+ /**
113
+ * Custom encoder for wire encoding (e.g. custom binary formats)
114
+ * @default jsonEncoder
115
+ */
116
+ experimental_encoder?: Encoder;
117
+ }
118
+ ```
119
+
120
+ ## Reference
121
+
122
+ You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/wsLink)