@orpc/pinia-colada 2.0.0-beta.49 → 2.0.0-beta.50

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.
@@ -1,59 +1,54 @@
1
- import type { AnyNestedClient, Client, InferClientContext, InferClientError } from '@orpc/client';
2
- import type { Public } from '@orpc/shared';
3
- import type { OperationKeyBaseOptions } from './key.ts';
4
- import type { RouterUtilsPlugin } from './plugin.ts';
5
- import type { ProcedureUtilsInfiniteInterceptor, ProcedureUtilsLiveInterceptor, ProcedureUtilsMutationInterceptor, ProcedureUtilsOptions, ProcedureUtilsQueryInterceptor, ProcedureUtilsStreamedInterceptor } from './procedure-utils.ts';
6
- import { ProcedureUtils } from './procedure-utils.ts';
7
- import { SharedUtils } from './shared-utils.ts';
1
+ import { OperationKeyBaseOptions } from "./key.js";
2
+ import { RouterUtilsPlugin } from "./plugin.js";
3
+ import { ProcedureUtils, ProcedureUtilsInfiniteInterceptor, ProcedureUtilsLiveInterceptor, ProcedureUtilsMutationInterceptor, ProcedureUtilsOptions, ProcedureUtilsQueryInterceptor, ProcedureUtilsStreamedInterceptor } from "./procedure-utils.js";
4
+ import { SharedUtils } from "./shared-utils.js";
5
+ import { Public } from "@orpc/shared";
6
+ import { AnyNestedClient, Client, InferClientContext, InferClientError } from "@orpc/client";
8
7
  /**
9
8
  * The utils shape derived from a client: procedure clients map to procedure
10
9
  * utils, and routers map recursively to nested utils.
11
10
  *
12
11
  * @see {@link https://orpc.dev/docs/integrations/pinia-colada | Pinia Colada Integration}
13
12
  */
14
- export type RouterUtils<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Public<ProcedureUtils<UClientContext, UInput, UOutput, UError>> : {
15
- [K in keyof T]: T[K] extends AnyNestedClient ? RouterUtils<T[K]> : never;
16
- } & Public<SharedUtils<unknown>>;
17
- export type RouterUtilsScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ProcedureUtilsOptions<UClientContext, UInput, UOutput, UError> : {
18
- [K in keyof T]?: (T[K] extends AnyNestedClient ? RouterUtilsScoped<T[K]> : never) | undefined;
19
- };
13
+ 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>>;
14
+ 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; };
20
15
  export interface RouterUtilsOptions<T extends AnyNestedClient> extends OperationKeyBaseOptions {
21
- /**
22
- * Base path for all query keys.
23
- *
24
- * @internal
25
- */
26
- path?: string[] | undefined;
27
- /**
28
- * Interceptors that intercept query inside .queryOptions
29
- */
30
- queryInterceptors?: ProcedureUtilsQueryInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
31
- /**
32
- * Interceptors that intercept query inside .streamedOptions
33
- */
34
- streamedInterceptors?: ProcedureUtilsStreamedInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
35
- /**
36
- * Interceptors that intercept query inside .liveOptions
37
- */
38
- liveInterceptors?: ProcedureUtilsLiveInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
39
- /**
40
- * Interceptors that intercept query inside .infiniteOptions
41
- */
42
- infiniteInterceptors?: ProcedureUtilsInfiniteInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
43
- /**
44
- * Interceptors that intercept mutation inside .mutationOptions
45
- */
46
- mutationInterceptors?: ProcedureUtilsMutationInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
47
- /**
48
- * Per-procedure options following the shape of the router.
49
- * Allows fine-grained configuration of individual procedure utils
50
- * without affecting the rest of the router.
51
- */
52
- scoped?: RouterUtilsScoped<T> | undefined;
53
- /**
54
- * Plugins to extend router utils behavior.
55
- */
56
- plugins?: RouterUtilsPlugin<T>[] | undefined;
16
+ /**
17
+ * Base path for all query keys.
18
+ *
19
+ * @internal
20
+ */
21
+ path?: string[] | undefined;
22
+ /**
23
+ * Interceptors that intercept query inside .queryOptions
24
+ */
25
+ queryInterceptors?: ProcedureUtilsQueryInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
26
+ /**
27
+ * Interceptors that intercept query inside .streamedOptions
28
+ */
29
+ streamedInterceptors?: ProcedureUtilsStreamedInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
30
+ /**
31
+ * Interceptors that intercept query inside .liveOptions
32
+ */
33
+ liveInterceptors?: ProcedureUtilsLiveInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
34
+ /**
35
+ * Interceptors that intercept query inside .infiniteOptions
36
+ */
37
+ infiniteInterceptors?: ProcedureUtilsInfiniteInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
38
+ /**
39
+ * Interceptors that intercept mutation inside .mutationOptions
40
+ */
41
+ mutationInterceptors?: ProcedureUtilsMutationInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
42
+ /**
43
+ * Per-procedure options following the shape of the router.
44
+ * Allows fine-grained configuration of individual procedure utils
45
+ * without affecting the rest of the router.
46
+ */
47
+ scoped?: RouterUtilsScoped<T> | undefined;
48
+ /**
49
+ * Plugins to extend router utils behavior.
50
+ */
51
+ plugins?: RouterUtilsPlugin<T>[] | undefined;
57
52
  }
