@orpc/tanstack-query 2.0.0-beta.46 → 2.0.0-beta.48

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.
@@ -0,0 +1,406 @@
1
+ import { intercept, isAsyncIteratorObject, isTypescriptObject, resolveMaybeOptionalOptions, toArray } from "@orpc/shared";
2
+ import { skipToken } from "@tanstack/query-core";
3
+ import { liveQuery } from "./live-query.mjs";
4
+ import { SharedUtils } from "./shared-utils.mjs";
5
+ import { serializableStreamedQuery } from "./stream-query.mjs";
6
+ import { createStructuralSharing } from "./structural-sharing.mjs";
7
+ import { OPERATION_CONTEXT_SYMBOL } from "./types.mjs";
8
+ const PROCEDURE_UTILS_INTERCEPTOR_KEYS = [
9
+ "queryInterceptors",
10
+ "streamedInterceptors",
11
+ "liveInterceptors",
12
+ "infiniteInterceptors",
13
+ "mutationInterceptors"
14
+ ];
15
+ const PROCEDURE_UTILS_MODIFIER_KEYS = [
16
+ "queryKey",
17
+ "queryOptions",
18
+ "streamedKey",
19
+ "streamedOptions",
20
+ "liveKey",
21
+ "liveOptions",
22
+ "infiniteKey",
23
+ "infiniteOptions",
24
+ "mutationKey",
25
+ "mutationOptions"
26
+ ];
27
+ export function isProcedureUtilsOptions(value) {
28
+ if (!isTypescriptObject(value)) {
29
+ return false;
30
+ }
31
+ for (const key of Object.keys(value)) {
32
+ if (value[key] === undefined) {
33
+ continue;
34
+ }
35
+ if (key === "prefix") {
36
+ if (typeof value[key] !== "string") {
37
+ return false;
38
+ }
39
+ } else if (key === "serializer") {
40
+ if (!isTypescriptObject(value[key]) || typeof value[key].serializeJson !== "function") {
41
+ return false;
42
+ }
43
+ } else if (PROCEDURE_UTILS_INTERCEPTOR_KEYS.includes(key)) {
44
+ if (!Array.isArray(value[key]) || value[key].some((i) => typeof i !== "function")) {
45
+ return false;
46
+ }
47
+ } else if (PROCEDURE_UTILS_MODIFIER_KEYS.includes(key)) {
48
+ if (!isTypescriptObject(value[key])) {
49
+ return false;
50
+ }
51
+ }
52
+ }
53
+ return true;
54
+ }
55
+ function mergeProcedureUtilsModifier(base, override) {
56
+ if (typeof override !== "function") {
57
+ if (typeof base !== "function") {
58
+ return {
59
+ ...base,
60
+ ...override
61
+ };
62
+ }
63
+ return (options) => base({
64
+ ...override,
65
+ ...options
66
+ });
67
+ }
68
+ const applyBase = typeof base === "function" ? base : (options) => ({
69
+ ...base,
70
+ ...options
71
+ });
72
+ return (options) => override(applyBase(options));
73
+ }
74
+
75
+ export function mergeProcedureUtilsOptions(base, override) {
76
+ const merged = {
77
+ ...base,
78
+ ...override
79
+ };
80
+ for (const key of PROCEDURE_UTILS_INTERCEPTOR_KEYS) {
81
+ const baseValue = base[key];
82
+ const overrideValue = override[key];
83
+ if (baseValue && overrideValue) {
84
+ merged[key] = [...baseValue, ...overrideValue];
85
+ }
86
+ }
87
+ for (const key of PROCEDURE_UTILS_MODIFIER_KEYS) {
88
+ const baseValue = base[key];
89
+ const overrideValue = override[key];
90
+ if (baseValue && overrideValue) {
91
+ merged[key] = mergeProcedureUtilsModifier(baseValue, overrideValue);
92
+ }
93
+ }
94
+ return merged;
95
+ }
96
+ export class ProcedureUtils extends SharedUtils {
97
+
98
+ call;
99
+ constructor(path, client, options = {}) {
100
+ super(path, options);
101
+ this.call = client;
102
+ }
103
+
104
+ queryKey(...rest) {
105
+ let optionsIn = resolveMaybeOptionalOptions(rest);
106
+ if (typeof this.options.queryKey === "function") {
107
+ optionsIn = this.options.queryKey(optionsIn);
108
+ } else if (this.options.queryKey) {
109
+ optionsIn = {
110
+ ...this.options.queryKey,
111
+ ...optionsIn
112
+ };
113
+ }
114
+ const queryKey = optionsIn.queryKey ?? this.key({
115
+ type: "query",
116
+ input: optionsIn.input
117
+ });
118
+ return queryKey;
119
+ }
120
+
121
+ queryOptions(...rest) {
122
+ let optionsIn = resolveMaybeOptionalOptions(rest);
123
+ if (typeof this.options.queryOptions === "function") {
124
+ optionsIn = this.options.queryOptions(optionsIn);
125
+ } else if (this.options.queryOptions) {
126
+ optionsIn = {
127
+ ...this.options.queryOptions,
128
+ ...optionsIn
129
+ };
130
+ }
131
+ const queryKey = this.queryKey(optionsIn);
132
+ return {
133
+ structuralSharing: createStructuralSharing(this.options.serializer),
134
+ ...optionsIn,
135
+ queryKey,
136
+ queryFn: (fnContext) => {
137
+ return intercept(this.options.queryInterceptors, {
138
+ path: this.path,
139
+ context: {
140
+ [OPERATION_CONTEXT_SYMBOL]: {
141
+ key: queryKey,
142
+ type: "query"
143
+ },
144
+ ...optionsIn.context
145
+ },
146
+ input: optionsIn.input,
147
+ fnContext
148
+ }, ({ context, input, fnContext }) => {
149
+ if (input === skipToken || optionsIn.queryFn === skipToken) {
150
+ throw new Error("queryFn should not be called when skipToken used for skipping");
151
+ }
152
+ if (optionsIn.queryFn) {
153
+ return optionsIn.queryFn(fnContext);
154
+ }
155
+ return this.call(input, {
156
+ signal: fnContext.signal,
157
+ context
158
+ });
159
+ });
160
+ },
161
+ ...optionsIn.input === skipToken || optionsIn.queryFn === skipToken ? { enabled: false } : {}
162
+ };
163
+ }
164
+
165
+ streamedKey(...rest) {
166
+ let optionsIn = resolveMaybeOptionalOptions(rest);
167
+ if (typeof this.options.streamedKey === "function") {
168
+ optionsIn = this.options.streamedKey(optionsIn);
169
+ } else if (this.options.streamedKey) {
170
+ optionsIn = {
171
+ ...this.options.streamedKey,
172
+ ...optionsIn
173
+ };
174
+ }
175
+ const queryKey = optionsIn.queryKey ?? this.key({
176
+ type: "streamed",
177
+ input: optionsIn.input,
178
+ fnOptions: optionsIn.queryFnOptions
179
+ });
180
+ return queryKey;
181
+ }
182
+
183
+ streamedOptions(...rest) {
184
+ let optionsIn = resolveMaybeOptionalOptions(rest);
185
+ if (typeof this.options.streamedOptions === "function") {
186
+ optionsIn = this.options.streamedOptions(optionsIn);
187
+ } else if (this.options.streamedOptions) {
188
+ optionsIn = {
189
+ ...this.options.streamedOptions,
190
+ ...optionsIn
191
+ };
192
+ }
193
+ const queryKey = this.streamedKey(optionsIn);
194
+ return {
195
+ ...optionsIn,
196
+ queryKey,
197
+ queryFn: (fnContext) => {
198
+ return intercept(toArray(this.options.streamedInterceptors), {
199
+ path: this.path,
200
+ context: {
201
+ [OPERATION_CONTEXT_SYMBOL]: {
202
+ key: queryKey,
203
+ type: "streamed"
204
+ },
205
+ ...optionsIn.context
206
+ },
207
+ input: optionsIn.input,
208
+ fnContext
209
+ }, ({ context, fnContext, input }) => {
210
+ if (input === skipToken || optionsIn.queryFn === skipToken) {
211
+ throw new Error("queryFn should not be called when skipToken used for skipping");
212
+ }
213
+ if (optionsIn.queryFn) {
214
+ return optionsIn.queryFn(fnContext);
215
+ }
216
+ return serializableStreamedQuery(async (queryContext) => {
217
+ const output = await this.call(input, {
218
+ signal: queryContext.signal,
219
+ context
220
+ });
221
+ if (!isAsyncIteratorObject(output)) {
222
+ throw new Error("streamedQuery requires an AsyncIteratorObject output");
223
+ }
224
+ return output;
225
+ }, optionsIn.queryFnOptions)(fnContext);
226
+ });
227
+ },
228
+ ...optionsIn.input === skipToken || optionsIn.queryFn === skipToken ? { enabled: false } : {}
229
+ };
230
+ }
231
+
232
+ liveKey(...rest) {
233
+ let optionsIn = resolveMaybeOptionalOptions(rest);
234
+ if (typeof this.options.liveKey === "function") {
235
+ optionsIn = this.options.liveKey(optionsIn);
236
+ } else if (this.options.liveKey) {
237
+ optionsIn = {
238
+ ...this.options.liveKey,
239
+ ...optionsIn
240
+ };
241
+ }
242
+ const queryKey = optionsIn.queryKey ?? this.key({
243
+ type: "live",
244
+ input: optionsIn.input
245
+ });
246
+ return queryKey;
247
+ }
248
+
249
+ liveOptions(...rest) {
250
+ let optionsIn = resolveMaybeOptionalOptions(rest);
251
+ if (typeof this.options.liveOptions === "function") {
252
+ optionsIn = this.options.liveOptions(optionsIn);
253
+ } else if (this.options.liveOptions) {
254
+ optionsIn = {
255
+ ...this.options.liveOptions,
256
+ ...optionsIn
257
+ };
258
+ }
259
+ const queryKey = this.liveKey(optionsIn);
260
+ return {
261
+ structuralSharing: createStructuralSharing(this.options.serializer),
262
+ ...optionsIn,
263
+ queryKey,
264
+ queryFn: (fnContext) => {
265
+ return intercept(toArray(this.options.liveInterceptors), {
266
+ path: this.path,
267
+ context: {
268
+ [OPERATION_CONTEXT_SYMBOL]: {
269
+ key: queryKey,
270
+ type: "live"
271
+ },
272
+ ...optionsIn.context
273
+ },
274
+ input: optionsIn.input,
275
+ fnContext
276
+ }, ({ fnContext, input, context }) => {
277
+ if (input === skipToken || optionsIn.queryFn === skipToken) {
278
+ throw new Error("queryFn should not be called when skipToken used for skipping");
279
+ }
280
+ if (optionsIn.queryFn) {
281
+ return optionsIn.queryFn(fnContext);
282
+ }
283
+ return liveQuery(async (queryContext) => {
284
+ const output = await this.call(input, {
285
+ signal: queryContext.signal,
286
+ context
287
+ });
288
+ if (!isAsyncIteratorObject(output)) {
289
+ throw new Error("liveQuery requires an AsyncIteratorObject output");
290
+ }
291
+ return output;
292
+ })(fnContext);
293
+ });
294
+ },
295
+ ...optionsIn.input === skipToken || optionsIn.queryFn === skipToken ? { enabled: false } : {}
296
+ };
297
+ }
298
+
299
+ infiniteKey(optionsIn) {
300
+ if (typeof this.options.infiniteKey === "function") {
301
+ optionsIn = this.options.infiniteKey(optionsIn);
302
+ } else if (this.options.infiniteKey) {
303
+ optionsIn = {
304
+ ...this.options.infiniteKey,
305
+ ...optionsIn
306
+ };
307
+ }
308
+ const queryKey = optionsIn.queryKey ?? this.key({
309
+ type: "infinite",
310
+ input: optionsIn.input === skipToken ? skipToken : optionsIn.input(optionsIn.initialPageParam)
311
+ });
312
+ return queryKey;
313
+ }
314
+
315
+ infiniteOptions(optionsIn) {
316
+ if (typeof this.options.infiniteOptions === "function") {
317
+ optionsIn = this.options.infiniteOptions(optionsIn);
318
+ } else if (this.options.infiniteOptions) {
319
+ optionsIn = {
320
+ ...this.options.infiniteOptions,
321
+ ...optionsIn
322
+ };
323
+ }
324
+ const queryKey = this.infiniteKey(optionsIn);
325
+ return {
326
+ structuralSharing: createStructuralSharing(this.options.serializer),
327
+ ...optionsIn,
328
+ queryKey,
329
+ queryFn: (fnContext) => {
330
+ return intercept(toArray(this.options.infiniteInterceptors), {
331
+ path: this.path,
332
+ context: {
333
+ [OPERATION_CONTEXT_SYMBOL]: {
334
+ key: queryKey,
335
+ type: "infinite"
336
+ },
337
+ ...optionsIn.context
338
+ },
339
+ input: optionsIn.input === skipToken ? skipToken : optionsIn.input(fnContext.pageParam),
340
+ fnContext
341
+ }, ({ context, input, fnContext }) => {
342
+ if (input === skipToken || optionsIn.queryFn === skipToken) {
343
+ throw new Error("queryFn should not be called when skipToken used for skipping");
344
+ }
345
+ if (optionsIn.queryFn) {
346
+ return optionsIn.queryFn(fnContext);
347
+ }
348
+ return this.call(input, {
349
+ signal: fnContext.signal,
350
+ context
351
+ });
352
+ });
353
+ },
354
+ ...optionsIn.input === skipToken || optionsIn.queryFn === skipToken ? { enabled: false } : {}
355
+ };
356
+ }
357
+
358
+ mutationKey(optionsIn = {}) {
359
+ if (typeof this.options.mutationKey === "function") {
360
+ optionsIn = this.options.mutationKey(optionsIn);
361
+ } else if (this.options.mutationKey) {
362
+ optionsIn = {
363
+ ...this.options.mutationKey,
364
+ ...optionsIn
365
+ };
366
+ }
367
+ const mutationKey = optionsIn.mutationKey ?? this.key({ type: "mutation" });
368
+ return mutationKey;
369
+ }
370
+
371
+ mutationOptions(...rest) {
372
+ let optionsIn = resolveMaybeOptionalOptions(rest);
373
+ if (typeof this.options.mutationOptions === "function") {
374
+ optionsIn = this.options.mutationOptions(optionsIn);
375
+ } else if (this.options.mutationOptions) {
376
+ optionsIn = {
377
+ ...this.options.mutationOptions,
378
+ ...optionsIn
379
+ };
380
+ }
381
+ const mutationKey = this.mutationKey(optionsIn);
382
+ return {
383
+ ...optionsIn,
384
+ mutationKey,
385
+ mutationFn: (input, fnContext) => {
386
+ return intercept(toArray(this.options.mutationInterceptors), {
387
+ path: this.path,
388
+ context: {
389
+ [OPERATION_CONTEXT_SYMBOL]: {
390
+ key: mutationKey,
391
+ type: "mutation"
392
+ },
393
+ ...optionsIn.context
394
+ },
395
+ fnContext,
396
+ input
397
+ }, ({ input, fnContext, context }) => {
398
+ if (optionsIn.mutationFn) {
399
+ return optionsIn.mutationFn(input, fnContext);
400
+ }
401
+ return this.call(input, { context });
402
+ });
403
+ }
404
+ };
405
+ }
406
+ }
@@ -0,0 +1,57 @@
1
+ import type { AnyNestedClient, Client, InferClientContext, InferClientError } from "@orpc/client";
2
+ import type { Public } from "@orpc/shared";
3
+ import type { OperationKeyBaseOptions } from "./key.mjs";
4
+ import type { RouterUtilsPlugin } from "./plugin.mjs";
5
+ import type { ProcedureUtilsInfiniteInterceptor, ProcedureUtilsLiveInterceptor, ProcedureUtilsMutationInterceptor, ProcedureUtilsOptions, ProcedureUtilsQueryInterceptor, ProcedureUtilsStreamedInterceptor } from "./procedure-utils.mjs";
6
+ import { ProcedureUtils } from "./procedure-utils.mjs";
7
+ import { SharedUtils } from "./shared-utils.mjs";
8
+ /**
9
+ * The utils shape derived from a client: procedure clients map to procedure
10
+ * utils, and routers map recursively to nested utils.
11
+ *
12
+ * @see {@link https://orpc.dev/docs/integrations/tanstack-query | TanStack Query Integration}
13
+ */
14
+ export type RouterUtils<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Public<ProcedureUtils<UClientContext, UInput, UOutput, UError>> : { [K in keyof T]: T[K] extends AnyNestedClient ? RouterUtils<T[K]> : never } & Public<SharedUtils<unknown>>;
15
+ export type RouterUtilsScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ProcedureUtilsOptions<UClientContext, UInput, UOutput, UError> : { [K in keyof T]?: (T[K] extends AnyNestedClient ? RouterUtilsScoped<T[K]> : never) | undefined };
16
+ export interface RouterUtilsOptions<T extends AnyNestedClient> extends OperationKeyBaseOptions {
17
+ /**
18
+ * Interceptors that intercept queryFn inside .queryOptions
19
+ */
20
+ queryInterceptors?: ProcedureUtilsQueryInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
21
+ /**
22
+ * Interceptors that intercept queryFn inside .streamedOptions
23
+ */
24
+ streamedInterceptors?: ProcedureUtilsStreamedInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
25
+ /**
26
+ * Interceptors that intercept queryFn inside .liveOptions
27
+ */
28
+ liveInterceptors?: ProcedureUtilsLiveInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
29
+ /**
30
+ * Interceptors that intercept queryFn inside .infiniteOptions
31
+ */
32
+ infiniteInterceptors?: ProcedureUtilsInfiniteInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
33
+ /**
34
+ * Interceptors that intercept mutationFn inside .mutationOptions
35
+ */
36
+ mutationInterceptors?: ProcedureUtilsMutationInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
37
+ /**
38
+ * Per-procedure options following the shape of the router.
39
+ * Allows fine-grained configuration of individual procedure utils
40
+ * without affecting the rest of the router.
41
+ */
42
+ scoped?: RouterUtilsScoped<T> | undefined;
43
+ /**
44
+ * Plugins to extend router utils behavior.
45
+ */
46
+ plugins?: RouterUtilsPlugin<T>[] | undefined;
47
+ }
48
+ /**
49
+ * Creates TanStack Query utils from a client, exposing query/mutation
50
+ * option builders for every procedure in the router.
51
+ *
52
+ * @remarks
53
+ * **Note**: Both client-side and server-side clients are supported.
54
+ *
55
+ * @see {@link https://orpc.dev/docs/integrations/tanstack-query | TanStack Query Integration}
56
+ */
57
+ export declare function createRouterUtils<T extends AnyNestedClient>(client: T, options?: NoInfer<RouterUtilsOptions<T>>): RouterUtils<T>;
@@ -0,0 +1,51 @@
1
+ import { RECURSIVE_CLIENT_UNWRAP_KEYS } from "@orpc/client";
2
+ import { bindMethods, isTypescriptObject, pick, toArray } from "@orpc/shared";
3
+ import { CompositeRouterUtilsPlugin } from "./plugin.mjs";
4
+ import { isProcedureUtilsOptions, mergeProcedureUtilsOptions, ProcedureUtils } from "./procedure-utils.mjs";
5
+ import { SharedUtils } from "./shared-utils.mjs";
6
+
7
+ export function createRouterUtils(client, options = {}) {
8
+ const plugin = new CompositeRouterUtilsPlugin(options.plugins);
9
+ options = plugin.init(options);
10
+ return createRouterUtilsInternal(client, options, plugin);
11
+ }
12
+ function createRouterUtilsInternal(client, options, plugin) {
13
+ const path = toArray(options.path);
14
+ const utils = typeof client === "function" && (options.scoped === undefined || isProcedureUtilsOptions(options.scoped)) ? bindMethods(new ProcedureUtils(path, client, plugin.initProcedureOptions(path, mergeProcedureUtilsOptions(pick(options, [
15
+ "prefix",
16
+ "serializer",
17
+ "queryInterceptors",
18
+ "streamedInterceptors",
19
+ "liveInterceptors",
20
+ "infiniteInterceptors",
21
+ "mutationInterceptors"
22
+ ]), options.scoped ?? {}))), { unbound: ["call"] }) : bindMethods(new SharedUtils(path, options));
23
+ const cache = new Map();
24
+ const recursive = new Proxy(utils, { get(target, prop) {
25
+ const value = Reflect.get(target, prop);
26
+ if (RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
27
+ return value ?? Reflect.get(Object.prototype, prop);
28
+ }
29
+ const nextClient = Reflect.get(client, prop);
30
+ if (typeof prop !== "string" || !isTypescriptObject(nextClient)) {
31
+ return value;
32
+ }
33
+ let result = cache.get(prop);
34
+ if (result === undefined) {
35
+ const nextUtils = createRouterUtilsInternal(nextClient, {
36
+ ...options,
37
+ path: [...path, prop],
38
+ scoped: options.scoped?.[prop]
39
+ }, plugin);
40
+ result = typeof value !== "function" ? nextUtils : new Proxy(value, { get(target, prop) {
41
+ if (typeof prop !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
42
+ return Reflect.get(target, prop);
43
+ }
44
+ return Reflect.get(nextUtils, prop);
45
+ } });
46
+ cache.set(prop, result);
47
+ }
48
+ return result;
49
+ } });
50
+ return recursive;
51
+ }
@@ -0,0 +1,11 @@
1
+ import type { OperationKey, OperationKeyBaseOptions, OperationKeyOptions } from "./key.mjs";
2
+ import type { OperationType } from "./types.mjs";
3
+ export declare class SharedUtils<TInput> {
4
+ protected readonly path: string[];
5
+ protected readonly options: OperationKeyBaseOptions;
6
+ constructor(path: string[], options: OperationKeyBaseOptions);
7
+ /**
8
+ * Generate a **partial matching** key for actions like revalidating queries, checking mutation status, etc.
9
+ */
10
+ key<TType extends OperationType>(options?: Omit<OperationKeyOptions<TType, TInput>, keyof OperationKeyBaseOptions>): OperationKey<TType, TInput>;
11
+ }
@@ -0,0 +1,17 @@
1
+ import { generateOperationKey } from "./key.mjs";
2
+ export class SharedUtils {
3
+ path;
4
+ options;
5
+ constructor(path, options) {
6
+ this.path = path;
7
+ this.options = options;
8
+ }
9
+
10
+ key(options = {}) {
11
+ return generateOperationKey(this.path, {
12
+ ...options,
13
+ prefix: this.options.prefix,
14
+ serializer: this.options.serializer
15
+ });
16
+ }
17
+ }
package/dist/ssr.d.mts ADDED
@@ -0,0 +1,38 @@
1
+ import type { AnyNestedClient, InferClientContext, InferClientError, RPCJsonSerialization } from "@orpc/client";
2
+ import type { Public } from "@orpc/shared";
3
+ import type { RouterUtilsPlugin } from "./plugin.mjs";
4
+ import type { ProcedureUtilsOptions } from "./procedure-utils.mjs";
5
+ import { RPCJsonSerializer } from "@orpc/client";
6
+ /**
7
+ * Creates `dehydrate` and `hydrate` query client defaults that preserve oRPC types.
8
+ *
9
+ * @see {@link https://orpc.dev/docs/integrations/tanstack-query#custom-serializers | TanStack Query Integration - Custom Serializers}
10
+ */
11
+ export declare function createHydrationOptions(serializer?: Public<RPCJsonSerializer>): {
12
+ dehydrate: {
13
+ serializeData: (data: unknown) => RPCJsonSerialization;
14
+ };
15
+ hydrate: {
16
+ deserializeData: (data: RPCJsonSerialization) => unknown;
17
+ };
18
+ };
19
+ export interface StreamQuerySSRUtilsPluginOptions {
20
+ /**
21
+ * Whether utils run on the server, where streamed and live queries are cancelled once they have data.
22
+ * Defaults to `true` when there is no global `window`.
23
+ */
24
+ isServer?: boolean | undefined;
25
+ }
26
+ /**
27
+ * Router utils plugin for SSR of streamed and live queries. On the server, streamed queries are
28
+ * cancelled once they connect and live queries on their first event, keeping the data received so far;
29
+ * in the browser, they refetch on mount so streams reopen after hydration.
30
+ *
31
+ * @see {@link https://orpc.dev/docs/integrations/tanstack-query#streamed-and-live-queries | TanStack Query Integration - Streamed and Live Queries}
32
+ */
33
+ export declare class StreamQuerySSRUtilsPlugin<T extends AnyNestedClient = AnyNestedClient> implements RouterUtilsPlugin<T> {
34
+ readonly name = "~stream-query-ssr";
35
+ private readonly isServer;
36
+ constructor(options?: StreamQuerySSRUtilsPluginOptions);
37
+ initProcedureOptions(_path: string[], options: ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>): ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>;
38
+ }
package/dist/ssr.mjs ADDED
@@ -0,0 +1,57 @@
1
+ import { RPCJsonSerializer } from "@orpc/client";
2
+ import { mergeProcedureUtilsOptions } from "./procedure-utils.mjs";
3
+
4
+ export function createHydrationOptions(serializer = new RPCJsonSerializer()) {
5
+ return {
6
+ dehydrate: { serializeData(data) {
7
+ const { json, meta } = serializer.serializeJson(data);
8
+ return {
9
+ json,
10
+ meta
11
+ };
12
+ } },
13
+ hydrate: { deserializeData(data) {
14
+ return serializer.deserializeJson(data);
15
+ } }
16
+ };
17
+ }
18
+
19
+ const cancelOnFirstData = async ({ next, fnContext }) => {
20
+ const cache = fnContext.client.getQueryCache();
21
+ const query = cache.find({
22
+ queryKey: fnContext.queryKey,
23
+ exact: true
24
+ });
25
+ const unsubscribe = cache.subscribe((event) => {
26
+ if (event.query === query && event.type === "updated" && event.action.type === "success") {
27
+ unsubscribe();
28
+ void event.query.cancel({ revert: true });
29
+ }
30
+ });
31
+ try {
32
+ return await next();
33
+ } finally {
34
+ unsubscribe();
35
+ }
36
+ };
37
+
38
+ export class StreamQuerySSRUtilsPlugin {
39
+ name = "~stream-query-ssr";
40
+ isServer;
41
+ constructor(options = {}) {
42
+ this.isServer = options.isServer ?? !("window" in globalThis);
43
+ }
44
+ initProcedureOptions(_path, options) {
45
+ return mergeProcedureUtilsOptions({
46
+ ...this.isServer ? {
47
+ streamedInterceptors: [cancelOnFirstData],
48
+ liveInterceptors: [cancelOnFirstData]
49
+ } : {},
50
+ streamedOptions: {
51
+ initialData: [],
52
+ refetchOnMount: "always"
53
+ },
54
+ liveOptions: { refetchOnMount: "always" }
55
+ }, options);
56
+ }
57
+ }
@@ -0,0 +1,30 @@
1
+ import type { Promisable } from "@orpc/shared";
2
+ import type { QueryFunction, QueryFunctionContext, QueryKey } from "@tanstack/query-core";
3
+ export interface SerializableStreamedQueryOptions {
4
+ /**
5
+ * Determines how data is handled when the query is fetched again
6
+ *
7
+ * - `'reset'`: Clears existing data and returns the query to a pending state.
8
+ * - `'append'`: Adds new streamed chunks to the existing data.
9
+ * - `'replace'`: Buffers streamed data and replaces the cache after the stream completes.
10
+ *
11
+ * @default 'reset'
12
+ */
13
+ refetchMode?: "append" | "reset" | "replace" | undefined;
14
+ /**
15
+ * Limits the number of data chunks stored in the query result.
16
+ * Older chunks are removed when the limit is reached.
17
+ *
18
+ * @default Number.POSITIVE_INFINITY (unlimited)
19
+ */
20
+ maxChunks?: number | undefined;
21
+ }
22
+ /**
23
+ * A variant of `streamedQuery` where:
24
+ * - Options are serializable
25
+ * - The output is predictable
26
+ */
27
+ export declare function serializableStreamedQuery<
28
+ TQueryFnData = unknown,
29
+ TQueryKey extends QueryKey = QueryKey
30
+ >(queryFn: (context: QueryFunctionContext<TQueryKey>) => Promisable<AsyncIterable<TQueryFnData>>, { refetchMode, maxChunks }?: SerializableStreamedQueryOptions): QueryFunction<TQueryFnData[], TQueryKey>;