@raf-query/core 0.11.1 → 0.12.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 (71) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +28 -18
  3. package/dist/client.d.mts +132 -121
  4. package/dist/client.mjs +59 -162
  5. package/dist/entry.d.mts +67 -148
  6. package/dist/entry.mjs +303 -474
  7. package/dist/features/focus-refetch/focus-refetch.d.mts +15 -0
  8. package/dist/features/focus-refetch/focus-refetch.mjs +18 -0
  9. package/dist/features/polling/polling.d.mts +12 -0
  10. package/dist/features/polling/polling.mjs +35 -0
  11. package/dist/features/reconnect-refetch/reconnect-refetch.d.mts +15 -0
  12. package/dist/features/reconnect-refetch/reconnect-refetch.mjs +14 -0
  13. package/dist/features/shared.mjs +13 -0
  14. package/dist/guards.mjs +23 -0
  15. package/dist/hydration/hydration.d.mts +73 -0
  16. package/dist/hydration/hydration.mjs +128 -0
  17. package/dist/index.d.mts +18 -13
  18. package/dist/index.mjs +15 -13
  19. package/dist/infinite/infinite.d.mts +71 -0
  20. package/dist/infinite/infinite.mjs +88 -0
  21. package/dist/internal.d.mts +13 -0
  22. package/dist/internal.mjs +7 -0
  23. package/dist/keys/keys.d.mts +46 -0
  24. package/dist/keys/keys.mjs +53 -0
  25. package/dist/keys/targets.d.mts +56 -0
  26. package/dist/keys/targets.mjs +85 -0
  27. package/dist/links/retry/retry.d.mts +26 -0
  28. package/dist/links/retry/retry.mjs +51 -0
  29. package/dist/links/timeout/timeout.d.mts +9 -0
  30. package/dist/links/timeout/timeout.mjs +27 -0
  31. package/dist/load.d.mts +124 -0
  32. package/dist/load.mjs +165 -0
  33. package/dist/options.d.mts +112 -351
  34. package/dist/options.mjs +25 -41
  35. package/dist/presets.d.mts +29 -0
  36. package/dist/presets.mjs +25 -0
  37. package/dist/root.d.mts +82 -0
  38. package/dist/structural-sharing/structural-sharing.mjs +32 -0
  39. package/dist/subscribe.d.mts +15 -0
  40. package/dist/subscribe.mjs +29 -0
  41. package/dist/thenable.d.mts +13 -17
  42. package/dist/thenable.mjs +25 -6
  43. package/dist/verbs.d.mts +109 -0
  44. package/dist/verbs.mjs +87 -0
  45. package/package.json +13 -9
  46. package/dist/_virtual/_rolldown/runtime.mjs +0 -13
  47. package/dist/all-keyed.d.mts +0 -18
  48. package/dist/all-keyed.mjs +0 -19
  49. package/dist/binding.d.mts +0 -92
  50. package/dist/binding.mjs +0 -186
  51. package/dist/cache.d.mts +0 -164
  52. package/dist/cache.mjs +0 -184
  53. package/dist/controls.d.mts +0 -95
  54. package/dist/controls.mjs +0 -70
  55. package/dist/hydration.d.mts +0 -84
  56. package/dist/hydration.mjs +0 -148
  57. package/dist/infinite.d.mts +0 -5
  58. package/dist/infinite.mjs +0 -103
  59. package/dist/key.d.mts +0 -18
  60. package/dist/key.mjs +0 -36
  61. package/dist/listen.mjs +0 -19
  62. package/dist/notify.mjs +0 -21
  63. package/dist/observer.d.mts +0 -110
  64. package/dist/observer.mjs +0 -300
  65. package/dist/platform.d.mts +0 -27
  66. package/dist/platform.mjs +0 -44
  67. package/dist/query.d.mts +0 -137
  68. package/dist/query.mjs +0 -147
  69. package/dist/request.mjs +0 -47
  70. package/dist/retry.mjs +0 -25
  71. package/dist/share.mjs +0 -40
@@ -1,374 +1,135 @@
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
3
  //#region src/options.d.ts
