functype-react 2.2.1 → 2.3.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.
- package/README.md +105 -11
- package/dist/query/index.d.ts +3 -1
- package/dist/query/index.js +1 -1
- package/dist/query/useIOInfiniteQuery.d.ts +67 -0
- package/dist/query/useIOInfiniteQuery.js +2 -0
- package/dist/query/useIOInfiniteQuery.js.map +1 -0
- package/dist/query/useIOMutation.d.ts +1 -1
- package/dist/query/useIOMutation.js.map +1 -1
- package/dist/query/useIOQuery.d.ts +2 -2
- package/dist/query/useIOQuery.js.map +1 -1
- package/dist/router/guard.d.ts +11 -0
- package/dist/router/guard.js +2 -0
- package/dist/router/guard.js.map +1 -0
- package/dist/router/index.d.ts +12 -0
- package/dist/router/index.js +1 -0
- package/dist/router/search.d.ts +56 -0
- package/dist/router/search.js +2 -0
- package/dist/router/search.js.map +1 -0
- package/package.json +12 -2
package/README.md
CHANGED
|
@@ -16,15 +16,16 @@ pnpm add functype functype-react react react-dom
|
|
|
16
16
|
|
|
17
17
|
## Surface
|
|
18
18
|
|
|
19
|
-
| Subpath | Contents
|
|
20
|
-
| ----------------------- |
|
|
21
|
-
| `functype-react` (main) | Stable hooks (`useStable*`), ADT hooks (`useOption`, `useEither`, `useTry`, `useList`), `Match` family components, equality helpers
|
|
22
|
-
| `functype-react/match` | `<Match>`, `<MatchOption>`, `<MatchEither>`, `<MatchTry>` (also re-exported from main)
|
|
23
|
-
| `functype-react/async` | `useIO`, `useIOPromise`, `useIOValue` (React 19 `use()` bridge), `<AsyncBoundary>`
|
|
24
|
-
| `functype-react/forms` | `Validated<E, A>` type alias, `useValidatedField`, `useValidatedForm`
|
|
25
|
-
| `functype-react/query` | `useIOQuery(State)`, `useIOMutation(State)`, `ioQueryFn`, `ioMutationFn`, `IOQueryError`, `toQueryState` — TanStack Query adapters for `IO` |
|
|
19
|
+
| Subpath | Contents |
|
|
20
|
+
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
21
|
+
| `functype-react` (main) | Stable hooks (`useStable*`), ADT hooks (`useOption`, `useEither`, `useTry`, `useList`), `Match` family components, equality helpers |
|
|
22
|
+
| `functype-react/match` | `<Match>`, `<MatchOption>`, `<MatchEither>`, `<MatchTry>` (also re-exported from main) |
|
|
23
|
+
| `functype-react/async` | `useIO`, `useIOPromise`, `useIOValue` (React 19 `use()` bridge), `<AsyncBoundary>` |
|
|
24
|
+
| `functype-react/forms` | `Validated<E, A>` type alias, `useValidatedField`, `useValidatedForm` |
|
|
25
|
+
| `functype-react/query` | `useIOQuery(State)`, `useIOInfiniteQuery`, `useIOMutation(State)`, `ioQueryFn`, `ioMutationFn`, `IOQueryError`, `toQueryState` — TanStack Query adapters for `IO` |
|
|
26
|
+
| `functype-react/router` | `exitRoute`, `searchParams`, `SearchParam` — TanStack Router guards and typed search params |
|
|
26
27
|
|
|
27
|
-
`./async`, `./forms`, and `./
|
|
28
|
+
`./async`, `./forms`, `./query` and `./router` stay off the main entry so consumers who don't touch Suspense, applicative forms, or React Query tree-shake them out.
|
|
28
29
|
|
|
29
30
|
## Tier 1 — stable hooks + ADT hooks
|
|
30
31
|
|
|
@@ -227,11 +228,37 @@ import { Http } from "functype/fetch"
|
|
|
227
228
|
import { useIOMutation } from "functype-react/query"
|
|
228
229
|
|
|
229
230
|
const create = useIOMutation((body: CreateTokenInput) => Http.post<Token>(url, { headers, body }), {
|
|
230
|
-
onError: (e) => toast(e.message, { detail: e.error._tag }),
|
|
231
|
+
onError: (e) => toast(e.message, { detail: e.defect ? "unexpected" : e.error._tag }),
|
|
231
232
|
})
|
|
232
233
|
```
|
|
233
234
|
|
|
234
|
-
|
|
235
|
+
`e` is the `IOQueryError<E>` box, so the typed error is `e.error`, and only when `e.defect` is `false`. To branch on it as an `Option`, write `e.defect ? None<ApiError>() : Some(e.error)`, with your own error type in place of `ApiError`. A bare `None()` makes the result `Option<unknown>`.
|
|
236
|
+
|
|
237
|
+
For a paged query, `useIOInfiniteQuery` takes the page param as an `Option`. The first page gets `None`, and `getNextPageParam` returns `None` when there are no more pages, so a cursor needs no `null` sentinel:
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
import { type IO, Option } from "functype"
|
|
241
|
+
import { useIOInfiniteQuery } from "functype-react/query"
|
|
242
|
+
|
|
243
|
+
type ApiError = { readonly _tag: "ApiError"; readonly status: number }
|
|
244
|
+
type EventPage = { readonly events: readonly string[]; readonly nextCursor: string | null }
|
|
245
|
+
declare const fetchEvents: (cursor: Option<string>, signal: AbortSignal) => IO<never, ApiError, EventPage>
|
|
246
|
+
|
|
247
|
+
const events = useIOInfiniteQuery(["events"], ({ pageParam, signal }) => fetchEvents(pageParam, signal), {
|
|
248
|
+
getNextPageParam: (last: EventPage) => Option(last.nextCursor),
|
|
249
|
+
})
|
|
250
|
+
// events.error is an IOQueryError<ApiError>; events.fetchNextPage and events.hasNextPage are React Query's own
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
- **Annotate the page in `getNextPageParam`,** as above. TypeScript types the effect's `pageParam` first, so it can only learn the param type from a `getNextPageParam` that types on its own. Without the annotation it reports `Option<string>` not assignable to `Option<never>` there.
|
|
254
|
+
- **The param type can't hold `null` or `undefined`.** React Query reads a `null` next param as "no more pages", and `None` already says that.
|
|
255
|
+
- **`data.pageParams` holds plain values.** React Query stores each param as itself, or as `null` for the first page, so its cache stays plain JSON for persisters and SSR.
|
|
256
|
+
- **Other options pass through.** Every other `useInfiniteQuery` option, such as `select`, `maxPages` or `placeholderData: keepPreviousData`, works as usual.
|
|
257
|
+
- **To match the result, project it.** `toQueryState(events)` gives an `AsyncState`. The hook returns React Query's result unchanged.
|
|
258
|
+
- **`None` is only ever the first page you fetched.** After `fetchPreviousPage`, or once `maxPages` drops the first page, a refetch starts from a page whose param is a `Some`, as plain React Query does. So pick params that your effect can fetch any page from, such as offsets or cursors.
|
|
259
|
+
- **A one-page query** still needs a typed `None`: `getNextPageParam: () => Option.none<string>()`.
|
|
260
|
+
|
|
261
|
+
For full control over the query object — or for `useSuspenseQuery` / `queryClient.prefetchQuery` — drop to the primitives. They carry no `@tanstack` types at all, so they compose with any of those:
|
|
235
262
|
|
|
236
263
|
```ts ignore
|
|
237
264
|
import { useQuery } from "@tanstack/react-query"
|
|
@@ -245,7 +272,7 @@ useQuery({
|
|
|
245
272
|
})
|
|
246
273
|
```
|
|
247
274
|
|
|
248
|
-
`ioQueryFn` is generic over the query context, so a richer one flows through unchanged
|
|
275
|
+
`ioQueryFn` is generic over the query context, so a richer one flows through unchanged. Annotate the callback parameter to reach `pageParam` when you call `useInfiniteQuery` yourself:
|
|
249
276
|
|
|
250
277
|
```ts ignore
|
|
251
278
|
import { type QueryFunctionContext, type QueryKey, useInfiniteQuery } from "@tanstack/react-query"
|
|
@@ -264,11 +291,78 @@ useInfiniteQuery({
|
|
|
264
291
|
|
|
265
292
|
Both the hooks and the primitives are generic over any `IO<never, E, A>` — nothing here is HTTP-specific. `Error.message` is derived structurally (`formatIOError`); pass `formatError` to override it. The derivation prefers, in order: a raw `Error`'s `.message`, the HTTP shape (`HTTP 403 Forbidden — /api/x`) for anything carrying a numeric `status`, a tagged error's own `message`, then the bare `_tag`, then JSON.
|
|
266
293
|
|
|
294
|
+
## Tier 6 — TanStack Router
|
|
295
|
+
|
|
296
|
+
`functype-react/router` needs `@tanstack/react-router`, an optional peer.
|
|
297
|
+
|
|
298
|
+
### Guards: `exitRoute`
|
|
299
|
+
|
|
300
|
+
TanStack Router redirects or shows Not Found only when `beforeLoad` or `loader` throws `redirect()` or `notFound()`. `exitRoute` takes an `Either` instead: a `Left` is thrown the way the router expects, and a `Right` is returned, so in `beforeLoad` it becomes the route's context.
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
import { createRootRoute, createRoute, notFound, redirect } from "@tanstack/react-router"
|
|
304
|
+
import { Either } from "functype"
|
|
305
|
+
import { exitRoute, type RouteExit } from "functype-react/router"
|
|
306
|
+
|
|
307
|
+
type Filter = "open" | "closed"
|
|
308
|
+
const isFilter = (value: string): value is Filter => value === "open" || value === "closed"
|
|
309
|
+
|
|
310
|
+
const checkFilter = (filter: string): Either<RouteExit, { readonly filter: Filter }> => {
|
|
311
|
+
if (filter === "all") return Either.left(redirect({ to: "/list/$filter", params: { filter: "open" } }))
|
|
312
|
+
return isFilter(filter) ? Either.right({ filter }) : Either.left(notFound())
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const root = createRootRoute()
|
|
316
|
+
const list = createRoute({
|
|
317
|
+
getParentRoute: () => root,
|
|
318
|
+
path: "/list/$filter",
|
|
319
|
+
beforeLoad: ({ params }) => exitRoute(checkFilter(params.filter)),
|
|
320
|
+
loader: ({ context }) => context.filter, // Filter
|
|
321
|
+
})
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
- **Typing:** a named check with a declared `Either<RouteExit, …>` return type, as above, types cleanly. When you build the `Either` inline, give `exitRoute` its `Right` type, or `void` for a guard that adds no context: `exitRoute<void>(…)`.
|
|
325
|
+
- **Async guards:** `await` the check first: `beforeLoad: async () => exitRoute(await check())`.
|
|
326
|
+
- **No wrapper:** `exitRoute` goes inside a plain `beforeLoad`. A wrapper around the whole function would lose the typed `params` that TanStack gives `beforeLoad`.
|
|
327
|
+
|
|
328
|
+
### Search params: `searchParams`
|
|
329
|
+
|
|
330
|
+
`searchParams` builds a `validateSearch` from one parser per key. Each parser returns an `Option`, so there's no `undefined` spreading per field:
|
|
331
|
+
|
|
332
|
+
```ts
|
|
333
|
+
import { createRootRoute, createRoute } from "@tanstack/react-router"
|
|
334
|
+
import { SearchParam, searchParams } from "functype-react/router"
|
|
335
|
+
|
|
336
|
+
const root = createRootRoute()
|
|
337
|
+
const search = createRoute({
|
|
338
|
+
getParentRoute: () => root,
|
|
339
|
+
path: "/search",
|
|
340
|
+
validateSearch: searchParams({
|
|
341
|
+
q: SearchParam.string,
|
|
342
|
+
page: SearchParam.integer,
|
|
343
|
+
sort: SearchParam.oneOf("new", "old"),
|
|
344
|
+
mine: SearchParam.boolean,
|
|
345
|
+
}),
|
|
346
|
+
})
|
|
347
|
+
// search.useSearch(): { q?: string | undefined; page?: number | undefined; sort?: "new" | "old" | undefined; mine?: boolean | undefined }
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
- **A rejected or missing value is `undefined`.** TanStack merges `validateSearch`'s result over the raw search, so a key left out would keep its raw, unvalidated value; `undefined` replaces it. TanStack leaves `undefined` keys out of the URLs it writes.
|
|
351
|
+
- **The same type works for `navigate`.** `navigate({ to: "/search", search: { q: "cats" } })` checks against it.
|
|
352
|
+
- **The parsers expect TanStack's parsing.** TanStack hands each value to `validateSearch` already parsed as JSON where it can be: `?page=2` is the number 2, and `?mine=true` is `true`.
|
|
353
|
+
- `SearchParam.string` takes a non-empty string. A number or boolean, as a hand-typed `?q=123` or `?q=true` parses, becomes its text. An empty value or `null` is rejected. TanStack has already parsed a hand-typed value as JSON by then, so its original text can be gone: `?q=1e3` arrives as `"1000"`, and a 20-digit number loses precision. Values that `navigate` writes are quoted, so they round-trip exactly.
|
|
354
|
+
- `SearchParam.number` and `SearchParam.integer` take a number, or a decimal string that reads as one. Hex such as `0x10` is rejected.
|
|
355
|
+
- `SearchParam.boolean` takes `true` or `false`, or those strings.
|
|
356
|
+
- `SearchParam.oneOf(...values)` takes one of the given strings.
|
|
357
|
+
- **Your own parser:** any `(raw: unknown) => Option<T>` is a field.
|
|
358
|
+
- **Keys no parser names** still pass through at runtime, as TanStack keeps them, but they aren't in the type.
|
|
359
|
+
|
|
267
360
|
## Compatibility
|
|
268
361
|
|
|
269
362
|
- **TypeScript**: `strict: true` + `noUncheckedIndexedAccess: true`. Loose configs will silently lose the type-level exhaustiveness guarantees.
|
|
270
363
|
- **React**: peer dep range `>=18 <20`. Tier 3's `useIOValue` (and consequently anything that depends on React 19's `use()` hook) is React-19-only at runtime; the rest of the package works on both.
|
|
271
364
|
- **SSR / RSC**: hooks are client-only and marked with `"use client"`. `<Match>` family components are pure and render fine in Server Components.
|
|
365
|
+
- **TanStack Router**: Tier 6 targets `@tanstack/react-router` `>=1.60.0`, an optional peer.
|
|
272
366
|
- **React Query**: Tier 5 targets `@tanstack/react-query` v5 (`>=5.0.0`), an optional peer. The `ioQueryFn` / `ioMutationFn` primitives type their context structurally, so they carry no `@tanstack` types and are unaffected by its major-version churn.
|
|
273
367
|
|
|
274
368
|
## Linting
|
package/dist/query/index.d.ts
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* - `ioQueryFn` / `ioMutationFn` — framework-agnostic primitives; drop into any
|
|
13
13
|
* `useQuery` / `useSuspenseQuery` / `prefetchQuery` call for full option control.
|
|
14
14
|
* - `useIOQuery` / `useIOMutation` — the common path, one call.
|
|
15
|
+
* - `useIOInfiniteQuery` — paged queries, with the page param as an `Option`.
|
|
15
16
|
* - `toQueryState` / `toMutationState` — project a React Query result onto the
|
|
16
17
|
* `AsyncState` ADT so it can be matched exhaustively with the `<Match>` family,
|
|
17
18
|
* rather than read through `data && !error && !isLoading` flag soup.
|
|
@@ -19,8 +20,9 @@
|
|
|
19
20
|
import { IOQueryError, formatIOError, isIOQueryError } from "./IOQueryError.js";
|
|
20
21
|
import { IOBridgeOptions, IOQueryFnContext, ioMutationFn, ioQueryFn } from "./ioQueryFn.js";
|
|
21
22
|
import { MutationResultView, QueryResultView, toMutationState, toQueryState } from "./queryState.js";
|
|
23
|
+
import { IOInfiniteQueryContext, IOPageParamFunction, StoredPageParam, UseIOInfiniteQueryOptions, useIOInfiniteQuery } from "./useIOInfiniteQuery.js";
|
|
22
24
|
import { UseIOMutationOptions, useIOMutation } from "./useIOMutation.js";
|
|
23
25
|
import { UseIOMutationStateResult, useIOMutationState } from "./useIOMutationState.js";
|
|
24
26
|
import { UseIOQueryOptions, useIOQuery } from "./useIOQuery.js";
|
|
25
27
|
import { UseIOQueryStateResult, useIOQueryState } from "./useIOQueryState.js";
|
|
26
|
-
export { type IOBridgeOptions, IOQueryError, type IOQueryFnContext, type MutationResultView, type QueryResultView, type UseIOMutationOptions, type UseIOMutationStateResult, type UseIOQueryOptions, type UseIOQueryStateResult, formatIOError, ioMutationFn, ioQueryFn, isIOQueryError, toMutationState, toQueryState, useIOMutation, useIOMutationState, useIOQuery, useIOQueryState };
|
|
28
|
+
export { type IOBridgeOptions, type IOInfiniteQueryContext, type IOPageParamFunction, IOQueryError, type IOQueryFnContext, type MutationResultView, type QueryResultView, type StoredPageParam, type UseIOInfiniteQueryOptions, type UseIOMutationOptions, type UseIOMutationStateResult, type UseIOQueryOptions, type UseIOQueryStateResult, formatIOError, ioMutationFn, ioQueryFn, isIOQueryError, toMutationState, toQueryState, useIOInfiniteQuery, useIOMutation, useIOMutationState, useIOQuery, useIOQueryState };
|
package/dist/query/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{IOQueryError as e,formatIOError as t,isIOQueryError as n}from"./IOQueryError.js";import{ioMutationFn as r,ioQueryFn as i}from"./ioQueryFn.js";import{toMutationState as a,toQueryState as o}from"./queryState.js";import{
|
|
1
|
+
import{IOQueryError as e,formatIOError as t,isIOQueryError as n}from"./IOQueryError.js";import{ioMutationFn as r,ioQueryFn as i}from"./ioQueryFn.js";import{toMutationState as a,toQueryState as o}from"./queryState.js";import{useIOInfiniteQuery as s}from"./useIOInfiniteQuery.js";import{useIOMutation as c}from"./useIOMutation.js";import{useIOMutationState as l}from"./useIOMutationState.js";import{useIOQuery as u}from"./useIOQuery.js";import{useIOQueryState as d}from"./useIOQueryState.js";export{e as IOQueryError,t as formatIOError,r as ioMutationFn,i as ioQueryFn,n as isIOQueryError,a as toMutationState,o as toQueryState,s as useIOInfiniteQuery,c as useIOMutation,l as useIOMutationState,u as useIOQuery,d as useIOQueryState};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { InfiniteData, QueryKey, QueryMeta, UseInfiniteQueryResult, useInfiniteQuery } from "@tanstack/react-query";
|
|
2
|
+
import { Option } from "functype";
|
|
3
|
+
import { IO } from "functype/io";
|
|
4
|
+
import { IOQueryError } from "./IOQueryError.js";
|
|
5
|
+
/**
|
|
6
|
+
* A page param as React Query stores it: the param itself, or `null` for the first page. Kept a
|
|
7
|
+
* plain value so the cache stays serializable for persisters and SSR hydration; the hook's own
|
|
8
|
+
* callbacks see it as an `Option`.
|
|
9
|
+
*
|
|
10
|
+
* @interop React Query stores page params in its cache and reads a `null` next param as "no more pages".
|
|
11
|
+
*/
|
|
12
|
+
export type StoredPageParam<P> = P | null;
|
|
13
|
+
/** What the effect factory of {@link useIOInfiniteQuery} receives. */
|
|
14
|
+
export type IOInfiniteQueryContext<P, TQueryKey extends QueryKey = QueryKey> = {
|
|
15
|
+
/** Aborts when React Query cancels the fetch. Pass it on to the request. */
|
|
16
|
+
readonly signal: AbortSignal;
|
|
17
|
+
readonly queryKey: TQueryKey;
|
|
18
|
+
/** `None` for the first page, else the param `getNextPageParam` or `getPreviousPageParam` gave. */
|
|
19
|
+
readonly pageParam: Option<P>;
|
|
20
|
+
readonly meta: QueryMeta | undefined;
|
|
21
|
+
};
|
|
22
|
+
/** Works out the param of the next or previous page, or `None` when there isn't one. */
|
|
23
|
+
export type IOPageParamFunction<A, P> = (page: A, allPages: ReadonlyArray<A>, pageParam: Option<P>, allPageParams: ReadonlyArray<Option<P>>) => Option<P>;
|
|
24
|
+
/**
|
|
25
|
+
* The options `useInfiniteQuery` itself takes for these types. Read from the function rather than
|
|
26
|
+
* from `UseInfiniteQueryOptions`, whose type parameters changed within v5.
|
|
27
|
+
*/
|
|
28
|
+
type InfiniteOptions<A, E, P, TData, TQueryKey extends QueryKey> = Parameters<typeof useInfiniteQuery<A, IOQueryError<E>, TData, TQueryKey, StoredPageParam<P>>>[0];
|
|
29
|
+
export type UseIOInfiniteQueryOptions<A, E, P, TData, TQueryKey extends QueryKey> = Omit<InfiniteOptions<A, E, P, TData, TQueryKey>, "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam" | "getPreviousPageParam"> & {
|
|
30
|
+
/** The next page's param, from the last page fetched, or `None` when it was the last. */
|
|
31
|
+
readonly getNextPageParam: IOPageParamFunction<A, P>;
|
|
32
|
+
/** The previous page's param, from the first page fetched, or `None` when it was the first. */
|
|
33
|
+
readonly getPreviousPageParam?: IOPageParamFunction<A, P>;
|
|
34
|
+
/** Override the derived `Error.message` on failure. */
|
|
35
|
+
readonly formatError?: (error: E) => string;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* `useInfiniteQuery` for effects: each page is an `IO<never, E, A>`, and a failure on any page
|
|
39
|
+
* reaches React Query's `error` as an {@link IOQueryError} whose `.error` is the typed `E`.
|
|
40
|
+
*
|
|
41
|
+
* The page param is an `Option`. The first page gets `None`, and `getNextPageParam` returns
|
|
42
|
+
* `None` when there are no more pages, so a cursor needs no `null` sentinel:
|
|
43
|
+
*
|
|
44
|
+
* ```ts
|
|
45
|
+
* const feed = useIOInfiniteQuery(
|
|
46
|
+
* ["feed", filter],
|
|
47
|
+
* ({ signal, pageParam }) => fetchFeed({ filter, cursor: pageParam.orUndefined() }, signal),
|
|
48
|
+
* { getNextPageParam: (last: FeedPage) => Option(last.nextCursor) },
|
|
49
|
+
* )
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* **Annotate the page in `getNextPageParam`**, as above. TypeScript types the effect's
|
|
53
|
+
* `pageParam` before it reads `getNextPageParam`, so it can only learn the param type from a
|
|
54
|
+
* `getNextPageParam` that doesn't need the effect's result to type-check. Leave the annotation
|
|
55
|
+
* out and TypeScript reports `Option<string>` not assignable to `Option<never>` on
|
|
56
|
+
* `getNextPageParam`. Passing a named, typed function works too.
|
|
57
|
+
*
|
|
58
|
+
* `P` can't include `null` or `undefined`: React Query reads a `null` param as "no more pages",
|
|
59
|
+
* and `None` already says so. React Query stores each param as itself, or `null` for the first
|
|
60
|
+
* page, so `data.pageParams` is an array of `P | null`.
|
|
61
|
+
*
|
|
62
|
+
* Every other `useInfiniteQuery` option (`select`, `maxPages`, `placeholderData`, …) passes
|
|
63
|
+
* through. Project the result with `toQueryState` to match it as an `AsyncState`; the hook
|
|
64
|
+
* returns React Query's result unchanged, so `fetchNextPage` and `hasNextPage` stay on it.
|
|
65
|
+
*/
|
|
66
|
+
export declare function useIOInfiniteQuery<A, E, P extends NonNullable<unknown> = never, TData = InfiniteData<A, StoredPageParam<P>>, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, io: (context: IOInfiniteQueryContext<P, TQueryKey>) => IO<never, E, A>, options: UseIOInfiniteQueryOptions<A, E, P, TData, TQueryKey>): UseInfiniteQueryResult<TData, IOQueryError<E>>;
|
|
67
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";import{useInfiniteQuery as e}from"@tanstack/react-query";import{Option as t}from"functype";import{ioQueryFn as n}from"./ioQueryFn.js";const r=e=>e===null?t.none():t(e),i=e=>e.orNull(),a=e=>(t,n,a,o)=>i(e(t,n,r(a),o.map(r)));function o(t,i,o){let{formatError:s,getNextPageParam:c,getPreviousPageParam:l,...u}=o;return e({...u,queryKey:t,queryFn:n(e=>i({signal:e.signal,queryKey:e.queryKey,pageParam:r(e.pageParam),meta:e.meta}),{formatError:s}),initialPageParam:null,getNextPageParam:a(c),...l===void 0?{}:{getPreviousPageParam:a(l)}})}export{o as useIOInfiniteQuery};
|
|
2
|
+
//# sourceMappingURL=useIOInfiniteQuery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useIOInfiniteQuery.js","names":["useInfiniteQuery","Option","ioQueryFn","toOption","param","toStored","stored","f","page","allPages","pageParam","allPageParams","useIOInfiniteQuery","queryKey","io","options","formatError","getNextPageParam","getPreviousPageParam","queryOptions","context"],"sources":["../../src/query/useIOInfiniteQuery.ts"],"sourcesContent":["\"use client\"\n\nimport type {\n InfiniteData,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n UseInfiniteQueryResult,\n} from \"@tanstack/react-query\"\nimport { useInfiniteQuery } from \"@tanstack/react-query\"\nimport type { Option as OptionType } from \"functype\"\nimport { Option } from \"functype\"\nimport type { IO } from \"functype/io\"\n\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { ioQueryFn } from \"./ioQueryFn\"\n\n/**\n * A page param as React Query stores it: the param itself, or `null` for the first page. Kept a\n * plain value so the cache stays serializable for persisters and SSR hydration; the hook's own\n * callbacks see it as an `Option`.\n *\n * @interop React Query stores page params in its cache and reads a `null` next param as \"no more pages\".\n */\nexport type StoredPageParam<P> = P | null\n\n/** What the effect factory of {@link useIOInfiniteQuery} receives. */\nexport type IOInfiniteQueryContext<P, TQueryKey extends QueryKey = QueryKey> = {\n /** Aborts when React Query cancels the fetch. Pass it on to the request. */\n readonly signal: AbortSignal\n readonly queryKey: TQueryKey\n /** `None` for the first page, else the param `getNextPageParam` or `getPreviousPageParam` gave. */\n readonly pageParam: OptionType<P>\n readonly meta: QueryMeta | undefined\n}\n\n/** Works out the param of the next or previous page, or `None` when there isn't one. */\nexport type IOPageParamFunction<A, P> = (\n page: A,\n allPages: ReadonlyArray<A>,\n pageParam: OptionType<P>,\n allPageParams: ReadonlyArray<OptionType<P>>,\n) => OptionType<P>\n\n/**\n * The options `useInfiniteQuery` itself takes for these types. Read from the function rather than\n * from `UseInfiniteQueryOptions`, whose type parameters changed within v5.\n */\ntype InfiniteOptions<A, E, P, TData, TQueryKey extends QueryKey> = Parameters<\n typeof useInfiniteQuery<A, IOQueryError<E>, TData, TQueryKey, StoredPageParam<P>>\n>[0]\n\nexport type UseIOInfiniteQueryOptions<A, E, P, TData, TQueryKey extends QueryKey> = Omit<\n InfiniteOptions<A, E, P, TData, TQueryKey>,\n \"queryKey\" | \"queryFn\" | \"initialPageParam\" | \"getNextPageParam\" | \"getPreviousPageParam\"\n> & {\n /** The next page's param, from the last page fetched, or `None` when it was the last. */\n readonly getNextPageParam: IOPageParamFunction<A, P>\n /** The previous page's param, from the first page fetched, or `None` when it was the first. */\n readonly getPreviousPageParam?: IOPageParamFunction<A, P>\n /** Override the derived `Error.message` on failure. */\n readonly formatError?: (error: E) => string\n}\n\nconst toOption = <P>(param: StoredPageParam<P>): OptionType<P> => (param === null ? Option.none() : Option(param))\n\nconst toStored = <P>(param: OptionType<P>): StoredPageParam<P> => param.orNull()\n\nconst stored =\n <A, P>(f: IOPageParamFunction<A, P>) =>\n (\n page: A,\n allPages: ReadonlyArray<A>,\n pageParam: StoredPageParam<P>,\n allPageParams: ReadonlyArray<StoredPageParam<P>>,\n ): StoredPageParam<P> =>\n toStored(f(page, allPages, toOption(pageParam), allPageParams.map(toOption)))\n\n/**\n * `useInfiniteQuery` for effects: each page is an `IO<never, E, A>`, and a failure on any page\n * reaches React Query's `error` as an {@link IOQueryError} whose `.error` is the typed `E`.\n *\n * The page param is an `Option`. The first page gets `None`, and `getNextPageParam` returns\n * `None` when there are no more pages, so a cursor needs no `null` sentinel:\n *\n * ```ts\n * const feed = useIOInfiniteQuery(\n * [\"feed\", filter],\n * ({ signal, pageParam }) => fetchFeed({ filter, cursor: pageParam.orUndefined() }, signal),\n * { getNextPageParam: (last: FeedPage) => Option(last.nextCursor) },\n * )\n * ```\n *\n * **Annotate the page in `getNextPageParam`**, as above. TypeScript types the effect's\n * `pageParam` before it reads `getNextPageParam`, so it can only learn the param type from a\n * `getNextPageParam` that doesn't need the effect's result to type-check. Leave the annotation\n * out and TypeScript reports `Option<string>` not assignable to `Option<never>` on\n * `getNextPageParam`. Passing a named, typed function works too.\n *\n * `P` can't include `null` or `undefined`: React Query reads a `null` param as \"no more pages\",\n * and `None` already says so. React Query stores each param as itself, or `null` for the first\n * page, so `data.pageParams` is an array of `P | null`.\n *\n * Every other `useInfiniteQuery` option (`select`, `maxPages`, `placeholderData`, …) passes\n * through. Project the result with `toQueryState` to match it as an `AsyncState`; the hook\n * returns React Query's result unchanged, so `fetchNextPage` and `hasNextPage` stay on it.\n */\nexport function useIOInfiniteQuery<\n A,\n E,\n P extends NonNullable<unknown> = never,\n TData = InfiniteData<A, StoredPageParam<P>>,\n TQueryKey extends QueryKey = QueryKey,\n>(\n queryKey: TQueryKey,\n io: (context: IOInfiniteQueryContext<P, TQueryKey>) => IO<never, E, A>,\n options: UseIOInfiniteQueryOptions<A, E, P, TData, TQueryKey>,\n): UseInfiniteQueryResult<TData, IOQueryError<E>> {\n const { formatError, getNextPageParam, getPreviousPageParam, ...queryOptions } = options\n\n return useInfiniteQuery<A, IOQueryError<E>, TData, TQueryKey, StoredPageParam<P>>({\n ...queryOptions,\n queryKey,\n queryFn: ioQueryFn<E, A, QueryFunctionContext<TQueryKey, StoredPageParam<P>>>(\n (context) =>\n io({\n signal: context.signal,\n queryKey: context.queryKey,\n // React Query's context type for `pageParam` differs across v5 releases and a generic `P`\n // leaves it unresolved, so it's read structurally. The hook always sets `initialPageParam`.\n pageParam: toOption((context as { readonly pageParam: StoredPageParam<P> }).pageParam),\n meta: context.meta,\n }),\n { formatError },\n ),\n initialPageParam: null,\n getNextPageParam: stored(getNextPageParam),\n ...(getPreviousPageParam === undefined ? {} : { getPreviousPageParam: stored(getPreviousPageParam) }),\n })\n}\n"],"mappings":"A,mJAgEA,MAAMG,EAAeC,GAA8CA,IAAU,KAAOH,EAAO,KAAK,EAAIA,EAAOG,CAAK,EAE1GC,EAAeD,GAA6CA,EAAM,OAAO,EAEzEE,EACGC,IAELC,EACAC,EACAC,EACAC,IAEAN,EAASE,EAAEC,EAAMC,EAAUN,EAASO,CAAS,EAAGC,EAAc,IAAIR,CAAQ,CAAC,CAAC,EA+BhF,SAAgBS,EAOdC,EACAC,EACAC,EACgD,CAChD,GAAM,CAAEC,cAAaC,mBAAkBC,uBAAsB,GAAGC,GAAiBJ,EAEjF,OAAOf,EAA2E,CAChF,GAAGmB,EACHN,WACA,QAASX,EACNkB,GACCN,EAAG,CACD,OAAQM,EAAQ,OAChB,SAAUA,EAAQ,SAGlB,UAAWjB,EAAUiB,EAAuD,SAAS,EACrF,KAAMA,EAAQ,IAChB,CAAC,EACH,CAAEJ,aAAY,CAChB,EACA,iBAAkB,KAClB,iBAAkBV,EAAOW,CAAgB,EACzC,GAAIC,IAAyB,IAAA,GAAY,CAAC,EAAI,CAAE,qBAAsBZ,EAAOY,CAAoB,CAAE,CACrG,CAAC,CACH,C"}
|
|
@@ -11,7 +11,7 @@ export type UseIOMutationOptions<A, E, V, TContext> = Omit<UseMutationOptions<A,
|
|
|
11
11
|
*
|
|
12
12
|
* ```ts
|
|
13
13
|
* const create = useIOMutation((body: CreateTokenInput) => Http.post<Token>(url, { headers, body }), {
|
|
14
|
-
* onError: (e) => toast(e.message, { detail: e.error._tag }),
|
|
14
|
+
* onError: (e) => toast(e.message, { detail: e.defect ? "unexpected" : e.error._tag }),
|
|
15
15
|
* })
|
|
16
16
|
*
|
|
17
17
|
* create.mutate({ name: "ci" })
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIOMutation.js","names":["useMutation","ioMutationFn","useIOMutation","io","options","formatError","mutationOptions"],"sources":["../../src/query/useIOMutation.ts"],"sourcesContent":["\"use client\"\n\nimport type { UseMutationOptions, UseMutationResult } from \"@tanstack/react-query\"\nimport { useMutation } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { ioMutationFn } from \"./ioQueryFn\"\n\nexport type UseIOMutationOptions<A, E, V, TContext> = Omit<\n UseMutationOptions<A, IOQueryError<E>, V, TContext>,\n \"mutationFn\"\n> & {\n /** Override the derived `Error.message` on failure. */\n readonly formatError?: (error: E) => string\n}\n\n/**\n * `useMutation` for effects — runs an `IO<never, E, A>` per invocation and threads its\n * typed error channel through to React Query.\n *\n * ```ts\n * const create = useIOMutation((body: CreateTokenInput) => Http.post<Token>(url, { headers, body }), {\n * onError: (e) => toast(e.message, { detail: e.error._tag }),\n * })\n *\n * create.mutate({ name: \"ci\" })\n * ```\n *\n * React Query does not supply an `AbortSignal` to mutations, so the callback receives\n * only the mutation variables.\n */\nexport function useIOMutation<A, E, V = void, TContext = unknown>(\n io: (variables: V) => IO<never, E, A>,\n options?: UseIOMutationOptions<A, E, V, TContext>,\n): UseMutationResult<A, IOQueryError<E>, V, TContext> {\n const { formatError, ...mutationOptions } = options ?? {}\n\n return useMutation<A, IOQueryError<E>, V, TContext>({\n ...mutationOptions,\n mutationFn: ioMutationFn<E, A, V>(io, { formatError }),\n })\n}\n"],"mappings":"A,+GAgCA,SAAgBE,EACdC,EACAC,EACoD,CACpD,GAAM,CAAEC,cAAa,GAAGC,GAAoBF,GAAW,CAAC,EAExD,OAAOJ,EAA6C,CAClD,GAAGM,EACH,WAAYL,EAAsBE,EAAI,CAAEE,aAAY,CAAC,CACvD,CAAC,CACH,C"}
|
|
1
|
+
{"version":3,"file":"useIOMutation.js","names":["useMutation","ioMutationFn","useIOMutation","io","options","formatError","mutationOptions"],"sources":["../../src/query/useIOMutation.ts"],"sourcesContent":["\"use client\"\n\nimport type { UseMutationOptions, UseMutationResult } from \"@tanstack/react-query\"\nimport { useMutation } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { ioMutationFn } from \"./ioQueryFn\"\n\nexport type UseIOMutationOptions<A, E, V, TContext> = Omit<\n UseMutationOptions<A, IOQueryError<E>, V, TContext>,\n \"mutationFn\"\n> & {\n /** Override the derived `Error.message` on failure. */\n readonly formatError?: (error: E) => string\n}\n\n/**\n * `useMutation` for effects — runs an `IO<never, E, A>` per invocation and threads its\n * typed error channel through to React Query.\n *\n * ```ts\n * const create = useIOMutation((body: CreateTokenInput) => Http.post<Token>(url, { headers, body }), {\n * onError: (e) => toast(e.message, { detail: e.defect ? \"unexpected\" : e.error._tag }),\n * })\n *\n * create.mutate({ name: \"ci\" })\n * ```\n *\n * React Query does not supply an `AbortSignal` to mutations, so the callback receives\n * only the mutation variables.\n */\nexport function useIOMutation<A, E, V = void, TContext = unknown>(\n io: (variables: V) => IO<never, E, A>,\n options?: UseIOMutationOptions<A, E, V, TContext>,\n): UseMutationResult<A, IOQueryError<E>, V, TContext> {\n const { formatError, ...mutationOptions } = options ?? {}\n\n return useMutation<A, IOQueryError<E>, V, TContext>({\n ...mutationOptions,\n mutationFn: ioMutationFn<E, A, V>(io, { formatError }),\n })\n}\n"],"mappings":"A,+GAgCA,SAAgBE,EACdC,EACAC,EACoD,CACpD,GAAM,CAAEC,cAAa,GAAGC,GAAoBF,GAAW,CAAC,EAExD,OAAOJ,EAA6C,CAClD,GAAGM,EACH,WAAYL,EAAsBE,EAAI,CAAEE,aAAY,CAAC,CACvD,CAAC,CACH,C"}
|
|
@@ -29,7 +29,7 @@ export type UseIOQueryOptions<A, E, TData, TQueryKey extends QueryKey> = Omit<Us
|
|
|
29
29
|
* ```
|
|
30
30
|
*
|
|
31
31
|
* Every other `useQuery` option (`select`, `staleTime`, `placeholderData`, …) passes
|
|
32
|
-
* through untouched. For full control over the query
|
|
33
|
-
*
|
|
32
|
+
* through untouched. For paged queries use `useIOInfiniteQuery`. For full control over the query
|
|
33
|
+
* object, or for `useSuspenseQuery`, use the `ioQueryFn` primitive directly.
|
|
34
34
|
*/
|
|
35
35
|
export declare function useIOQuery<A, E, TData = A, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, io: (context: QueryFunctionContext<TQueryKey>) => IO<never, E, A>, options?: UseIOQueryOptions<A, E, TData, TQueryKey>): UseQueryResult<TData, IOQueryError<E>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIOQuery.js","names":["useQuery","ioQueryFn","useIOQuery","queryKey","io","options","formatError","queryOptions"],"sources":["../../src/query/useIOQuery.ts"],"sourcesContent":["\"use client\"\n\nimport type { QueryFunctionContext, QueryKey, UseQueryOptions, UseQueryResult } from \"@tanstack/react-query\"\nimport { useQuery } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { ioQueryFn } from \"./ioQueryFn\"\n\nexport type UseIOQueryOptions<A, E, TData, TQueryKey extends QueryKey> = Omit<\n UseQueryOptions<A, IOQueryError<E>, TData, TQueryKey>,\n \"queryKey\" | \"queryFn\"\n> & {\n /** Override the derived `Error.message` on failure. */\n readonly formatError?: (error: E) => string\n}\n\n/**\n * `useQuery` for effects — runs an `IO<never, E, A>` and threads its typed error channel\n * through to React Query's `error`.\n *\n * The failure is boxed as `IOQueryError<E>`, so `error instanceof Error` and\n * `error.message` behave normally while `error.error` stays fully discriminable:\n *\n * ```ts\n * const { data, error } = useIOQuery(\n * [\"connector-limits\", userId],\n * ({ signal }) => Http.get<Limits>(url, { headers, signal }),\n * { enabled: !!userId },\n * )\n *\n * if (error) {\n * HttpErrors.match(error.error, {\n * NetworkError: () => <Offline />,\n * HttpStatusError: (e) => (e.status === 403 ? <UpgradePrompt /> : <Failed />),\n * DecodeError: () => <SchemaDrift />,\n * })\n * }\n * ```\n *\n * Every other `useQuery` option (`select`, `staleTime`, `placeholderData`, …) passes\n * through untouched. For full control over the query object
|
|
1
|
+
{"version":3,"file":"useIOQuery.js","names":["useQuery","ioQueryFn","useIOQuery","queryKey","io","options","formatError","queryOptions"],"sources":["../../src/query/useIOQuery.ts"],"sourcesContent":["\"use client\"\n\nimport type { QueryFunctionContext, QueryKey, UseQueryOptions, UseQueryResult } from \"@tanstack/react-query\"\nimport { useQuery } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { ioQueryFn } from \"./ioQueryFn\"\n\nexport type UseIOQueryOptions<A, E, TData, TQueryKey extends QueryKey> = Omit<\n UseQueryOptions<A, IOQueryError<E>, TData, TQueryKey>,\n \"queryKey\" | \"queryFn\"\n> & {\n /** Override the derived `Error.message` on failure. */\n readonly formatError?: (error: E) => string\n}\n\n/**\n * `useQuery` for effects — runs an `IO<never, E, A>` and threads its typed error channel\n * through to React Query's `error`.\n *\n * The failure is boxed as `IOQueryError<E>`, so `error instanceof Error` and\n * `error.message` behave normally while `error.error` stays fully discriminable:\n *\n * ```ts\n * const { data, error } = useIOQuery(\n * [\"connector-limits\", userId],\n * ({ signal }) => Http.get<Limits>(url, { headers, signal }),\n * { enabled: !!userId },\n * )\n *\n * if (error) {\n * HttpErrors.match(error.error, {\n * NetworkError: () => <Offline />,\n * HttpStatusError: (e) => (e.status === 403 ? <UpgradePrompt /> : <Failed />),\n * DecodeError: () => <SchemaDrift />,\n * })\n * }\n * ```\n *\n * Every other `useQuery` option (`select`, `staleTime`, `placeholderData`, …) passes\n * through untouched. For paged queries use `useIOInfiniteQuery`. For full control over the query\n * object, or for `useSuspenseQuery`, use the `ioQueryFn` primitive directly.\n */\nexport function useIOQuery<A, E, TData = A, TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n io: (context: QueryFunctionContext<TQueryKey>) => IO<never, E, A>,\n options?: UseIOQueryOptions<A, E, TData, TQueryKey>,\n): UseQueryResult<TData, IOQueryError<E>> {\n const { formatError, ...queryOptions } = options ?? {}\n\n return useQuery<A, IOQueryError<E>, TData, TQueryKey>({\n ...queryOptions,\n queryKey,\n queryFn: ioQueryFn<E, A, QueryFunctionContext<TQueryKey>>(io, { formatError }),\n })\n}\n"],"mappings":"A,yGA4CA,SAAgBE,EACdC,EACAC,EACAC,EACwC,CACxC,GAAM,CAAEC,cAAa,GAAGC,GAAiBF,GAAW,CAAC,EAErD,OAAOL,EAA+C,CACpD,GAAGO,EACHJ,WACA,QAASF,EAAiDG,EAAI,CAAEE,aAAY,CAAC,CAC/E,CAAC,CACH,C"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AnyRedirect, NotFoundError } from "@tanstack/react-router";
|
|
2
|
+
import { Either } from "functype";
|
|
3
|
+
/** What ends a route early: a `redirect(…)` or a `notFound(…)` from TanStack Router. */
|
|
4
|
+
export type RouteExit = AnyRedirect | NotFoundError;
|
|
5
|
+
/**
|
|
6
|
+
* Ends `beforeLoad` or `loader` from an `Either`: a `Left` redirect or not-found is thrown the way
|
|
7
|
+
* TanStack Router expects, and a `Right` is returned, so in `beforeLoad` it becomes route context.
|
|
8
|
+
*
|
|
9
|
+
* @interop TanStack Router redirects or shows Not Found from beforeLoad or loader only when it throws redirect() or notFound().
|
|
10
|
+
*/
|
|
11
|
+
export declare const exitRoute: <A>(result: Either<RouteExit, A>) => A;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guard.js","names":["exitRoute","result","exit","value"],"sources":["../../src/router/guard.ts"],"sourcesContent":["import type { AnyRedirect, NotFoundError } from \"@tanstack/react-router\"\nimport type { Either } from \"functype\"\n\n/** What ends a route early: a `redirect(…)` or a `notFound(…)` from TanStack Router. */\nexport type RouteExit = AnyRedirect | NotFoundError\n\n/**\n * Ends `beforeLoad` or `loader` from an `Either`: a `Left` redirect or not-found is thrown the way\n * TanStack Router expects, and a `Right` is returned, so in `beforeLoad` it becomes route context.\n *\n * @interop TanStack Router redirects or shows Not Found from beforeLoad or loader only when it throws redirect() or notFound().\n */\nexport const exitRoute = <A>(result: Either<RouteExit, A>): A =>\n result.fold(\n (exit) => {\n throw exit\n },\n (value) => value,\n )\n"],"mappings":"AAYA,MAAaA,EAAgBC,GAC3BA,EAAO,KACJC,GAAS,CACR,MAAMA,CACR,EACCC,GAAUA,CACb,E"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `functype-react/router` — TanStack Router helpers for functype.
|
|
3
|
+
*
|
|
4
|
+
* - `exitRoute` ends `beforeLoad` or `loader` from an `Either`, so a guard returns a value
|
|
5
|
+
* instead of throwing `redirect()` or `notFound()` itself.
|
|
6
|
+
* - `searchParams` and `SearchParam` build a typed `validateSearch` from one `Option` parser per key.
|
|
7
|
+
*
|
|
8
|
+
* Requires `@tanstack/react-router`, an optional peer dependency.
|
|
9
|
+
*/
|
|
10
|
+
import { RouteExit, exitRoute } from "./guard.js";
|
|
11
|
+
import { SearchField, SearchOf, SearchParam, SearchValidator, searchParams } from "./search.js";
|
|
12
|
+
export { type RouteExit, type SearchField, type SearchOf, SearchParam, type SearchValidator, exitRoute, searchParams };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{exitRoute as e}from"./guard.js";import{SearchParam as t,searchParams as n}from"./search.js";export{t as SearchParam,e as exitRoute,n as searchParams};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Option } from "functype";
|
|
2
|
+
/** Reads one search param: `Some` for a value it accepts, `None` for anything else. */
|
|
3
|
+
export type SearchField<T> = (raw: unknown) => Option<T>;
|
|
4
|
+
/**
|
|
5
|
+
* The validated search object: each field's value, or `undefined` when its parser gave `None`.
|
|
6
|
+
*
|
|
7
|
+
* @interop TanStack Router merges validateSearch's result over the raw search and drops undefined keys from URLs, so a rejected key must be undefined, not absent.
|
|
8
|
+
*/
|
|
9
|
+
export type SearchOf<F> = { readonly [K in keyof F]?: (F[K] extends SearchField<infer T> ? T : never) | undefined; };
|
|
10
|
+
/**
|
|
11
|
+
* Parsers for {@link searchParams}. Each takes what TanStack Router's search parsing gives for one
|
|
12
|
+
* key, which is JSON where the value parses as JSON (`?page=2` is the number 2, `?on=true` is
|
|
13
|
+
* `true`) and the raw string otherwise.
|
|
14
|
+
*/
|
|
15
|
+
export declare const SearchParam: {
|
|
16
|
+
/**
|
|
17
|
+
* A non-empty string. A number or boolean, as `?q=123` and `?q=true` parse, becomes its text; an
|
|
18
|
+
* empty value or `null` is rejected.
|
|
19
|
+
*/
|
|
20
|
+
readonly string: (raw: unknown) => Option<string>;
|
|
21
|
+
/** A finite number, or a decimal string that reads as one (not hex). */
|
|
22
|
+
readonly number: (raw: unknown) => Option<number>;
|
|
23
|
+
/** A whole number, or a decimal string that reads as one. */
|
|
24
|
+
readonly integer: (raw: unknown) => Option<number>;
|
|
25
|
+
/** `true` or `false`, or the strings `"true"` and `"false"`. */
|
|
26
|
+
readonly boolean: (raw: unknown) => Option<boolean>;
|
|
27
|
+
/** One of the given strings. Anything else is left out. */
|
|
28
|
+
readonly oneOf: <const V extends readonly [string, ...string[]]>(...values: V) => SearchField<V[number]>;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* A `validateSearch` in TanStack Router's validator-object form. It is an object with `parse`, not a
|
|
32
|
+
* function, because TanStack loses a function validator's type when it is written inline beside a
|
|
33
|
+
* `beforeLoad` or `loaderDeps` that reads `search`.
|
|
34
|
+
*/
|
|
35
|
+
export type SearchValidator<F> = {
|
|
36
|
+
readonly parse: (search: Readonly<Record<string, unknown>>) => SearchOf<F>;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Builds a `validateSearch` from one parser per key. A parser's `None` sets its key to `undefined`.
|
|
40
|
+
* TanStack Router merges this result over the raw search, so an absent key would keep its raw,
|
|
41
|
+
* unvalidated value; `undefined` replaces it, and TanStack leaves `undefined` keys out of URLs. The
|
|
42
|
+
* result is also the type `navigate`'s `search` takes. Keys no parser names still pass through at
|
|
43
|
+
* runtime, as TanStack keeps them, but aren't in the type.
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* const listSearch = searchParams({
|
|
47
|
+
* q: SearchParam.string,
|
|
48
|
+
* page: SearchParam.integer,
|
|
49
|
+
* sort: SearchParam.oneOf("new", "old"),
|
|
50
|
+
* })
|
|
51
|
+
*
|
|
52
|
+
* const list = createRoute({ getParentRoute: () => root, path: "/list", validateSearch: listSearch })
|
|
53
|
+
* // useSearch: { readonly q?: string | undefined; readonly page?: number | undefined; readonly sort?: "new" | "old" | undefined }
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export declare const searchParams: <F extends Readonly<Record<string, SearchField<unknown>>>>(fields: F) => SearchValidator<F>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Option as e}from"functype";const t=t=>typeof t==`string`?t.length>0?e(t):e.none():typeof t==`number`?Number.isFinite(t)?e(String(t)):e.none():typeof t==`boolean`?e(String(t)):e.none(),n=/^-?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$/,r=t=>{if(typeof t==`number`)return Number.isFinite(t)?e(t):e.none();if(typeof t!=`string`||!n.test(t))return e.none();let r=Number(t);return Number.isFinite(r)?e(r):e.none()},i={string:t,number:r,integer:(e=>r(e).filter(Number.isInteger)),boolean:(t=>typeof t==`boolean`?e(t):t===`true`?e(!0):t===`false`?e(!1):e.none()),oneOf:(...e)=>n=>t(n).filter(t=>e.includes(t))},a=e=>({parse:t=>Object.fromEntries(Object.entries(e).map(([e,n])=>[e,n(t[e]).orUndefined()]))});export{i as SearchParam,a as searchParams};
|
|
2
|
+
//# sourceMappingURL=search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search.js","names":["Option","text","raw","DECIMAL","numeric","n","SearchParam","values","value","searchParams","fields","search","key","parse"],"sources":["../../src/router/search.ts"],"sourcesContent":["import type { Option as OptionType } from \"functype\"\nimport { Option } from \"functype\"\n\n/** Reads one search param: `Some` for a value it accepts, `None` for anything else. */\nexport type SearchField<T> = (raw: unknown) => OptionType<T>\n\n/**\n * The validated search object: each field's value, or `undefined` when its parser gave `None`.\n *\n * @interop TanStack Router merges validateSearch's result over the raw search and drops undefined keys from URLs, so a rejected key must be undefined, not absent.\n */\nexport type SearchOf<F> = { readonly [K in keyof F]?: (F[K] extends SearchField<infer T> ? T : never) | undefined }\n\nconst text = (raw: unknown): OptionType<string> => {\n if (typeof raw === \"string\") return raw.length > 0 ? Option(raw) : Option.none()\n // TanStack Router parses `?q=123` as the number 123 and `?q=true` as true, so a hand-typed\n // number or boolean is still text.\n if (typeof raw === \"number\") return Number.isFinite(raw) ? Option(String(raw)) : Option.none()\n return typeof raw === \"boolean\" ? Option(String(raw)) : Option.none()\n}\n\n/**\n * A decimal number as text: digits, an optional fraction and exponent. No hex, no blanks. Each digit\n * run has one way to match, so a long input from a crafted URL is checked in linear time.\n */\nconst DECIMAL = /^-?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?$/\n\nconst numeric = (raw: unknown): OptionType<number> => {\n if (typeof raw === \"number\") return Number.isFinite(raw) ? Option(raw) : Option.none()\n if (typeof raw !== \"string\" || !DECIMAL.test(raw)) return Option.none()\n const n = Number(raw)\n return Number.isFinite(n) ? Option(n) : Option.none()\n}\n\n/**\n * Parsers for {@link searchParams}. Each takes what TanStack Router's search parsing gives for one\n * key, which is JSON where the value parses as JSON (`?page=2` is the number 2, `?on=true` is\n * `true`) and the raw string otherwise.\n */\nexport const SearchParam = {\n /**\n * A non-empty string. A number or boolean, as `?q=123` and `?q=true` parse, becomes its text; an\n * empty value or `null` is rejected.\n */\n string: text satisfies SearchField<string>,\n /** A finite number, or a decimal string that reads as one (not hex). */\n number: numeric satisfies SearchField<number>,\n /** A whole number, or a decimal string that reads as one. */\n integer: ((raw: unknown) => numeric(raw).filter(Number.isInteger)) satisfies SearchField<number>,\n /** `true` or `false`, or the strings `\"true\"` and `\"false\"`. */\n boolean: ((raw: unknown): OptionType<boolean> => {\n if (typeof raw === \"boolean\") return Option(raw)\n if (raw === \"true\") return Option(true)\n return raw === \"false\" ? Option(false) : Option.none()\n }) satisfies SearchField<boolean>,\n /** One of the given strings. Anything else is left out. */\n oneOf:\n <const V extends readonly [string, ...string[]]>(...values: V): SearchField<V[number]> =>\n (raw) =>\n text(raw).filter((value): value is V[number] => values.includes(value)),\n} as const\n\n/**\n * A `validateSearch` in TanStack Router's validator-object form. It is an object with `parse`, not a\n * function, because TanStack loses a function validator's type when it is written inline beside a\n * `beforeLoad` or `loaderDeps` that reads `search`.\n */\nexport type SearchValidator<F> = {\n readonly parse: (search: Readonly<Record<string, unknown>>) => SearchOf<F>\n}\n\n/**\n * Builds a `validateSearch` from one parser per key. A parser's `None` sets its key to `undefined`.\n * TanStack Router merges this result over the raw search, so an absent key would keep its raw,\n * unvalidated value; `undefined` replaces it, and TanStack leaves `undefined` keys out of URLs. The\n * result is also the type `navigate`'s `search` takes. Keys no parser names still pass through at\n * runtime, as TanStack keeps them, but aren't in the type.\n *\n * ```ts\n * const listSearch = searchParams({\n * q: SearchParam.string,\n * page: SearchParam.integer,\n * sort: SearchParam.oneOf(\"new\", \"old\"),\n * })\n *\n * const list = createRoute({ getParentRoute: () => root, path: \"/list\", validateSearch: listSearch })\n * // useSearch: { readonly q?: string | undefined; readonly page?: number | undefined; readonly sort?: \"new\" | \"old\" | undefined }\n * ```\n */\nexport const searchParams = <F extends Readonly<Record<string, SearchField<unknown>>>>(\n fields: F,\n): SearchValidator<F> => ({\n parse: (search) =>\n Object.fromEntries(\n Object.entries(fields).map(([key, parse]) => [key, parse(search[key]).orUndefined()]),\n ) as SearchOf<F>,\n})\n"],"mappings":"A,kCAaA,MAAMC,EAAQC,GACR,OAAOA,GAAQ,SAAiBA,EAAI,OAAS,EAAIF,EAAOE,CAAG,EAAIF,EAAO,KAAK,EAG3E,OAAOE,GAAQ,SAAiB,OAAO,SAASA,CAAG,EAAIF,EAAO,OAAOE,CAAG,CAAC,EAAIF,EAAO,KAAK,EACtF,OAAOE,GAAQ,UAAYF,EAAO,OAAOE,CAAG,CAAC,EAAIF,EAAO,KAAK,EAOhEG,EAAU,yCAEVC,EAAWF,GAAqC,CACpD,GAAI,OAAOA,GAAQ,SAAU,OAAO,OAAO,SAASA,CAAG,EAAIF,EAAOE,CAAG,EAAIF,EAAO,KAAK,EACrF,GAAI,OAAOE,GAAQ,UAAY,CAACC,EAAQ,KAAKD,CAAG,EAAG,OAAOF,EAAO,KAAK,EACtE,IAAMK,EAAI,OAAOH,CAAG,EACpB,OAAO,OAAO,SAASG,CAAC,EAAIL,EAAOK,CAAC,EAAIL,EAAO,KAAK,CACtD,EAOaM,EAAc,CAKzB,OAAQL,EAER,OAAQG,EAER,SAAWF,GAAiBE,EAAQF,CAAG,CAAC,CAAC,OAAO,OAAO,SAAS,GAEhE,SAAWA,GACL,OAAOA,GAAQ,UAAkBF,EAAOE,CAAG,EAC3CA,IAAQ,OAAeF,EAAO,EAAI,EAC/BE,IAAQ,QAAUF,EAAO,EAAK,EAAIA,EAAO,KAAK,GAGvD,OACmD,GAAGO,IACnDL,GACCD,EAAKC,CAAG,CAAC,CAAC,OAAQM,GAA8BD,EAAO,SAASC,CAAK,CAAC,CAC5E,EA6BaC,EACXC,IACwB,CACxB,MAAQC,GACN,OAAO,YACL,OAAO,QAAQD,CAAM,CAAC,CAAC,KAAK,CAACE,EAAKC,KAAW,CAACD,EAAKC,EAAMF,EAAOC,EAAI,CAAC,CAAC,YAAY,CAAC,CAAC,CACtF,CACJ,G"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "functype-react",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "React bindings for functype — ADT-aware hooks and exhaustive pattern matching components",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"functype",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
},
|
|
27
27
|
"peerDependencies": {
|
|
28
28
|
"@tanstack/react-query": ">=5.0.0",
|
|
29
|
+
"@tanstack/react-router": ">=1.60.0",
|
|
29
30
|
"functype": ">=2.0.0",
|
|
30
31
|
"react": ">=18.0.0 <20.0.0",
|
|
31
32
|
"react-dom": ">=18.0.0 <20.0.0"
|
|
@@ -34,12 +35,16 @@
|
|
|
34
35
|
"@tanstack/react-query": {
|
|
35
36
|
"optional": true
|
|
36
37
|
},
|
|
38
|
+
"@tanstack/react-router": {
|
|
39
|
+
"optional": true
|
|
40
|
+
},
|
|
37
41
|
"react-dom": {
|
|
38
42
|
"optional": true
|
|
39
43
|
}
|
|
40
44
|
},
|
|
41
45
|
"devDependencies": {
|
|
42
46
|
"@tanstack/react-query": "^5.108.2",
|
|
47
|
+
"@tanstack/react-router": "1.170.46",
|
|
43
48
|
"@testing-library/dom": "^10.4.2",
|
|
44
49
|
"@testing-library/jest-dom": "^7.0.1",
|
|
45
50
|
"@testing-library/react": "^16.3.3",
|
|
@@ -47,7 +52,7 @@
|
|
|
47
52
|
"@types/react": "^19.3.0",
|
|
48
53
|
"@types/react-dom": "^19.3.0",
|
|
49
54
|
"fast-check": "^4.10.3",
|
|
50
|
-
"functype": "^2.
|
|
55
|
+
"functype": "^2.3.0",
|
|
51
56
|
"jsdom": "^31.0.1",
|
|
52
57
|
"react": "^19.3.1",
|
|
53
58
|
"react-dom": "^19.3.1",
|
|
@@ -84,6 +89,11 @@
|
|
|
84
89
|
"types": "./dist/query/index.d.ts",
|
|
85
90
|
"import": "./dist/query/index.js",
|
|
86
91
|
"default": "./dist/query/index.js"
|
|
92
|
+
},
|
|
93
|
+
"./router": {
|
|
94
|
+
"types": "./dist/router/index.d.ts",
|
|
95
|
+
"import": "./dist/router/index.js",
|
|
96
|
+
"default": "./dist/router/index.js"
|
|
87
97
|
}
|
|
88
98
|
},
|
|
89
99
|
"files": [
|