58
53
  /**
59
54
  * Creates Pinia Colada utils from a client, exposing query/mutation
@@ -64,4 +59,4 @@ export interface RouterUtilsOptions<T extends AnyNestedClient> extends Operation
64
59
  *
65
60
  * @see {@link https://orpc.dev/docs/integrations/pinia-colada | Pinia Colada Integration}
66
61
  */
67
- export declare function createRouterUtils<T extends AnyNestedClient>(client: T, options?: NoInfer<RouterUtilsOptions<T>>): RouterUtils<T>;
62
+ export declare function createRouterUtils<T extends AnyNestedClient>(client: T, options?: NoInfer<RouterUtilsOptions<T>>): RouterUtils<T>;
@@ -1,69 +1,54 @@
1
- import { RECURSIVE_CLIENT_UNWRAP_KEYS } from '@orpc/client';
2
- import { bindMethods, isNonPrimitive, pick, toArray } from '@orpc/shared';
3
- import { CompositeRouterUtilsPlugin } from './plugin.js';
4
- import { isProcedureUtilsOptions, mergeProcedureUtilsOptions, ProcedureUtils, } from './procedure-utils.js';
5
- import { SharedUtils } from './shared-utils.js';
1
+ import { CompositeRouterUtilsPlugin } from "./plugin.js";
2
+ import { ProcedureUtils, isProcedureUtilsOptions, mergeProcedureUtilsOptions } from "./procedure-utils.js";
3
+ import { SharedUtils } from "./shared-utils.js";
4
+ import { bindMethods, isNonPrimitive, pick, toArray } from "@orpc/shared";
5
+ import { RECURSIVE_CLIENT_UNWRAP_KEYS } from "@orpc/client";
6
+ // src/router-utils.ts
6
7
  /**
7
- * Creates Pinia Colada utils from a client, exposing query/mutation
8
- * option builders for every procedure in the router.
9
- *
10
- * @remarks
11
- * **Note**: Both client-side and server-side clients are supported.
12
- *
13
- * @see {@link https://orpc.dev/docs/integrations/pinia-colada | Pinia Colada Integration}
14
- */
15
- export function createRouterUtils(client, options = {}) {
16
- const plugin = new CompositeRouterUtilsPlugin(options.plugins);
17
- options = plugin.init(options);
18
- return createRouterUtilsInternal(client, options, plugin);
8
+ * Creates Pinia Colada utils from a client, exposing query/mutation
9
+ * option builders for every procedure in the router.
10
+ *
11
+ * @remarks
12
+ * **Note**: Both client-side and server-side clients are supported.
13
+ *
14
+ * @see {@link https://orpc.dev/docs/integrations/pinia-colada | Pinia Colada Integration}
15
+ */
16
+ function createRouterUtils(client, options = {}) {
17
+ const plugin = new CompositeRouterUtilsPlugin(options.plugins);
18
+ options = plugin.init(options);
19
+ return createRouterUtilsInternal(client, options, plugin);
19
20
  }
20
21
  function createRouterUtilsInternal(client, options, plugin) {
21
- const path = toArray(options.path);
22
- const utils = typeof client === 'function' &&
23
- (options.scoped === undefined || isProcedureUtilsOptions(options.scoped))
24
- ? bindMethods(new ProcedureUtils(path, client, plugin.initProcedureOptions(path, mergeProcedureUtilsOptions(pick(options, [
25
- 'prefix',
26
- 'serializer',
27
- 'queryInterceptors',
28
- 'streamedInterceptors',
29
- 'liveInterceptors',
30
- 'infiniteInterceptors',
31
- 'mutationInterceptors',
32
- ]), options.scoped ?? {}))), { unbound: ['call'] })
33
- : bindMethods(new SharedUtils(path, options));
34
- const cache = new Map();
35
- const recursive = new Proxy(utils, {
36
- get(target, prop) {
37
- const value = Reflect.get(target, prop);
38
- if (RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
39
- return value ?? Reflect.get(Object.prototype, prop);
40
- }
41
- const nextClient = Reflect.get(client, prop);
42
- if (typeof prop !== 'string' || !isNonPrimitive(nextClient)) {
43
- return value;
44
- }
45
- let result = cache.get(prop);
46
- if (result === undefined) {
47
- const nextUtils = createRouterUtilsInternal(nextClient, {
48
- ...options,
49
- path: [...path, prop],
50
- scoped: options.scoped?.[prop],
51
- }, plugin);
52
- result =
53
- typeof value !== 'function'
54
- ? nextUtils
55
- : new Proxy(value, {
56
- get(target, prop) {
57
- if (typeof prop !== 'string' || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
58
- return Reflect.get(target, prop);
59
- }
60
- return Reflect.get(nextUtils, prop);
61
- },
62
- });
63
- cache.set(prop, result);
64
- }
65
- return result;
66
- },
67
- });
68
- return recursive;
22
+ const path = toArray(options.path);
23
+ const utils = typeof client === "function" && (options.scoped === void 0 || isProcedureUtilsOptions(options.scoped)) ? bindMethods(new ProcedureUtils(path, client, plugin.initProcedureOptions(path, mergeProcedureUtilsOptions(pick(options, [
24
+ "prefix",
25
+ "serializer",
26
+ "queryInterceptors",
27
+ "streamedInterceptors",
28
+ "liveInterceptors",
29
+ "infiniteInterceptors",
30
+ "mutationInterceptors"
31
+ ]), options.scoped ?? {}))), { unbound: ["call"] }) : bindMethods(new SharedUtils(path, options));
32
+ const cache = /* @__PURE__ */ new Map();
33
+ return new Proxy(utils, { get(target, prop) {
34
+ const value = Reflect.get(target, prop);
35
+ if (RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) return value ?? Reflect.get(Object.prototype, prop);
36
+ const nextClient = Reflect.get(client, prop);
37
+ if (typeof prop !== "string" || !isNonPrimitive(nextClient)) return value;
38
+ let result = cache.get(prop);
39
+ if (result === void 0) {
40
+ const nextUtils = createRouterUtilsInternal(nextClient, {
41
+ ...options,
42
+ path: [...path, prop],
43
+ scoped: options.scoped?.[prop]
44
+ }, plugin);
45
+ result = typeof value !== "function" ? nextUtils : new Proxy(value, { get(target, prop) {
46
+ if (typeof prop !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) return Reflect.get(target, prop);
47
+ return Reflect.get(nextUtils, prop);
48
+ } });
49
+ cache.set(prop, result);
50
+ }
51
+ return result;
52
+ } });
69
53
  }
54
+ export { createRouterUtils };
@@ -1,13 +1,13 @@
1
- import type { OperationKey, OperationKeyBaseOptions, OperationKeyOptions } from './key.ts';
2
- import type { OperationType } from './types.ts';
1
+ import { OperationKey, OperationKeyBaseOptions, OperationKeyOptions } from "./key.js";
2
+ import { OperationType } from "./types.js";
3
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
- * @see {@link https://orpc.dev/docs/integrations/pinia-colada#querymutation-key | Pinia Colada Integration - Query/Mutation Key}
11
- */
12
- key<TType extends OperationType>(options?: Omit<OperationKeyOptions<TType, TInput>, keyof OperationKeyBaseOptions>): OperationKey<TType, TInput>;
13
- }
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
+ * @see {@link https://orpc.dev/docs/integrations/pinia-colada#querymutation-key | Pinia Colada Integration - Query/Mutation Key}
11
+ */
12
+ key<TType extends OperationType>(options?: Omit<OperationKeyOptions<TType, TInput>, keyof OperationKeyBaseOptions>): OperationKey<TType, TInput>;
13
+ }
@@ -1,21 +1,23 @@
1
- import { generateOperationKey } from './key.js';
2
- export class SharedUtils {
3
- path;
4
- options;
5
- constructor(path, options) {
6
- this.path = path;
7
- this.options = options;
8
- }
9
- /**
10
- * Generate a **partial matching** key for actions like revalidating queries, checking mutation status, etc.
11
- *
12
- * @see {@link https://orpc.dev/docs/integrations/pinia-colada#querymutation-key | Pinia Colada Integration - Query/Mutation Key}
13
- */
14
- key(options = {}) {
15
- return generateOperationKey(this.path, {
16
- ...options,
17
- prefix: this.options.prefix,
18
- serializer: this.options.serializer,
19
- });
20
- }
21
- }
1
+ import { generateOperationKey } from "./key.js";
2
+ // src/shared-utils.ts
3
+ var SharedUtils = class {
4
+ path;
5
+ options;
6
+ constructor(path, options) {
7
+ this.path = path;
8
+ this.options = options;
9
+ }
10
+ /**
11
+ * Generate a **partial matching** key for actions like revalidating queries, checking mutation status, etc.
12
+ *
13
+ * @see {@link https://orpc.dev/docs/integrations/pinia-colada#querymutation-key | Pinia Colada Integration - Query/Mutation Key}
14
+ */
15
+ key(options = {}) {
16
+ return generateOperationKey(this.path, {
17
+ ...options,
18
+ prefix: this.options.prefix,
19
+ serializer: this.options.serializer
20
+ });
21
+ }
22
+ };
23
+ export { SharedUtils };
package/dist/ssr.d.ts CHANGED
@@ -1,12 +1,12 @@
1
- import type { AnyNestedClient, InferClientContext, InferClientError } from '@orpc/client';
2
- import type { RouterUtilsPlugin } from './plugin.ts';
3
- import type { ProcedureUtilsOptions } from './procedure-utils.ts';
1
+ import { RouterUtilsPlugin } from "./plugin.js";
2
+ import { ProcedureUtilsOptions } from "./procedure-utils.js";
3
+ import { AnyNestedClient, InferClientContext, InferClientError } from "@orpc/client";
4
4
  export interface StreamQuerySSRUtilsPluginOptions {
5
- /**
6
- * Whether utils run on the server, where streamed and live queries always settle at their first data.
7
- * Defaults to `true` when there is no global `window`, or in Deno.
8
- */
9
- isServer?: boolean | undefined;
5
+ /**
6
+ * Whether utils run on the server, where streamed and live queries always settle at their first data.
7
+ * Defaults to `true` when there is no global `window`, or in Deno.
8
+ */
9
+ isServer?: boolean | undefined;
10
10
  }
11
11
  /**
12
12
  * Router utils plugin for SSR of streamed and live queries: sets `settleOnFirstData: true` on the server,
@@ -15,8 +15,8 @@ export interface StreamQuerySSRUtilsPluginOptions {
15
15
  * @see {@link https://orpc.dev/docs/integrations/pinia-colada#streamed-and-live-queries-in-ssr | Pinia Colada Integration - Streamed and Live Queries in SSR}
16
16
  */
17
17
  export declare class StreamQuerySSRUtilsPlugin<T extends AnyNestedClient = AnyNestedClient> implements RouterUtilsPlugin<T> {
18
- readonly name = "~stream-query-ssr";
19
- private readonly defaults;
20
- constructor(options?: StreamQuerySSRUtilsPluginOptions);
21
- initProcedureOptions(_path: string[], options: ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>): ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>;
22
- }
18
+ readonly name = "~stream-query-ssr";
19
+ private readonly defaults;
20
+ constructor(options?: StreamQuerySSRUtilsPluginOptions);
21
+ initProcedureOptions(_path: string[], options: ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>): ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>;
22
+ }
package/dist/ssr.js CHANGED
@@ -1,24 +1,22 @@
1
- import { mergeProcedureUtilsOptions } from './procedure-utils.js';
1
+ import { mergeProcedureUtilsOptions } from "./procedure-utils.js";
2
+ // src/ssr.ts
2
3
  /**
3
- * Router utils plugin for SSR of streamed and live queries: sets `settleOnFirstData: true` on the server,
4
- * and `staleTime: 0` in the browser, so hydrated data is stale and its stream reopens when a component mounts.
5
- *
6
- * @see {@link https://orpc.dev/docs/integrations/pinia-colada#streamed-and-live-queries-in-ssr | Pinia Colada Integration - Streamed and Live Queries in SSR}
7
- */
8
- export class StreamQuerySSRUtilsPlugin {
9
- name = '~stream-query-ssr';
10
- defaults;
11
- constructor(options = {}) {
12
- // the server always settles, even when observed, and keeps the staleTime so components sharing a query do not reopen it
13
- this.defaults =
14
- (options.isServer ?? (!('window' in globalThis) || 'Deno' in globalThis))
15
- ? { settleOnFirstData: true }
16
- : { staleTime: 0 };
17
- }
18
- initProcedureOptions(_path, options) {
19
- return mergeProcedureUtilsOptions({
20
- streamedOptions: this.defaults,
21
- liveOptions: this.defaults,
22
- }, options);
23
- }
24
- }
4
+ * Router utils plugin for SSR of streamed and live queries: sets `settleOnFirstData: true` on the server,
5
+ * and `staleTime: 0` in the browser, so hydrated data is stale and its stream reopens when a component mounts.
6
+ *
7
+ * @see {@link https://orpc.dev/docs/integrations/pinia-colada#streamed-and-live-queries-in-ssr | Pinia Colada Integration - Streamed and Live Queries in SSR}
8
+ */
9
+ var StreamQuerySSRUtilsPlugin = class {
10
+ name = "~stream-query-ssr";
11
+ defaults;
12
+ constructor(options = {}) {
13
+ this.defaults = options.isServer ?? (!("window" in globalThis) || "Deno" in globalThis) ? { settleOnFirstData: true } : { staleTime: 0 };
14
+ }
15
+ initProcedureOptions(_path, options) {
16
+ return mergeProcedureUtilsOptions({
17
+ streamedOptions: this.defaults,
18
+ liveOptions: this.defaults
19
+ }, options);
20
+ }
21
+ };
22
+ export { StreamQuerySSRUtilsPlugin };
@@ -1,42 +1,33 @@
1
- import type { Promisable } from '@orpc/shared';
2
- import type { UseQueryFnContext } from './types.ts';
1
+ import "./types.js";
2
+ import "@orpc/shared";
3
3
  export interface SerializableStreamedQueryOptions {
4
- /**
5
- * What a fetch does with existing data once its stream connects.
6
- * Until then the data stays, so an entry with data never returns to `pending`.
7
- *
8
- * - `'reset'`: the data becomes `[]`, then each chunk is appended.
9
- * - `'append'`: the data is kept (trimmed to `maxChunks`), and each chunk is appended.
10
- *
11
- * @default 'reset'
12
- */
13
- refetchMode?: 'append' | 'reset' | 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;
4
+ /**
5
+ * What a fetch does with existing data once its stream connects.
6
+ * Until then the data stays, so an entry with data never returns to `pending`.
7
+ *
8
+ * - `'reset'`: the data becomes `[]`, then each chunk is appended.
9
+ * - `'append'`: the data is kept (trimmed to `maxChunks`), and each chunk is appended.
10
+ *
11
+ * @default 'reset'
12
+ */
13
+ refetchMode?: "append" | "reset" | 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
21
  }
22
22
  export interface SettleOnFirstDataOptions {
23
- /**
24
- * Settles the fetch at its first data (streamed: when the stream connects; live: on the first event)
25
- * instead of following the stream to its end. The stream is closed and the data kept.
26
- * The stream reopens on mount only once the entry is stale (e.g. with `staleTime: 0`, as `StreamQuerySSRUtilsPlugin` sets in the browser).
27
- * Use it only where nothing watches the stream, such as server rendering:
28
- * a refetch while a component uses the query would also settle, closing its stream.
29
- *
30
- * @default false
31
- */
32
- settleOnFirstData?: boolean | undefined;
33
- }
34
- /**
35
- * A Pinia Colada query function that accumulates streamed chunks into an array,
36
- * publishing each chunk to the cache entry as it arrives.
37
- *
38
- * Inspired by [TanStack Query streamedQuery](https://tanstack.com/query/latest/docs/reference/streamedQuery) where:
39
- * - Options are serializable
40
- * - The output is predictable
41
- */
42
- export declare function serializableStreamedQuery<T>(queryFn: (context: UseQueryFnContext) => Promisable<AsyncIterable<T>>, { refetchMode, maxChunks, settleOnFirstData, }?: SerializableStreamedQueryOptions & SettleOnFirstDataOptions): (context: UseQueryFnContext) => Promise<T[]>;
23
+ /**
24
+ * Settles the fetch at its first data (streamed: when the stream connects; live: on the first event)
25
+ * instead of following the stream to its end. The stream is closed and the data kept.
26
+ * The stream reopens on mount only once the entry is stale (e.g. with `staleTime: 0`, as `StreamQuerySSRUtilsPlugin` sets in the browser).
27
+ * Use it only where nothing watches the stream, such as server rendering:
28
+ * a refetch while a component uses the query would also settle, closing its stream.
29
+ *
30
+ * @default false
31
+ */
32
+ settleOnFirstData?: boolean | undefined;
33
+ }
@@ -1,59 +1,47 @@
1
- import { throwIfAborted } from '@orpc/shared';
1
+ import { listenAbort, takeLast, throwIfAborted } from "@orpc/shared";
2
+ // src/stream-query.ts
2
3
  /**
3
- * A Pinia Colada query function that accumulates streamed chunks into an array,
4
- * publishing each chunk to the cache entry as it arrives.
5
- *
6
- * Inspired by [TanStack Query streamedQuery](https://tanstack.com/query/latest/docs/reference/streamedQuery) where:
7
- * - Options are serializable
8
- * - The output is predictable
9
- */
10
- export function serializableStreamedQuery(queryFn, { refetchMode = 'reset', maxChunks = Number.POSITIVE_INFINITY, settleOnFirstData = false, } = {}) {
11
- return async (context) => {
12
- const { entry, signal } = context;
13
- const write = (data) => {
14
- entry.state.value = { status: 'success', data, error: null };
15
- return data;
16
- };
17
- // a fetch cut short (cancelled, superseded, or its last component left) reopens when used again
18
- const markStale = () => {
19
- entry.when = 0;
20
- };
21
- if (signal.aborted) {
22
- markStale();
23
- }
24
- signal.addEventListener('abort', markStale, { once: true });
25
- const stream = await queryFn(context);
26
- // close without reading, so a generator the query no longer wants never starts
27
- if (signal.aborted) {
28
- await stream[Symbol.asyncIterator]().return?.();
29
- throw signal.reason;
30
- }
31
- const current = entry.state.value.data;
32
- let data = write(refetchMode === 'append' && current ? limitArraySize(current, maxChunks) : []);
33
- if (settleOnFirstData) {
34
- await stream[Symbol.asyncIterator]().return?.();
35
- return data;
36
- }
37
- for await (const chunk of stream) {
38
- throwIfAborted(signal);
39
- // read the entry, so writes made during the stream are kept
40
- const current = entry.state.value.data ?? [];
41
- data = write(limitArraySize([...current, chunk], maxChunks));
42
- }
43
- // a stream that ends on abort must not be stored as fresh data
44
- throwIfAborted(signal);
45
- // Colada writes the returned data again, so return the entry data to keep later writes
46
- const cached = entry.state.value.data;
47
- if (cached === undefined) {
48
- return data;
49
- }
50
- // only an array is trimmed; another value written after the stream (e.g. `null`) is kept as is
51
- return Array.isArray(cached) ? limitArraySize(cached, maxChunks) : cached;
52
- };
53
- }
54
- function limitArraySize(items, maxSize) {
55
- if (items.length <= maxSize) {
56
- return items;
57
- }
58
- return items.slice(items.length - maxSize);
4
+ * A Pinia Colada query function that accumulates streamed chunks into an array,
5
+ * publishing each chunk to the cache entry as it arrives.
6
+ *
7
+ * Inspired by [TanStack Query streamedQuery](https://tanstack.com/query/latest/docs/reference/streamedQuery) where:
8
+ * - Options are serializable
9
+ * - The output is predictable
10
+ */
11
+ function serializableStreamedQuery(queryFn, { refetchMode = "reset", maxChunks = Number.POSITIVE_INFINITY, settleOnFirstData = false } = {}) {
12
+ return async (context) => {
13
+ const { entry, signal } = context;
14
+ const write = (data) => {
15
+ entry.state.value = {
16
+ status: "success",
17
+ data,
18
+ error: null
19
+ };
20
+ return data;
21
+ };
22
+ listenAbort(signal, () => {
23
+ entry.when = 0;
24
+ });
25
+ const stream = await queryFn(context);
26
+ if (signal.aborted) {
27
+ await stream[Symbol.asyncIterator]().return?.();
28
+ throw signal.reason;
29
+ }
30
+ const current = entry.state.value.data;
31
+ let data = write(refetchMode === "append" && current ? takeLast(current, maxChunks) : []);
32
+ if (settleOnFirstData) {
33
+ await stream[Symbol.asyncIterator]().return?.();
34
+ return data;
35
+ }
36
+ for await (const chunk of stream) {
37
+ throwIfAborted(signal);
38
+ const current = entry.state.value.data ?? [];
39
+ data = write(takeLast([...current, chunk], maxChunks));
40
+ }
41
+ throwIfAborted(signal);
42
+ const cached = entry.state.value.data;
43
+ if (cached === void 0) return data;
44
+ return Array.isArray(cached) ? takeLast(cached, maxChunks) : cached;
45
+ };
59
46
  }
47
+ export { serializableStreamedQuery };