@raf-query/core 0.11.1 → 0.13.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 (73) hide show
  1. package/CHANGELOG.md +39 -1
  2. package/README.md +28 -18
  3. package/dist/client.d.mts +163 -119
  4. package/dist/client.mjs +90 -162
  5. package/dist/entry.d.mts +73 -147
  6. package/dist/entry.mjs +314 -471
  7. package/dist/features/focus-refetch/focus-refetch.d.mts +17 -0
  8. package/dist/features/focus-refetch/focus-refetch.mjs +20 -0
  9. package/dist/features/polling/polling.d.mts +16 -0
  10. package/dist/features/polling/polling.mjs +39 -0
  11. package/dist/features/reconnect-refetch/reconnect-refetch.d.mts +17 -0
  12. package/dist/features/reconnect-refetch/reconnect-refetch.mjs +16 -0
  13. package/dist/features/shared.mjs +13 -0
  14. package/dist/guards.mjs +23 -0
  15. package/dist/hydration/hydration.d.mts +108 -0
  16. package/dist/hydration/hydration.mjs +142 -0
  17. package/dist/index.d.mts +19 -13
  18. package/dist/index.mjs +16 -13
  19. package/dist/infinite/infinite.d.mts +83 -0
  20. package/dist/infinite/infinite.mjs +120 -0
  21. package/dist/infinite/paging.d.mts +71 -0
  22. package/dist/infinite/paging.mjs +62 -0
  23. package/dist/internal.d.mts +13 -0
  24. package/dist/internal.mjs +7 -0
  25. package/dist/keys/keys.d.mts +54 -0
  26. package/dist/keys/keys.mjs +53 -0
  27. package/dist/keys/targets.d.mts +62 -0
  28. package/dist/keys/targets.mjs +85 -0
  29. package/dist/links/retry/retry.d.mts +33 -0
  30. package/dist/links/retry/retry.mjs +53 -0
  31. package/dist/links/timeout/timeout.d.mts +17 -0
  32. package/dist/links/timeout/timeout.mjs +35 -0
  33. package/dist/load.d.mts +149 -0
  34. package/dist/load.mjs +179 -0
  35. package/dist/options.d.mts +161 -332
  36. package/dist/options.mjs +28 -40
  37. package/dist/presets.d.mts +35 -0
  38. package/dist/presets.mjs +27 -0
  39. package/dist/root.d.mts +86 -0
  40. package/dist/structural-sharing/structural-sharing.mjs +32 -0
  41. package/dist/subscribe.d.mts +15 -0
  42. package/dist/subscribe.mjs +29 -0
  43. package/dist/thenable.d.mts +15 -17
  44. package/dist/thenable.mjs +25 -6
  45. package/dist/verbs.d.mts +150 -0
  46. package/dist/verbs.mjs +115 -0
  47. package/package.json +13 -9
  48. package/dist/_virtual/_rolldown/runtime.mjs +0 -13
  49. package/dist/all-keyed.d.mts +0 -18
  50. package/dist/all-keyed.mjs +0 -19
  51. package/dist/binding.d.mts +0 -92
  52. package/dist/binding.mjs +0 -186
  53. package/dist/cache.d.mts +0 -164
  54. package/dist/cache.mjs +0 -184
  55. package/dist/controls.d.mts +0 -95
  56. package/dist/controls.mjs +0 -70
  57. package/dist/hydration.d.mts +0 -84
  58. package/dist/hydration.mjs +0 -148
  59. package/dist/infinite.d.mts +0 -5
  60. package/dist/infinite.mjs +0 -103
  61. package/dist/key.d.mts +0 -18
  62. package/dist/key.mjs +0 -36
  63. package/dist/listen.mjs +0 -19
  64. package/dist/notify.mjs +0 -21
  65. package/dist/observer.d.mts +0 -110
  66. package/dist/observer.mjs +0 -300
  67. package/dist/platform.d.mts +0 -27
  68. package/dist/platform.mjs +0 -44
  69. package/dist/query.d.mts +0 -137
  70. package/dist/query.mjs +0 -147
  71. package/dist/request.mjs +0 -47
  72. package/dist/retry.mjs +0 -25
  73. package/dist/share.mjs +0 -40
@@ -1,374 +1,203 @@
1
- import { QueryKey } from "./key.mjs";
2
- import { Effect, Schedule } from "effect";
1
+ import { QueryKey } from "./keys/keys.mjs";
2
+ import { AnyRoot, DefaultTypes, RootOf, RootTag, RootTypes } from "./root.mjs";
3
+ import { QueryClient } from "./client.mjs";
3
4
  //#region src/options.d.ts