4
- /**
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.
11
- *
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.
85
- */
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. */
4
+ export interface QueryFunctionContext<TKey extends QueryKey = QueryKey> {
5
+ /** The query's `meta`, typed by its root where the query is defined. */
6
+ readonly meta: object;
7
+ readonly queryKey: TKey;
8
+ /** Aborted when the request is restarted or its entry is removed. */
114
9
  readonly signal: AbortSignal;
115
10
  }
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 {
129
- /**
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.
141
- */
142
- readonly enabled?: boolean;
143
- /** How long an unread entry stays cached, in ms. `Infinity` keeps it. */
11
+ declare const dataTag: unique symbol;
12
+ /** Options every query takes. */
13
+ export interface BaseOptions<TKey extends QueryKey, TTypes extends RootTypes = RootTypes> {
14
+ /** How long an entry with no reader stays cached. Default 5 minutes; never on the server. */
144
15
  readonly gcTime?: number;
145
16
  /**
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.
17
+ * Settings for the root's links and features, and data for targets: the
18
+ * fields the root's parts declare, such as `retry` with the `retry()`
19
+ * link.
149
20
  */
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. */
21
+ readonly meta?: NoInfer<Partial<TTypes["meta"]>>;
22
+ /** A plain array, usually built by a `group()`. Handles keep its literal type. */
23
+ readonly queryKey: TKey;
24
+ /** How long data stays fresh, in ms. Default `0`. */
160
25
  readonly staleTime?: number;
161
- /**
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`.
165
- */
26
+ /** Keep the deeply equal parts of new data, so they keep their identity. Default `true`. */
166
27
  readonly structuralSharing?: boolean;
167
28
  }
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> {
178
- /**
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.
184
- */
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>;
191
- }
192
- /**
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.
197
- */
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;
204
- }
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>;
29
+ /** What `queryOptions` and `infiniteQueryOptions` return. */
30
+ export interface QueryOptions<TKey extends QueryKey = QueryKey, TQueryFnData = unknown, TData = TQueryFnData, TTypes extends RootTypes = RootTypes> extends BaseOptions<TKey, TTypes> {
31
+ /** Phantom: the root the builder is bound to. Never set at runtime. */
32
+ readonly "~root"?: RootTag<TTypes>;
33
+ /** Set by `infiniteQueryOptions`: runs the request page by page. */
34
+ readonly "~run"?: (op: never) => Promise<unknown>;
35
+ readonly [dataTag]?: TData;
36
+ readonly queryFn: (context: never) => unknown;
37
+ readonly select?: (data: TQueryFnData) => TData;
38
+ readonly stream?: StreamOptions<TQueryFnData, never>;
39
+ }
40
+ export interface StreamOptions<TData, TChunk> {
41
+ /** The data before the first chunk. */
42
+ readonly initial: TData;
43
+ /** Fold a chunk into the data. */
44
+ readonly reduce: (data: TData, chunk: TChunk) => TData;
45
+ }
46
+ type Awaitable<T> = PromiseLike<T> | T;
47
+ /**
48
+ * `T` as a conditional type, so a builder infers its data type from the
49
+ * `queryFn` alone: an annotated `select` or `getNextPageParam` parameter
50
+ * doesn't widen it.
51
+ */
52
+ export type FromQueryFn<T> = T extends unknown ? T : never;
53
+ /** `queryOptions`, with `meta` checked against the root `TTypes`. */
54
+ export interface QueryOptionsBuilder<TTypes extends RootTypes> {
55
+ <const TKey extends QueryKey, TChunk, TData>(options: BaseOptions<TKey, TTypes> & {
56
+ readonly queryFn: (context: QueryFunctionContext<TKey>) => AsyncIterable<TChunk>;
57
+ readonly stream: StreamOptions<TData, TChunk>;
58
+ }): QueryOptions<TKey, TData, TData, TTypes>;
59
+ <const TKey extends QueryKey, TQueryFnData, TData = TQueryFnData>(options: BaseOptions<TKey, TTypes> & {
60
+ readonly queryFn: (context: QueryFunctionContext<TKey>) => Awaitable<TQueryFnData>;
61
+ readonly select?: (data: FromQueryFn<TQueryFnData>) => TData;
62
+ }): QueryOptions<TKey, TQueryFnData, TData, TTypes>;
215
63
  }
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"]>;
220
- }
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
64
  /**
234
65
  * Typed options for a query factory:
235
66
  *
236
67
  * ```ts
237
- * export function postQuery(input: { slug: string }) {
238
- * return queryOptions({
239
- * queryKey: ["post", input.slug],
240
- * queryFn: () => getPost(input),
68
+ * export const issueQuery = (input: { id: number }) =>
69
+ * queryOptions({
70
+ * queryKey: issues("byId", input),
71
+ * queryFn: ({ signal }) => getIssue(input.id, { signal }),
241
72
  * });
242
- * }
243
73
  * ```
244
74
  *
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.
75
+ * A `queryFn` that returns an async iterable is a stream: pass `stream` to
76
+ * fold its chunks into the data. Readers get the data after the first chunk,
77
+ * and every later chunk updates it in place.
253
78
  *
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.
256
- *
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`.
261
- */
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>>;
268
- /**
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}.
79
+ * Its `meta` is any record. To check `meta` against a client's links and
80
+ * features, use the builder {@link bindQueryOptions} returns.
273
81
  */
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
- }
82
+ export declare const queryOptions: QueryOptionsBuilder<DefaultTypes>;
285
83
  /**
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.
84
+ * `queryOptions` bound to a root: `meta` takes the fields the root's links
85
+ * and features declare, and verbs take only that root's clients. `T` is the
86
+ * client's type, or the type of a function that makes it. Bind once per app:
290
87
  *
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. */
88
+ * ```ts
89
+ * // raf.ts
90
+ * export const queryOptions = bindQueryOptions<typeof makeQueryClient>();
91
+ * ```
92
+ *
93
+ * It returns `queryOptions` itself; only the types change.
94
+ */
95
+ export declare function bindQueryOptions<T>(): QueryOptionsBuilder<RootOf<T>>;
96
+ /**
97
+ * A function of the query's input that returns its options. The input is a
98
+ * method parameter typed `unknown`, which TypeScript checks bivariantly:
99
+ * every factory fits, and an inline generic factory maker passed where a
100
+ * `QueryFactory` is expected infers its own type parameters instead of
101
+ * `never`.
102
+ */
103
+ export type QueryFactory = {
104
+ factory(input: unknown): {
105
+ readonly queryFn: (context: never) => unknown;
106
+ readonly queryKey: QueryKey;
107
+ };
108
+ }["factory"];
109
+ /** A factory whose query has one value, not pages: what `useQuery` reads. */
110
+ export type SingleQueryFactory = {
111
+ factory(input: unknown): ReturnType<QueryFactory> & {
112
+ readonly getNextPageParam?: never;
113
+ };
114
+ }["factory"];
115
+ /** A factory of paged queries (`infiniteQueryOptions`): what `useInfiniteQuery` reads. */
116
+ export type InfiniteQueryFactory = {
117
+ factory(input: unknown): ReturnType<QueryFactory> & {
118
+ readonly getNextPageParam: (...args: never) => unknown;
119
+ };
120
+ }["factory"];
121
+ /** What a reader gets: the `select`ed data, or else the `queryFn`'s. */
122
+ export type DataOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends {
123
+ readonly [dataTag]?: infer TData;
124
+ } ? TData : never;
125
+ /** A factory's input: its first parameter, or `undefined` if it takes none. */
312
126
  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.