4
5
  /**
5
- * The types of a plain query: what its `queryFn` resolves to, for an Effect
6
- * `queryFn` its error and the services it needs, and the shape of its key.
7
- * Leave `error` out and it is `unknown` (promises reject with anything);
8
- * leave `services` out and it is `never`; leave `key` out and it is any
9
- * {@link QueryKey}. `throwOnError` is the query's `throwOnError` option;
10
- * leave it out when the query doesn't set one.
6
+ * What a `queryFn` gets: the client making the request, the query's key,
7
+ * `meta` and abort `signal`.
11
8
  *
12
- * ```ts
13
- * type PostOptions = QueryOptions<{ data: Post }>;
14
- * ```
15
- */
16
- export interface QueryTypes {
17
- readonly data: unknown;
18
- readonly error?: unknown;
19
- readonly key?: QueryKey;
20
- readonly services?: unknown;
21
- readonly throwOnError?: boolean;
22
- }
23
- /**
24
- * The types of a paged query: one page, the param that loads it, and as in
25
- * {@link QueryTypes}, an Effect `queryFn`'s error and services, the key and
26
- * `throwOnError`.
27
- */
28
- export interface InfiniteQueryTypes {
29
- readonly error?: unknown;
30
- readonly key?: QueryKey;
31
- readonly page: unknown;
32
- readonly pageParam: unknown;
33
- readonly services?: unknown;
34
- readonly throwOnError?: boolean;
35
- }
36
- /** `error` of a types bag, `unknown` when it has none. */
37
- type ErrorIn<TTypes> = TTypes extends {
38
- readonly error: infer TError;
39
- } ? TError : unknown;
40
- /** `services` of a types bag, `never` when it has none. */
41
- type ServicesIn<TTypes> = TTypes extends {
42
- readonly services: infer TServices;
43
- } ? TServices : never;
44
- /** `key` of a types bag, any {@link QueryKey} when it has none. */
45
- type KeyIn<TTypes> = TTypes extends {
46
- readonly key: infer TKey extends QueryKey;
47
- } ? TKey : QueryKey;
48
- /** `throwOnError` of a types bag, `undefined` when it has none. */
49
- type ThrowIn<TTypes> = TTypes extends {
50
- readonly throwOnError: infer TThrow extends boolean;
51
- } ? TThrow : undefined;
52
- /** One object type for an intersection, so bags read as written. */
53
- type Flat<T> = { [K in keyof T]: T[K]; };
54
- type ErrorPart<TError> = unknown extends TError ? unknown : {
55
- error: TError;
56
- };
57
- type ServicesPart<TServices> = [TServices] extends [never] ? unknown : {
58
- services: TServices;
59
- };
60
- type ThrowPart<TThrow> = [TThrow] extends [boolean] ? {
61
- throwOnError: TThrow;
62
- } : unknown;
63
- /**
64
- * The bag `queryOptions` returns. `error` is left out when the `queryFn`
65
- * doesn't name one (`unknown`: a promise or a plain value). `services` is
66
- * left out when the `queryFn` needs none (`never`). An Effect's error,
67
- * including `never` when it can't fail, stays. `key` is always there, so two
68
- * factories with different key shapes have different types. `throwOnError`
69
- * is there when the options set it.
70
- */
71
- type QueryTypesOf<TData, TError, TServices, TKey, TThrow> = Flat<{
72
- data: TData;
73
- key: TKey;
74
- } & ErrorPart<TError> & ServicesPart<TServices> & ThrowPart<TThrow>>;
75
- /** As {@link QueryTypesOf}, for a paged query. */
76
- type InfiniteQueryTypesOf<TPage, TPageParam, TError, TServices, TKey, TThrow> = Flat<{
77
- key: TKey;
78
- page: TPage;
79
- pageParam: TPageParam;
80
- } & ErrorPart<TError> & ServicesPart<TServices> & ThrowPart<TThrow>>;
81
- /**
82
- * What a `queryFn` may return: a value, a promise, or an `Effect`. An
83
- * Effect's error type becomes the query's (promises reject with `unknown`),
84
- * and the services it needs become requirements of the verbs that start it.
9
+ * @see https://raf-query.katt.dev/docs/query-functions#the-query-function-context
85
10
  */