336
- */
337
- export type ServicesOf<TFactory extends QueryFactory> = ReturnType<TFactory> extends InfiniteQueryOptions<infer TTypes> ? ServicesIn<TTypes> : ReturnType<TFactory> extends QueryOptions<infer TTypes> ? ServicesIn<TTypes> : never;
338
- /**
339
- * The `throwOnError` a factory's options set, `undefined` when they set
340
- * none (or for a factory of no particular query).
341
- */
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;
345
- /**
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.
349
- */
350
- export interface LoadOptions {
351
- /** Load this many pages up front (default 1). */
352
- readonly pages?: number;
353
- }
354
- declare const factoryType: unique symbol;
355
- /**
356
- * The serializable reference a loader or server component hands to the
357
- * component that reads the query. It holds no functions.
358
- */
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
- }
366
- /**
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`.
370
- */
371
- export interface QueryHandleWithData<TFactory extends QueryFactory = QueryFactory> extends QueryHandle<TFactory> {
372
- readonly data: DataOf<TFactory>;
373
- }
127
+ /** The input arguments of a factory: none, or its input. */
128
+ export type InputArgs<TFactory extends QueryFactory> = Parameters<TFactory> extends [] ? [] : Parameters<TFactory> extends [infer TInput, ...Array<unknown>] ? [input: TInput] : [input?: Parameters<TFactory>[0]];
129
+ /** A factory's key type, the way handles carry it. */
130
+ export type KeyOf<TFactory extends QueryFactory> = ReturnType<TFactory>["queryKey"];
131
+ /** The root a factory's builder is bound to; any root for an unbound one. */
132
+ export type RootOfFactory<TFactory extends QueryFactory> = ReturnType<TFactory> extends {
133
+ readonly "~root"?: RootTag<infer TTypes>;
134
+ } ? TTypes extends DefaultTypes ? AnyRoot : TTypes : AnyRoot;
374
135
  //#endregion