86
- export type QueryFnResult<TTypes extends QueryTypes> = TTypes["data"] | PromiseLike<TTypes["data"]> | Effect.Effect<TTypes["data"], ErrorIn<TTypes>, ServicesIn<TTypes>>;
87
- /**
88
- * App-wide types, filled in by module augmentation. Declare `queryMeta` to
89
- * type every query's `meta`. Augment the package you import from;
90
- * `@raf-query/react` re-exports this interface, so either works:
91
- *
92
- * ```ts
93
- * declare module "@raf-query/react" {
94
- * interface Register {
95
- * queryMeta: { errorMessage?: string };
96
- * }
97
- * }
98
- * ```
99
- */
100
- export interface Register {}
101
- /**
102
- * Type of a query's `meta`. `Record<string, unknown>` unless `queryMeta` is
103
- * declared on {@link Register}.
104
- */
105
- export type QueryMeta = Register extends {
106
- queryMeta: infer TQueryMeta;
107
- } ? TQueryMeta : Record<string, unknown>;
108
- export interface QueryFunctionContext {
109
- /** The query's `meta` when this request started ({@link QueryBehavior.meta}). */
110
- readonly meta: QueryMeta | undefined;
111
- /** The query's key, as returned by the factory. */
112
- readonly queryKey: QueryKey;
113
- /** Aborted when the request is cancelled or superseded. */
114
- readonly signal: AbortSignal;
115
- }
116
- export interface PageFunctionContext<TPageParam> extends QueryFunctionContext {
117
- /** Which end of the list this page is being added to. */
118
- readonly direction: "backward" | "forward";
119
- readonly pageParam: TPageParam;
120
- }
121
- /**
122
- * How many times to retry a failed request: `false`, `true` (forever), a
123
- * count, a predicate, or an Effect `Schedule`. The predicate gets the number
124
- * of failures so far (1 after the first).
125
- */
126
- export type RetryPolicy = boolean | number | Schedule.Schedule<unknown, unknown> | ((failureCount: number, error: unknown) => boolean);
127
- /** Options every query accepts. `QueryCache` defaults fill in the rest. */
128
- export interface QueryBehavior {
11
+ export interface QueryFunctionContext<TKey extends QueryKey = QueryKey> {
129
12
  /**
130
- * `false` keeps the query from running. Default `true`. The factory
131
- * decides per call, so `enabled: typeof window !== "undefined"` runs a
132
- * query only in the browser, for data only a browser has (permissions,
133
- * device APIs, `localStorage`).
134
- *
135
- * While disabled, readers see `isPending`, `ensure` and `fetch` fail with
136
- * `Query.DisabledError`, and `invalidate`, `reset` and `refetch` do
137
- * nothing. In the browser, its promise stays pending until a factory
138
- * call returns `true` and runs it. A server cache never sends it, and its
139
- * promise rejects with `Query.DisabledError`: under Suspense, React
140
- * renders the fallback on the server and the component in the browser.
13
+ * The client making the request. A server makes one per request, so it
14
+ * keys per-request services, such as an API client with the request's
15
+ * cookies.
141
16
  */
142
- readonly enabled?: boolean;
143
- /** How long an unread entry stays cached, in ms. `Infinity` keeps it. */
17
+ readonly client: QueryClient;
18
+ /** The query's `meta`, typed by its root where the query is defined. */
19
+ readonly meta: object;
20
+ readonly queryKey: TKey;
21
+ /** Aborted when the request is restarted or its entry is removed. */
22
+ readonly signal: AbortSignal;
23
+ }
24
+ declare const dataTag: unique symbol;
25
+ declare const queryFnDataTag: unique symbol;
26
+ /** Options every query takes. */
27
+ export interface BaseOptions<TKey extends QueryKey, TTypes extends RootTypes = RootTypes> {
28
+ /** How long an entry with no reader stays cached. Default 5 minutes; never on the server. */
144
29
  readonly gcTime?: number;
145
30
  /**
146
- * Anything to know about the query elsewhere: the `queryFn` context,
147
- * `Query.metaUnsafe(query)` (e.g. in the client's `onError`), devtools. A
148
- * query's own `meta` replaces the default's as a whole.
31
+ * Settings for the root's links and features, and data for targets: the
32
+ * fields the root's parts declare, such as `retry` with the `retry()`
33
+ * link.
149
34
  */
150
- readonly meta?: QueryMeta;
151
- /** Refetch read, stale queries when the browser comes back online. */
152
- readonly refetchOnReconnect?: boolean;
153
- /** Refetch read, stale queries when the window regains focus. */
154
- readonly refetchOnWindowFocus?: boolean;
155
- /** Retries after a failed request. */
156
- readonly retry?: RetryPolicy;
157
- /** Delay before retry number `failureCount` (1-based), in ms. */
158
- readonly retryDelay?: number | ((failureCount: number, error: unknown) => number);
159
- /** How long data counts as fresh, in ms. Fresh data is never refetched. */
160
- readonly staleTime?: number;
35
+ readonly meta?: NoInfer<Partial<TTypes["meta"]>>;
36
+ /** A plain array, usually built by a `group()`. Handles keep its literal type. */
37
+ readonly queryKey: TKey;
161
38
  /**
162
- * Keep the parts of new data that are deeply equal to the old data, so
163
- * unchanged objects keep their identity and unchanged data keeps its
164
- * promise. Compares plain objects and arrays. Default `true`.
39
+ * `false` for a query only a browser can run (a permission, the service
40
+ * worker, `localStorage`): a server client never starts it, never sends
41
+ * it, and reads it as not loaded yet, so the browser runs it once it
42
+ * renders. Default `true`.
43
+ *
44
+ * @see https://raf-query.katt.dev/docs/ssr-and-hydration#browser-only-queries
165
45
  */
46
+ readonly ssr?: boolean;
47
+ /** How long data stays fresh, in ms. Default `0`. */
48
+ readonly staleTime?: number;
49
+ /** Keep the deeply equal parts of new data, so they keep their identity. Default `true`. */
166
50
  readonly structuralSharing?: boolean;
167
51
  }
168
- declare const servicesType: unique symbol;
169
- interface ServicesField<TServices> {
170
- /**
171
- * Type-only: the services the `queryFn`'s Effect needs. Never present at
172
- * runtime. A `queryFn`'s return type can't carry them on its own: with
173
- * `unknown` data, any return type is assignable to `QueryFnResult`.
174
- */
175
- readonly [servicesType]?: () => TServices;
176
- }
177
- interface ThrowOnErrorField<TThrow> {
52
+ /**
53
+ * What `queryOptions` and `infiniteQueryOptions` return.
54
+ *
55
+ * @see https://raf-query.katt.dev/docs/api-reference#query-factories
56
+ */
57
+ export interface QueryOptions<TKey extends QueryKey = QueryKey, TQueryFnData = unknown, TData = TQueryFnData, TTypes extends RootTypes = RootTypes> extends BaseOptions<TKey, TTypes> {
58
+ /** Phantom: the root the builder is bound to. Never set at runtime. */
59
+ readonly "~root"?: RootTag<TTypes>;
60
+ /** Set by `infiniteQueryOptions`: runs the request page by page. */
61
+ readonly "~run"?: (op: never) => Promise<unknown>;
62
+ readonly [dataTag]?: TData;
63
+ readonly queryFn: (context: never) => unknown;
178
64
  /**
179
- * How reads of this query settle on failure when they don't set
180
- * `throwOnError` themselves: `true` rejects (to an error boundary),
181
- * `false` settles with a `Result`. Omit it for the client's default.
182
- * Only an Effect `queryFn`'s typed error reads as a `Result`; a promise
183
- * `queryFn` always rejects.
65
+ * Phantom: the `queryFn`'s data, before `select`. What `setData` writes,
66
+ * read from a property rather than `select`'s parameter, so a factory
67
+ * built inline by a generic maker still infers where it's passed.
184
68
  */
185
- readonly throwOnError?: TThrow;
186
- }
187
- export interface QueryOptions<TTypes extends QueryTypes> extends QueryBehavior, ServicesField<ServicesIn<TTypes>>, ThrowOnErrorField<ThrowIn<TTypes>> {
188
- readonly kind: "query";
189
- queryFn(context: QueryFunctionContext): QueryFnResult<TTypes>;
190
- readonly queryKey: KeyIn<TTypes>;
69
+ readonly [queryFnDataTag]?: TQueryFnData;
70
+ readonly select?: (data: TQueryFnData) => TData;
71
+ readonly stream?: StreamOptions<TQueryFnData, never>;
191
72
  }
192
73
  /**
193
- * The functions of paged options, typed by the page and page param types
194
- * themselves. Typed through the bag, inference breaks: TypeScript fixes
195
- * every type parameter a contextually typed parameter's type mentions, so
196
- * `context` would fix the page type before `queryFn`'s return could infer it.
74
+ * How a `queryFn` that returns an async iterable folds its chunks into data.
75
+ *
76
+ * @see https://raf-query.katt.dev/docs/query-functions#streaming
197
77
  */
198
- interface PageFunctions<TPage, TPageParam, TResult> {
199
- /** Param for the page after `lastPage`, or `null` / `undefined` at the end. */
200
- getNextPageParam(lastPage: TPage, pages: ReadonlyArray<TPage>, lastPageParam: TPageParam, pageParams: ReadonlyArray<TPageParam>): TPageParam | null | undefined;
201
- /** Param for the page before `firstPage`, or `null` / `undefined` at the start. */
202
- getPreviousPageParam?(firstPage: TPage, pages: ReadonlyArray<TPage>, firstPageParam: TPageParam, pageParams: ReadonlyArray<TPageParam>): TPageParam | null | undefined;
203
- queryFn(context: PageFunctionContext<TPageParam>): TResult;
78
+ export interface StreamOptions<TData, TChunk> {
79
+ /** The data before the first chunk. */
80
+ readonly initial: TData;
81
+ /** Fold a chunk into the data. */
82
+ readonly reduce: (data: TData, chunk: TChunk) => TData;
204
83
  }
205
- export interface InfiniteQueryOptions<TTypes extends InfiniteQueryTypes> extends PageFunctions<TTypes["page"], TTypes["pageParam"], QueryFnResult<{
206
- data: TTypes["page"];
207
- error: ErrorIn<TTypes>;
208
- services: ServicesIn<TTypes>;
209
- }>>, QueryBehavior, ServicesField<ServicesIn<TTypes>>, ThrowOnErrorField<ThrowIn<TTypes>> {
210
- readonly initialPageParam: TTypes["pageParam"];
211
- readonly kind: "infinite";
212
- /** Keep at most this many pages; the far end is dropped when paging. */
213
- readonly maxPages?: number;
214
- readonly queryKey: KeyIn<TTypes>;
215
- }
216
- /** Data of a paged query. */
217
- export interface InfiniteData<TTypes extends Pick<InfiniteQueryTypes, "page" | "pageParam">> {
218
- readonly pageParams: ReadonlyArray<TTypes["pageParam"]>;
219
- readonly pages: ReadonlyArray<TTypes["page"]>;
84
+ type Awaitable<T> = PromiseLike<T> | T;
85
+ /**
86
+ * `T` as a conditional type, so a builder infers its data type from the
87
+ * `queryFn` alone: an annotated `select` or `getNextPageParam` parameter
88
+ * doesn't widen it.
89
+ */
90
+ export type FromQueryFn<T> = T extends unknown ? T : never;
91
+ /**
92
+ * `queryOptions`, with `meta` checked against the root `TTypes`.
93
+ *
94
+ * @see https://raf-query.katt.dev/docs/links-and-features#typing-meta-by-its-root
95
+ */
96
+ export interface QueryOptionsBuilder<TTypes extends RootTypes> {
97
+ <const TKey extends QueryKey, TChunk, TData>(options: BaseOptions<TKey, TTypes> & {
98
+ readonly queryFn: (context: QueryFunctionContext<TKey>) => AsyncIterable<TChunk>;
99
+ readonly stream: StreamOptions<TData, TChunk>;
100
+ }): QueryOptions<TKey, TData, TData, TTypes>;
101
+ <const TKey extends QueryKey, TQueryFnData, TData = TQueryFnData>(options: BaseOptions<TKey, TTypes> & {
102
+ readonly queryFn: (context: QueryFunctionContext<TKey>) => Awaitable<TQueryFnData>;
103
+ readonly select?: (data: FromQueryFn<TQueryFnData>) => TData;
104
+ }): QueryOptions<TKey, TQueryFnData, TData, TTypes>;
220
105
  }
221
- export type AnyQueryOptions = QueryOptions<{
222
- data: unknown;
223
- error: unknown;
224
- services: unknown;
225
- throwOnError: boolean;
226
- }> | InfiniteQueryOptions<{
227
- error: unknown;
228
- page: unknown;
229
- pageParam: unknown;
230
- services: unknown;
231
- throwOnError: boolean;
232
- }>;
233
106
  /**
234
107
  * Typed options for a query factory:
235
108
  *
236
109
  * ```ts
237
- * export function postQuery(input: { slug: string }) {
238
- * return queryOptions({
239
- * queryKey: ["post", input.slug],
240
- * queryFn: () => getPost(input),
110
+ * export const postQuery = (input: { slug: string }) =>
111
+ * queryOptions({
112
+ * queryKey: posts(input.slug),
113
+ * queryFn: ({ signal }) => getPost(input.slug, { signal }),
241
114
  * });
242
- * }
243
115
  * ```
244
116
  *
245
- * A `queryFn` Effect may need services; they're inferred, and every verb
246
- * that can start the query requires them. Its error is part of the returned
247
- * type. A promise or a plain value has no error to infer, so the type leaves
248
- * `error` out (`ErrorOf` is `unknown`).
249
- *
250
- * The key's literal type is kept too (`readonly ["post", string]`), so two
251
- * factories with the same input and data but different keys have different
252
- * types, and a handle of one doesn't type-check where the other's goes.
117
+ * A `queryFn` that returns an async iterable is a stream: pass `stream` to
118
+ * fold its chunks into the data. Readers get the data after the first chunk,
119
+ * and every later chunk updates it in place.
253
120
  *
254
- * `throwOnError: true` or `false` is kept as a literal too, so reads that
255
- * don't set their own follow it in their types.
121
+ * Its `meta` is any record. To check `meta` against a client's links and
122
+ * features, use the builder {@link bindQueryOptions} returns.
256
123
  *
257
- * The type parameters are only there for TypeScript to infer the types bag
258
- * from `queryFn`, `queryKey` and `throwOnError`; it can't infer a bag's
259
- * members. Passing them explicitly, pass `TThrow` too when setting
260
- * `throwOnError`.
124
+ * @see https://raf-query.katt.dev/docs/query-factories
261
125
  */
262
- export declare function queryOptions<TData, TError = unknown, TServices = never, const TKey extends QueryKey = QueryKey, TThrow extends boolean | undefined = undefined>(options: Omit<QueryOptions<{
263
- data: TData;
264
- error: TError;
265
- key: TKey;
266
- services: TServices;
267
- }>, "kind" | "throwOnError"> & ThrowOnErrorField<TThrow>): QueryOptions<QueryTypesOf<TData, TError, TServices, TKey, TThrow>>;
126
+ export declare const queryOptions: QueryOptionsBuilder<DefaultTypes>;
268
127
  /**
269
- * Typed options for a paged query factory. The page type is inferred from
270
- * `queryFn`, as in {@link queryOptions}. So is an Effect `queryFn`'s error;
271
- * a promise or a plain value leaves `error` out. The key's literal type is
272
- * kept, as in {@link queryOptions}.
273
- */
274
- export declare function infiniteQueryOptions<TPage, TPageParam, TError = unknown, TServices = never, const TKey extends QueryKey = QueryKey, TThrow extends boolean | undefined = undefined>(options: Omit<InfiniteQueryOptions<{
275
- error: TError;
276
- key: TKey;
277
- page: TPage;
278
- pageParam: TPageParam;
279
- services: TServices;
280
- }>, "kind" | "throwOnError"> & ThrowOnErrorField<TThrow>): InfiniteQueryOptions<InfiniteQueryTypesOf<TPage, TPageParam, TError, TServices, TKey, TThrow>>;
281
- interface FactoryResult {
282
- readonly kind: "infinite" | "query";
283
- readonly queryKey: QueryKey;
284
- }
285
- /**
286
- * A function of zero or one argument returning `queryOptions(...)` or
287
- * `infiniteQueryOptions(...)` whose `queryFn` needs at most `TServices`
288
- * (any services by default). A second parameter is a type error: the single
289
- * argument is the query's input, and a handle carries it.
128
+ * `queryOptions` bound to a root: `meta` takes the fields the root's links
129
+ * and features declare, and verbs take only that root's clients. `T` is the
130
+ * client's type, or the type of a function that makes it. Bind once per app:
290
131
  *
291
- * The return type names no `queryFn`, and no services for the default:
292
- * TypeScript infers an inline factory's `queryOptions` type arguments from
293
- * it, and an `unknown` there would infer `unknown` services.
294
- */
295
- export type QueryFactory<TServices = unknown> = FactorySignature<unknown extends TServices ? FactoryResult : FactoryResult & ServicesField<TServices>>["call"];
296
- /** A {@link QueryFactory} returning `infiniteQueryOptions(...)`. */
297
- export type PagedQueryFactory<TServices = unknown> = FactorySignature<unknown extends TServices ? PagedFactoryResult : PagedFactoryResult & ServicesField<TServices>>["call"];
298
- interface PagedFactoryResult extends FactoryResult {
299
- readonly kind: "infinite";
300
- }
301
- /**
302
- * A method, so its `input` is checked bivariantly: a factory of any input
303
- * type is assignable. A verb's factory parameter is contextually typed by
304
- * this, and a generic factory maker called inline
305
- * (`qc.ensure(makeFactory(x), input)`) infers its own type parameters
306
- * against it. An `input: never` there would infer `never` for them.
307
- */
308
- interface FactorySignature<TResult> {
309
- call(input: unknown): TResult;
310
- }
311
- /** The factory's input type; `undefined` for factories without one. */
312
- export type InputOf<TFactory extends QueryFactory> = Parameters<TFactory> extends [] ? undefined : Parameters<TFactory>[0];
313
- /** Arguments after the factory: the input, optional when the factory's is. */
314
- export type InputArgs<TFactory extends QueryFactory> = [] extends Parameters<TFactory> ? [input?: InputOf<TFactory>] : [input: InputOf<TFactory>];
315
- /** Whether the factory returns `infiniteQueryOptions(...)`. */
316
- export type IsPaged<TFactory extends QueryFactory> = ReturnType<TFactory> extends {
317
- readonly kind: "infinite";
318
- } ? true : false;
319
- /**
320
- * The data a factory's query resolves to; `unknown` for a factory of no
321
- * particular query.
322
- */
323
- export type DataOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends InfiniteQueryOptions<infer TTypes> ? InfiniteData<{
324
- page: TTypes["page"];
325
- pageParam: TTypes["pageParam"];
326
- }> : ReturnType<TFactory> extends QueryOptions<infer TTypes> ? TTypes["data"] : unknown;
327
- /**
328
- * The error a factory's request fails with: the `queryFn`'s Effect error
329
- * type, or `unknown` for promises and plain values.
330
- */
331
- export type ErrorOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends InfiniteQueryOptions<infer TTypes> ? ErrorIn<TTypes> : ReturnType<TFactory> extends QueryOptions<infer TTypes> ? ErrorIn<TTypes> : unknown;
332
- /**
333
- * The services a factory's `queryFn` Effect needs: what `ensure`, `fetch`,
334
- * `prefetch`, `getQuery` and `watch` require. `never` for promises and plain
335
- * values, and for a factory of no particular query.
132
+ * ```ts
133
+ * // raf.ts
134
+ * export const queryOptions = bindQueryOptions<typeof makeQueryClient>();
135
+ * ```
136
+ *
137
+ * It returns `queryOptions` itself; only the types change.
138
+ *
139
+ * @see https://raf-query.katt.dev/docs/links-and-features#typing-meta-by-its-root
336
140
  */
337
- export type ServicesOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends InfiniteQueryOptions<infer TTypes> ? ServicesIn<TTypes> : ReturnType<TFactory> extends QueryOptions<infer TTypes> ? ServicesIn<TTypes> : never;
141
+ export declare function bindQueryOptions<T>(): QueryOptionsBuilder<RootOf<T>>;
338
142
  /**
339
- * The `throwOnError` a factory's options set, `undefined` when they set
340
- * none (or for a factory of no particular query).
143
+ * A function of the query's input that returns its options. The input is a
144
+ * method parameter typed `unknown`, which TypeScript checks bivariantly:
145
+ * every factory fits, and an inline generic factory maker passed where a
146
+ * `QueryFactory` is expected infers its own type parameters instead of
147
+ * `never`.
148
+ *
149
+ * @see https://raf-query.katt.dev/docs/query-factories
341
150
  */
342
- export type ThrowOnErrorOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends InfiniteQueryOptions<infer TTypes> ? ThrowIn<TTypes> : ReturnType<TFactory> extends QueryOptions<infer TTypes> ? ThrowIn<TTypes> : undefined;
343
- /** Page type of a paged factory. */
344
- export type PageOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends InfiniteQueryOptions<infer TTypes> ? TTypes["page"] : never;
151
+ export type QueryFactory = {
152
+ factory(input: unknown): {
153
+ readonly queryFn: (context: never) => unknown;
154
+ readonly queryKey: QueryKey;
155
+ };
156
+ }["factory"];
345
157
  /**
346
- * `ensure` / `fetch` options, for {@link PagedQueryFactory paged factories}
347
- * only. Not generic: an options type that depends on the factory's type stops
348
- * a generic factory maker called inline from inferring.
158
+ * A factory whose query has one value, not pages: what `useQuery` reads.
159
+ *
160
+ * @see https://raf-query.katt.dev/docs/query-factories
349
161
  */
350
- export interface LoadOptions {
351
- /** Load this many pages up front (default 1). */
352
- readonly pages?: number;
353
- }
354
- declare const factoryType: unique symbol;
162
+ export type SingleQueryFactory = {
163
+ factory(input: unknown): ReturnType<QueryFactory> & {
164
+ readonly getNextPageParam?: never;
165
+ };
166
+ }["factory"];
355
167
  /**
356
- * The serializable reference a loader or server component hands to the
357
- * component that reads the query. It holds no functions.
168
+ * A factory of paged queries (`infiniteQueryOptions`): what `useInfiniteQuery` reads.
169
+ *
170
+ * @see https://raf-query.katt.dev/docs/query-factories
171
+ */
172
+ export type InfiniteQueryFactory = {
173
+ factory(input: unknown): ReturnType<QueryFactory> & {
174
+ readonly getNextPageParam: (...args: never) => unknown;
175
+ };
176
+ }["factory"];
177
+ /** The `queryFn`'s data, before `select`: what `setData` writes and `getData` reads. */
178
+ export type QueryFnDataOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends {
179
+ readonly [queryFnDataTag]?: infer TData;
180
+ } ? TData : unknown;
181
+ /**
182
+ * What a reader gets: the `select`ed data, or else the `queryFn`'s.
183
+ *
184
+ * @see https://raf-query.katt.dev/docs/query-factories#type-inference
358
185
  */
359
- export interface QueryHandle<TFactory extends QueryFactory = QueryFactory> {
360
- /** Type-only: ties the handle to its factory. Never present at runtime. */
361
- readonly [factoryType]?: TFactory;
362
- /** The factory's input; `unknown` on a handle of no particular factory. */
363
- readonly input: InputOf<TFactory>;
364
- readonly key: QueryKey;
365
- }
186
+ export type DataOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends {
187
+ readonly [dataTag]?: infer TData;
188
+ } ? TData : never;
366
189
  /**
367
- * A handle from `ensure` or `fetch`, with the data they waited for. `data`
368
- * is a snapshot from when the handle was returned; components read the live
369
- * entry with `useQuery`.
190
+ * A factory's input: its first parameter, or `undefined` if it takes none.
191
+ *
192
+ * @see https://raf-query.katt.dev/docs/query-factories#type-inference
370
193
  */
371
- export interface QueryHandleWithData<TFactory extends QueryFactory = QueryFactory> extends QueryHandle<TFactory> {
372
- readonly data: DataOf<TFactory>;
373
- }
194
+ export type InputOf<TFactory extends QueryFactory> = Parameters<TFactory> extends [] ? undefined : Parameters<TFactory>[0];
195
+ /** The input arguments of a factory: none, or its input. */
196
+ export type InputArgs<TFactory extends QueryFactory> = Parameters<TFactory> extends [] ? [] : Parameters<TFactory> extends [infer TInput, ...Array<unknown>] ? [input: TInput] : [input?: Parameters<TFactory>[0]];
197
+ /** A factory's key type, the way handles carry it. */
198
+ export type KeyOf<TFactory extends QueryFactory> = ReturnType<TFactory>["queryKey"];
199
+ /** The root a factory's builder is bound to; any root for an unbound one. */
200
+ export type RootOfFactory<TFactory extends QueryFactory> = ReturnType<TFactory> extends {
201
+ readonly "~root"?: RootTag<infer TTypes>;
202
+ } ? TTypes extends DefaultTypes ? AnyRoot : TTypes : AnyRoot;
374
203
  //#endregion
package/dist/options.mjs CHANGED
@@ -3,55 +3,43 @@
3
3
  * Typed options for a query factory:
4
4
  *
5
5
  * ```ts
6
- * export function postQuery(input: { slug: string }) {
7
- * return queryOptions({
8
- * queryKey: ["post", input.slug],
9
- * queryFn: () => getPost(input),
6
+ * export const postQuery = (input: { slug: string }) =>
7
+ * queryOptions({
8
+ * queryKey: posts(input.slug),
9
+ * queryFn: ({ signal }) => getPost(input.slug, { signal }),
10
10
  * });
11
- * }
12
11
  * ```
13
12
  *
14
- * A `queryFn` Effect may need services; they're inferred, and every verb
15
- * that can start the query requires them. Its error is part of the returned
16
- * type. A promise or a plain value has no error to infer, so the type leaves
17
- * `error` out (`ErrorOf` is `unknown`).
13
+ * A `queryFn` that returns an async iterable is a stream: pass `stream` to
14
+ * fold its chunks into the data. Readers get the data after the first chunk,
15
+ * and every later chunk updates it in place.
18
16
  *
19
- * The key's literal type is kept too (`readonly ["post", string]`), so two
20
- * factories with the same input and data but different keys have different
21
- * types, and a handle of one doesn't type-check where the other's goes.
17
+ * Its `meta` is any record. To check `meta` against a client's links and
18
+ * features, use the builder {@link bindQueryOptions} returns.
22
19
  *
23
- * `throwOnError: true` or `false` is kept as a literal too, so reads that
24
- * don't set their own follow it in their types.
25
- *
26
- * The type parameters are only there for TypeScript to infer the types bag
27
- * from `queryFn`, `queryKey` and `throwOnError`; it can't infer a bag's
28
- * members. Passing them explicitly, pass `TThrow` too when setting
29
- * `throwOnError`.
20
+ * @see https://raf-query.katt.dev/docs/query-factories
30
21
  */
31
- function queryOptions(options) {
32
- return {
33
- ...options,
34
- kind: "query"
35
- };
36
- }
22
+ const queryOptions = (options) => options;
37
23
  /**
38
- * Typed options for a paged query factory. The page type is inferred from
39
- * `queryFn`, as in {@link queryOptions}. So is an Effect `queryFn`'s error;
40
- * a promise or a plain value leaves `error` out. The key's literal type is
41
- * kept, as in {@link queryOptions}.
24
+ * `queryOptions` bound to a root: `meta` takes the fields the root's links
25
+ * and features declare, and verbs take only that root's clients. `T` is the
26
+ * client's type, or the type of a function that makes it. Bind once per app:
27
+ *
28
+ * ```ts
29
+ * // raf.ts
30
+ * export const queryOptions = bindQueryOptions<typeof makeQueryClient>();
31
+ * ```
32
+ *
33
+ * It returns `queryOptions` itself; only the types change.
34
+ *
35
+ * @see https://raf-query.katt.dev/docs/links-and-features#typing-meta-by-its-root
42
36
  */
43
- function infiniteQueryOptions(options) {
44
- return {
45
- ...options,
46
- kind: "infinite"
47
- };
37
+ function bindQueryOptions() {
38
+ return queryOptions;
48
39
  }
49
- /**
50
- * Calls a factory with an input the caller has already type-checked against
51
- * `InputArgs<TFactory>`.
52
- */
53
- function optionsFor(factory, input) {
40
+ /** Call a factory with an input its caller's types already checked. */
41
+ function optionsOf(factory, input) {
54
42
  return factory(input);
55
43
  }
56
44
  //#endregion
57
- export { infiniteQueryOptions, optionsFor, queryOptions };
45
+ export { bindQueryOptions, optionsOf, queryOptions };