package/dist/options.mjs CHANGED
@@ -3,55 +3,39 @@
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 issueQuery = (input: { id: number }) =>
7
+ * queryOptions({
8
+ * queryKey: issues("byId", input),
9
+ * queryFn: ({ signal }) => getIssue(input.id, { 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.
22
- *
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`.
17
+ * Its `meta` is any record. To check `meta` against a client's links and
18
+ * features, use the builder {@link bindQueryOptions} returns.
30
19
  */
31
- function queryOptions(options) {
32
- return {
33
- ...options,
34
- kind: "query"
35
- };
36
- }
20
+ const queryOptions = (options) => options;
37
21
  /**
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}.
22
+ * `queryOptions` bound to a root: `meta` takes the fields the root's links
23
+ * and features declare, and verbs take only that root's clients. `T` is the
24
+ * client's type, or the type of a function that makes it. Bind once per app:
25
+ *
26
+ * ```ts
27
+ * // raf.ts
28
+ * export const queryOptions = bindQueryOptions<typeof makeQueryClient>();
29
+ * ```
30
+ *
31
+ * It returns `queryOptions` itself; only the types change.
42
32
  */
43
- function infiniteQueryOptions(options) {
44
- return {
45
- ...options,
46
- kind: "infinite"
47
- };
33
+ function bindQueryOptions() {
34
+ return queryOptions;
48
35
  }
49
- /**
50
- * Calls a factory with an input the caller has already type-checked against
51
- * `InputArgs<TFactory>`.
52
- */
53
- function optionsFor(factory, input) {
36
+ /** Call a factory with an input its caller's types already checked. */
37
+ function optionsOf(factory, input) {
54
38
  return factory(input);
55
39
  }
56
40
  //#endregion
57
- export { infiniteQueryOptions, optionsFor, queryOptions };
41
+ export { bindQueryOptions, optionsOf, queryOptions };
@@ -0,0 +1,29 @@
1
+ import { Feature, Link } from "./client.mjs";
2
+ import { FocusRefetchMeta } from "./features/focus-refetch/focus-refetch.mjs";
3
+ import { ReconnectRefetchMeta } from "./features/reconnect-refetch/reconnect-refetch.mjs";
4
+ import { PollingMeta } from "./features/polling/polling.mjs";
5
+ import { RetryMeta } from "./links/retry/retry.mjs";
6
+ //#region src/presets.d.ts
7
+ /** What `recommended()` returns: its parts keep the `meta` they declare. */
8
+ export interface Recommended {
9
+ readonly features: readonly [Feature<{
10
+ readonly meta: FocusRefetchMeta;
11
+ }>, Feature<{
12
+ readonly meta: ReconnectRefetchMeta;
13
+ }>, Feature<{
14
+ readonly meta: PollingMeta;
15
+ }>];
16
+ readonly links: readonly [Link<{
17
+ readonly meta: RetryMeta;
18
+ }>];
19
+ }
20
+ /**
21
+ * The behaviors most apps want: retries, refetching on focus and reconnect,
22
+ * and polling. Spread it into the config:
23
+ *
24
+ * ```ts
25
+ * createQueryClient({ ...recommended(), staleTime: 30_000 });
26
+ * ```
27
+ */
28
+ export declare function recommended(): Recommended;
29
+ //#endregion
@@ -0,0 +1,25 @@
1
+ import { focusRefetch } from "./features/focus-refetch/focus-refetch.mjs";
2
+ import { reconnectRefetch } from "./features/reconnect-refetch/reconnect-refetch.mjs";
3
+ import { polling } from "./features/polling/polling.mjs";
4
+ import { retry } from "./links/retry/retry.mjs";
5
+ //#region src/presets.ts
6
+ /**
7
+ * The behaviors most apps want: retries, refetching on focus and reconnect,
8
+ * and polling. Spread it into the config:
9
+ *
10
+ * ```ts
11
+ * createQueryClient({ ...recommended(), staleTime: 30_000 });
12
+ * ```
13
+ */
14
+ function recommended() {
15
+ return {
16
+ features: [
17
+ focusRefetch(),
18
+ reconnectRefetch(),
19
+ polling()
20
+ ],
21
+ links: [retry()]
22
+ };
23
+ }
24
+ //#endregion
25
+ export { recommended };