what-core 0.13.11 → 0.15.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 (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -38
  3. package/a11y.d.ts +128 -0
  4. package/data.d.ts +294 -0
  5. package/dist/a11y.js +510 -0
  6. package/dist/a11y.min.js +413 -0
  7. package/dist/actions.js +158 -0
  8. package/dist/actions.min.js +112 -0
  9. package/dist/animation.js +481 -0
  10. package/dist/animation.min.js +295 -0
  11. package/dist/async.js +180 -0
  12. package/dist/async.min.js +134 -0
  13. package/dist/components.js +577 -0
  14. package/dist/components.min.js +413 -0
  15. package/dist/data.js +1212 -0
  16. package/dist/data.min.js +918 -0
  17. package/dist/diagnostics.js +187 -0
  18. package/dist/diagnostics.min.js +134 -0
  19. package/dist/dom.js +796 -0
  20. package/dist/dom.min.js +603 -0
  21. package/dist/entries/a11y.js +43 -0
  22. package/dist/entries/a11y.min.js +43 -0
  23. package/dist/entries/data.js +29 -0
  24. package/dist/entries/data.min.js +29 -0
  25. package/dist/entries/dom.js +45 -0
  26. package/dist/entries/dom.min.js +45 -0
  27. package/dist/entries/form.js +31 -0
  28. package/dist/entries/form.min.js +31 -0
  29. package/dist/entries/internal.js +123 -0
  30. package/dist/entries/internal.min.js +123 -0
  31. package/dist/entries/motion.js +23 -0
  32. package/dist/entries/motion.min.js +23 -0
  33. package/dist/entries/ui.js +25 -0
  34. package/dist/entries/ui.min.js +25 -0
  35. package/dist/env.js +5 -0
  36. package/dist/env.min.js +5 -0
  37. package/dist/errors.js +1518 -0
  38. package/dist/errors.min.js +548 -0
  39. package/dist/form.js +936 -0
  40. package/dist/form.min.js +703 -0
  41. package/dist/guardrails.js +84 -0
  42. package/dist/guardrails.min.js +55 -0
  43. package/dist/h.js +232 -0
  44. package/dist/h.min.js +171 -0
  45. package/dist/head.js +241 -0
  46. package/dist/head.min.js +207 -0
  47. package/dist/helpers.js +126 -0
  48. package/dist/helpers.min.js +98 -0
  49. package/dist/hooks.js +255 -0
  50. package/dist/hooks.min.js +153 -0
  51. package/dist/hot.js +215 -0
  52. package/dist/hot.min.js +24 -0
  53. package/dist/hydration-data.js +495 -0
  54. package/dist/hydration-data.min.js +371 -0
  55. package/dist/import-changes.js +273 -0
  56. package/dist/import-changes.min.js +272 -0
  57. package/dist/index.js +95 -0
  58. package/dist/index.min.js +95 -227
  59. package/dist/jsx-dev-runtime.js +10 -0
  60. package/dist/jsx-dev-runtime.min.js +10 -1
  61. package/dist/jsx-runtime.js +27 -0
  62. package/dist/jsx-runtime.min.js +15 -1
  63. package/dist/live.js +54 -0
  64. package/dist/live.min.js +49 -0
  65. package/dist/markup-rules.js +250 -0
  66. package/dist/markup-rules.min.js +213 -0
  67. package/dist/reactive.js +3334 -0
  68. package/dist/reactive.min.js +2033 -0
  69. package/dist/render.js +4746 -0
  70. package/dist/render.min.js +2797 -1
  71. package/dist/scheduler.js +225 -0
  72. package/dist/scheduler.min.js +162 -0
  73. package/dist/selector.js +11 -0
  74. package/dist/selector.min.js +10 -0
  75. package/dist/server-context.js +148 -0
  76. package/dist/server-context.min.js +121 -0
  77. package/dist/skeleton.js +342 -0
  78. package/dist/skeleton.min.js +310 -0
  79. package/dist/store.js +72 -0
  80. package/dist/store.min.js +50 -0
  81. package/dist/testing.js +720 -0
  82. package/dist/testing.min.js +458 -1
  83. package/dist/vnode-adoption.js +19 -0
  84. package/dist/vnode-adoption.min.js +19 -0
  85. package/dist/vnode-renderer.js +61 -0
  86. package/dist/vnode-renderer.min.js +47 -0
  87. package/dom.d.ts +44 -0
  88. package/form.d.ts +218 -0
  89. package/hot.d.ts +35 -0
  90. package/index.d.ts +421 -736
  91. package/internal.d.ts +284 -0
  92. package/jsx-runtime.d.ts +160 -137
  93. package/markup-rules.d.ts +83 -0
  94. package/motion.d.ts +156 -0
  95. package/package.json +117 -3
  96. package/render.d.ts +278 -29
  97. package/src/a11y.js +64 -59
  98. package/src/actions.js +226 -0
  99. package/src/animation.js +105 -57
  100. package/src/async.js +259 -0
  101. package/src/components.js +495 -144
  102. package/src/data.js +1410 -1159
  103. package/src/diagnostics.js +263 -0
  104. package/src/dom.js +1159 -872
  105. package/src/entries/a11y.js +24 -0
  106. package/src/entries/data.js +17 -0
  107. package/src/entries/dom.js +29 -0
  108. package/src/entries/form.js +16 -0
  109. package/src/entries/internal.js +63 -0
  110. package/src/entries/motion.js +13 -0
  111. package/src/entries/ui.js +13 -0
  112. package/src/env-development.js +12 -0
  113. package/src/env.js +33 -0
  114. package/src/errors.js +1144 -168
  115. package/src/form.js +723 -225
  116. package/src/guardrails.js +38 -126
  117. package/src/h.js +227 -152
  118. package/src/head.js +189 -19
  119. package/src/helpers.js +47 -75
  120. package/src/hooks.js +233 -248
  121. package/src/hot.js +316 -0
  122. package/src/hydration-data.js +859 -16
  123. package/src/import-changes.js +156 -0
  124. package/src/index.js +38 -188
  125. package/src/jsx-dev-runtime.js +7 -14
  126. package/src/jsx-runtime.js +25 -9
  127. package/src/live.js +80 -0
  128. package/src/markup-rules.js +387 -0
  129. package/src/reactive.js +4400 -862
  130. package/src/render.js +6502 -2570
  131. package/src/scheduler.js +56 -21
  132. package/src/selector.js +31 -0
  133. package/src/server-context.js +252 -22
  134. package/src/skeleton.js +22 -12
  135. package/src/store.js +17 -31
  136. package/src/testing.js +389 -63
  137. package/src/vnode-adoption.js +48 -0
  138. package/src/vnode-renderer.js +114 -0
  139. package/testing.d.ts +81 -1
  140. package/ui.d.ts +20 -0
  141. package/dist/chunk-6YOUZ6T4.min.js +0 -1
  142. package/dist/chunk-FN6HXME3.min.js +0 -11
  143. package/dist/chunk-VKZY7JPN.min.js +0 -1
  144. package/src/agent-context.js +0 -127
  145. package/src/warnings.js +0 -193
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present ZVN DEV
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -15,51 +15,62 @@ npm install what-core
15
15
  ```js
16
16
  import { signal, computed, effect, batch, untrack } from 'what-core';
17
17
 
18
- const count = signal(0);
18
+ const count = signal(0, 'count');
19
19
 
20
20
  // Read
21
21
  count(); // 0
22
22
 
23
- // Write
23
+ // Write: count(5) and count((c) => c + 1) do the same
24
24
  count.set(5);
25
- count.set(c => c + 1);
25
+ count.set((c) => c + 1);
26
26
 
27
- // Derived value
27
+ // Derived value: recomputed when read after count changes
28
28
  const doubled = computed(() => count() * 2);
29
29
 
30
- // Side effects
30
+ // Side effect: runs now, then again after count or doubled changes. A write
31
+ // outside batch() runs the effects it affects on the next microtask.
31
32
  effect(() => {
32
- console.log('Count:', count());
33
+ console.log('Count:', count(), 'doubled:', doubled());
33
34
  });
34
35
 
35
- // Batch updates (effects run once at the end)
36
- batch(() => {
37
- a.set(1);
38
- b.set(2);
36
+ // Batch writes: the effects run once, synchronously, when the outermost batch
37
+ // ends; batch() returns what the function returns
38
+ const first = signal('Ada', 'first');
39
+ const last = signal('Lovelace', 'last');
40
+ const full = batch(() => {
41
+ first.set('Grace');
42
+ last.set('Hopper');
43
+ return `${first()} ${last()}`;
39
44
  });
40
45
 
41
46
  // Read without subscribing
42
- untrack(() => someSignal());
47
+ untrack(() => count());
43
48
  count.peek();
44
49
  ```
45
50
 
46
51
  ## Hooks
47
52
 
48
- React-compatible hooks backed by signals internally.
53
+ The hooks keep React's names and call shapes, but a component runs once, so
54
+ they hand you signals: `useState` and `useReducer` return `[accessor, setter]`,
55
+ `useMemo` returns an accessor (its dependency array is ignored), and
56
+ `useEffect` re-runs when a signal it reads changes, or with a dependency array
57
+ only for the accessors listed (`[count]`, never `[count()]`); `[]` runs it once
58
+ after mount. Call hooks in a component body.
49
59
 
50
- ```js
51
- import {
52
- useState, useEffect, useMemo, useCallback,
53
- useRef, useReducer, useContext, createContext,
54
- onMount, onCleanup,
55
- } from 'what-core';
56
-
57
- const [count, setCount] = useState(0);
58
-
59
- useEffect(() => {
60
- const id = setInterval(tick, 1000);
61
- return () => clearInterval(id);
62
- }, []);
60
+ ```jsx
61
+ import { useState, useEffect, useMemo } from 'what-core';
62
+
63
+ function Clock() {
64
+ const [seconds, setSeconds] = useState(0);
65
+ const minutes = useMemo(() => Math.floor(seconds() / 60));
66
+
67
+ useEffect(() => {
68
+ const id = setInterval(() => setSeconds((s) => s + 1), 1000);
69
+ return () => clearInterval(id);
70
+ }, []);
71
+
72
+ return <p>{minutes()}:{seconds() % 60}</p>;
73
+ }
63
74
  ```
64
75
 
65
76
  ## Components
@@ -81,34 +92,49 @@ mount(<Counter />, '#app');
81
92
 
82
93
  | Export path | Contents |
83
94
  |---|---|
84
- | `what-core` | Signals, hooks, components, store, forms, data fetching, animation, a11y, skeleton loaders |
85
- | `what-core/render` | Fine-grained rendering primitives (`template`, `insert`, `spread`, `delegateEvents`) |
95
+ | `what-core` | Signals, hooks, components and boundaries, context, store, `Head`, `mount`/`hydrate`, diagnostics |
96
+ | `what-core/render` | Fine-grained rendering primitives (`template`, `insert`, `spread`, `delegateEvents`, `on`) |
97
+ | `what-core/form` | Forms: `useForm`, `useField`, `rules`, resolvers, bound inputs |
98
+ | `what-core/data` | One query cache: `query`, `useQuery`, `useSWR`, `useInfiniteQuery`, `useFetch`, `invalidateQueries`, `invalidatePath` |
99
+ | `what-core/a11y` | Focus management, ARIA helpers, announcements |
100
+ | `what-core/ui` | Skeleton loaders and spinners |
101
+ | `what-core/motion` | Springs, tweens, `useTween`, gestures, CSS transitions |
102
+ | `what-core/dom` | The DOM read/write scheduler and DOM utilities |
103
+ | `what-core/internal` | What sibling packages (what-server, what-devtools) share with core; not for apps |
86
104
  | `what-core/jsx-runtime` | JSX automatic runtime |
87
105
  | `what-core/testing` | Test utilities |
88
106
 
107
+ `what-framework` re-exports each of these (except `internal`) under the same subpath.
108
+
89
109
  ## API Overview
90
110
 
91
- **Reactivity** -- `signal`, `computed`, `effect`, `batch`, `untrack`, `flushSync`, `createRoot`
111
+ **Reactivity** -- `signal`, `computed`, `effect`, `batch`, `untrack`, `flushSync`, `createRoot`, `getOwner`, `runWithOwner`, `createSelector`
112
+
113
+ **Async values** -- an async `computed`, `refresh`, `isPending`, `startTransition`, `useTransition`, `useOptimistic`, `use`, `settled` ([ASYNC.md](https://github.com/CelsianJs/what-framework/blob/main/docs/ASYNC.md))
114
+
115
+ **Actions** -- `useActionState`, `useFormStatus` (React 19's, on transitions; [DATA.md](https://github.com/CelsianJs/what-framework/blob/main/docs/DATA.md))
116
+
117
+ **Rendering** -- `h`, `Fragment`, `html`, `mount`, `hydrate`, `applyStreamedBoundaries`
92
118
 
93
- **Rendering** -- `Fragment`, `html`, `mount`, `template`, `insert`, `spread`, `delegateEvents`
119
+ **Hooks** -- `useState`, `useSignal`, `useComputed`, `useEffect`, `useMemo`, `useCallback`, `useRef`, `useContext`, `useReducer`, `useId`, `createContext`, `onMount`, `onCleanup`, `createResource`, `useLoaderData`
94
120
 
95
- **Hooks** -- `useState`, `useSignal`, `useComputed`, `useEffect`, `useMemo`, `useCallback`, `useRef`, `useContext`, `useReducer`, `createContext`, `onMount`, `onCleanup`, `createResource`
121
+ **Components** -- `memo`, `lazy`, `Suspense`, `ErrorBoundary`, `Show`, `For`, `Switch`, `Match`, `Portal`
96
122
 
97
- **Components** -- `memo`, `lazy`, `Suspense`, `ErrorBoundary`, `Show`, `For`, `Switch`, `Match`, `Island`, `Portal`
123
+ **Store** -- `createStore`, `derived`
98
124
 
99
- **Store** -- `createStore`, `derived`, `atom`
125
+ **Head** -- `Head`, `getResponse`
100
126
 
101
- **Data Fetching** -- `useSWR`, `useQuery`, `useInfiniteQuery`, `invalidateQueries`, `prefetchQuery`
127
+ **Diagnostics** -- `getDiagnostics`, `subscribeDiagnostics`, `clearDiagnostics`, `getErrorDefinition`, `WhatError`
102
128
 
103
- **Forms** -- `useForm`, `useField`, `rules`, `zodResolver`, `Input`, `Select`, `Checkbox`, `ErrorMessage`
129
+ **Data Fetching** (`what-core/data`) -- `query`, `useSWR`, `useQuery`, `useInfiniteQuery`, `useFetch`, `invalidateQueries`, `invalidatePath`, `prefetchQuery`, `setQueryData`, `getQueryData`, `clearCache` (docs/DATA.md)
104
130
 
105
- **Animation** -- `spring`, `tween`, `easings`, `useGesture`, `useTransition`
131
+ **Forms** (`what-core/form`) -- `useForm`, `useField`, `rules`, `zodResolver`, `Input`, `Select`, `Checkbox`, `ErrorMessage`
106
132
 
107
- **Accessibility** -- `useFocusTrap`, `FocusTrap`, `announce`, `SkipLink`, `useRovingTabIndex`, `VisuallyHidden`, `useId`
133
+ **Animation** (`what-core/motion`) -- `spring`, `tween`, `easings`, `useGesture`, `useTween`
108
134
 
109
- **Scheduler** -- `scheduleRead`, `scheduleWrite`, `measure`, `mutate`, `onResize`, `onIntersect`
135
+ **Accessibility** (`what-core/a11y`) -- `useFocusTrap`, `FocusTrap`, `announce`, `SkipLink`, `useRovingTabIndex`, `VisuallyHidden`, `useIds`
110
136
 
111
- **Head** -- `Head`, `clearHead`
137
+ **Scheduler** (`what-core/dom`) -- `scheduleRead`, `scheduleWrite`, `measure`, `mutate`, `onResize`, `onIntersect`, `clearHead`
112
138
 
113
139
  ## Links
114
140
 
package/a11y.d.ts ADDED
@@ -0,0 +1,128 @@
1
+ // what-core/a11y (what-framework/a11y): focus management, ARIA state helpers,
2
+ // announcements and keyboard helpers. useId is on the root entry.
3
+ import type { VNode, VNodeChild } from './index.js';
4
+
5
+ // --- Accessibility ---
6
+
7
+ export function useFocus(): {
8
+ current: () => Element | null;
9
+ focus: (element?: Element | null) => void;
10
+ blur: () => void;
11
+ };
12
+
13
+ export function useFocusRestore(): {
14
+ capture: (target?: Element | null) => void;
15
+ restore: (fallbackTarget?: Element | null) => void;
16
+ previous: () => Element | null;
17
+ };
18
+
19
+ export function useFocusTrap(containerRef: { current?: Element | null } | Element): {
20
+ activate: () => void | (() => void);
21
+ deactivate: () => void;
22
+ };
23
+
24
+ export function FocusTrap(props: { children?: VNodeChild; active?: boolean }): VNode;
25
+ export function announce(message: string, options?: { priority?: 'polite' | 'assertive'; timeout?: number }): void;
26
+ export function announceAssertive(message: string): void;
27
+ export function SkipLink(props: { href?: string; children?: VNodeChild }): VNode;
28
+
29
+ export function useAriaExpanded(initialExpanded?: boolean): {
30
+ expanded: () => boolean;
31
+ toggle: () => void;
32
+ open: () => void;
33
+ close: () => void;
34
+ buttonProps: () => Record<string, any>;
35
+ panelProps: () => Record<string, any>;
36
+ };
37
+
38
+ export function useAriaSelected<T = any>(initialSelected?: T): {
39
+ selected: () => T;
40
+ select: (value: T) => void;
41
+ isSelected: (value: T) => boolean;
42
+ itemProps: (value: T) => Record<string, any>;
43
+ };
44
+
45
+ export function useAriaChecked(initialChecked?: boolean): {
46
+ checked: () => boolean;
47
+ toggle: () => void;
48
+ set: (value: boolean) => void;
49
+ checkboxProps: () => Record<string, any>;
50
+ };
51
+
52
+ export interface RovingTabIndexOptions {
53
+ /**
54
+ * Container role, emitted by containerProps(). The hook emits NO role by
55
+ * default: roving tabindex is the shared keyboard mechanic of toolbars,
56
+ * menus, trees, grids, tablists, radiogroups and listboxes, and a default
57
+ * spread last would silently overwrite the role the caller wrote beside it.
58
+ */
59
+ role?: string;
60
+ }
61
+
62
+ /**
63
+ * Props for one roving item. `ref` is the item's REGISTRATION (the hook holds
64
+ * the node through it and cannot move focus without it), so a `ref` passed via
65
+ * `overrides` is chained rather than replaced. `tabIndex` is an accessor, not a
66
+ * number: exactly one item is tabbable at a time and which one changes as focus
67
+ * roves, so a resolved value could not survive the spread.
68
+ */
69
+ export interface RovingItemProps {
70
+ ref: { current: Element | null };
71
+ tabIndex: () => number;
72
+ onKeyDown: (e: KeyboardEvent) => void;
73
+ onFocus: (e: Event) => void;
74
+ [prop: string]: any;
75
+ }
76
+
77
+ export function useRovingTabIndex(
78
+ itemCountOrSignal: number | (() => number),
79
+ options?: RovingTabIndexOptions,
80
+ ): {
81
+ /** Active index, clamped to the current count so the group is never untabbable. */
82
+ focusIndex: () => number;
83
+ /**
84
+ * Set the active index. Out-of-range indexes are REFUSED, not clamped. Moves
85
+ * real focus only when the group already owns it, so syncing from application
86
+ * state cannot steal focus from elsewhere on the page.
87
+ */
88
+ setFocusIndex: (index: number) => void;
89
+ /**
90
+ * Explicitly move focus to an item (a menu focusing its first item on open).
91
+ * Returns the element it focused, or null when the index is out of range or
92
+ * the item is not in the DOM.
93
+ */
94
+ focusItem: (index: number) => Element | null;
95
+ getItemProps: (index: number, overrides?: Record<string, any>) => RovingItemProps;
96
+ containerProps: (overrides?: Record<string, any>) => Record<string, any>;
97
+ };
98
+
99
+ export function VisuallyHidden(props: { children?: VNodeChild; as?: string }): VNode;
100
+ export function LiveRegion(props: { children?: VNodeChild; priority?: 'polite' | 'assertive'; atomic?: boolean }): VNode;
101
+ export function useIds(count: number, prefix?: string): string[];
102
+ export function useDescribedBy(description: VNodeChild): {
103
+ descriptionId: string;
104
+ descriptionProps: () => Record<string, any>;
105
+ describedByProps: () => Record<string, any>;
106
+ Description: () => VNode;
107
+ };
108
+ export function useLabelledBy(label: VNodeChild): {
109
+ labelId: string;
110
+ labelProps: () => Record<string, any>;
111
+ labelledByProps: () => Record<string, any>;
112
+ };
113
+
114
+ export const Keys: {
115
+ Enter: 'Enter';
116
+ Space: ' ';
117
+ Escape: 'Escape';
118
+ ArrowUp: 'ArrowUp';
119
+ ArrowDown: 'ArrowDown';
120
+ ArrowLeft: 'ArrowLeft';
121
+ ArrowRight: 'ArrowRight';
122
+ Home: 'Home';
123
+ End: 'End';
124
+ Tab: 'Tab';
125
+ };
126
+
127
+ export function onKey(key: string, handler: (e: KeyboardEvent) => void): (e: KeyboardEvent) => void;
128
+ export function onKeys(keys: string[], handler: (e: KeyboardEvent) => void): (e: KeyboardEvent) => void;
package/data.d.ts ADDED
@@ -0,0 +1,294 @@
1
+ // what-core/data (what-framework/data): one query cache on async values, the
2
+ // signal-native query() that reads it, the React-ecosystem hooks over it, and
3
+ // the cache operations (docs/DATA.md).
4
+
5
+ import type { AsyncComputed } from './index.js';
6
+
7
+ /**
8
+ * A cache key. An array key is joined into one normalized string
9
+ * (`['todos', 1]` is `"todos:1"`), so an array and its normalization address
10
+ * the same entry everywhere a key is accepted, and a string key shares the
11
+ * namespace: `query('todos')`, `useSWR('todos')` and
12
+ * `useQuery({ queryKey: ['todos'] })` are one entry.
13
+ */
14
+ export type QueryKey = string | readonly unknown[];
15
+
16
+ /** A key, or a function of signals that returns one; null, false or undefined: no key (nothing is fetched). */
17
+ export type QueryKeySource<K extends QueryKey = QueryKey> = K | null | false | undefined | (() => K | null | false | undefined);
18
+
19
+ export interface QueryOptions<T> {
20
+ /** How long (ms) a landed value is fresh: a reader attaching within it is answered from the cache. Default 0. */
21
+ staleTime?: number;
22
+ /** How long (ms) an entry nothing reads is kept before it is dropped. Default 5 minutes. */
23
+ gcTime?: number;
24
+ /** Total attempts for a failing fetch (a number), or whether to try again. Default 1: no retry. */
25
+ retry?: number | boolean | ((failures: number, error: unknown) => boolean);
26
+ retryDelay?: (attempt: number) => number;
27
+ /** The entry's value before the first fetch lands (or a function returning it). */
28
+ initialData?: T | (() => T);
29
+ }
30
+
31
+ /**
32
+ * The signal-native read of the cache: an async value for the entry `key`
33
+ * names now. `key` may be a function of signals; when it moves, the value
34
+ * fetches the new key's entry (or shows it at once, if it is cached and
35
+ * fresh) and keeps the old value meanwhile (`pending()` is true). Reading it
36
+ * before the first value lands holds the reader, or suspends its
37
+ * `<Suspense>`; `refresh(q)` fetches the entry again; a server render sends
38
+ * the value in the hydration data channel, under the key, and the hydrating
39
+ * client adopts it with no request. Readers of one key share one request.
40
+ */
41
+ export function query<T, K extends QueryKey = QueryKey>(
42
+ key: QueryKeySource<K>,
43
+ fetcher: (key: K, ctx: { signal: AbortSignal }) => Promise<T> | T,
44
+ options?: QueryOptions<T>,
45
+ ): AsyncComputed<T>;
46
+
47
+ // --- The hooks: React-ecosystem shapes over the same cache ---
48
+
49
+ export function useFetch<T = any>(url: string | null | (() => string | null | undefined), options?: {
50
+ method?: string;
51
+ body?: unknown;
52
+ headers?: Record<string, string>;
53
+ /** Applied to the parsed JSON before it is cached. */
54
+ transform?: (data: any) => T;
55
+ /** What data() is before the first response. Default null. */
56
+ initialData?: T | null;
57
+ /** The fetch implementation. Default globalThis.fetch. */
58
+ fetch?: typeof fetch;
59
+ }): {
60
+ /** null (or initialData) until the first response lands. */
61
+ data: () => T | null;
62
+ error: () => any;
63
+ isLoading: () => boolean;
64
+ /** Fetches again; never rejects (a failure shows in error()). */
65
+ refetch: () => Promise<void>;
66
+ mutate: (newData: T) => void;
67
+ };
68
+
69
+ export interface SWROptions<T> {
70
+ revalidateOnFocus?: boolean;
71
+ revalidateOnReconnect?: boolean;
72
+ /** Poll every n ms (0: never). */
73
+ refreshInterval?: number;
74
+ /** A fetch within this many ms of the last one answers a new reader, a focus or a reconnect. Default 2000. */
75
+ dedupingInterval?: number;
76
+ /** What data() is while the cache has nothing for the key (not stored in the cache). */
77
+ fallbackData?: T;
78
+ /**
79
+ * Structural sharing (TanStack Query's default): a response equal to the
80
+ * cached data keeps the cached references, and a changed one keeps every
81
+ * part it did not change, so a keyed list sees the same row objects after
82
+ * a refetch. A function picks what is kept from (cached, response); false
83
+ * takes every response as it arrives. Default true.
84
+ */
85
+ structuralSharing?: boolean | ((prev: T | undefined, next: T) => T);
86
+ /** Show the previous key's data while a new key loads. */
87
+ keepPreviousData?: boolean;
88
+ /** Called when a fetch this reader started succeeds. */
89
+ onSuccess?: (data: T, key: any) => void;
90
+ onError?: (error: any, key: any) => void;
91
+ }
92
+
93
+ /**
94
+ * SWR's shape. A null, false or throwing key (or a function returning one)
95
+ * pauses it. `fetcher(key, { signal })` receives the key as written.
96
+ */
97
+ export function useSWR<T = any, K = any>(
98
+ key: K | null | false | (() => K | null | false | undefined),
99
+ fetcher: (key: K, ctx: { signal: AbortSignal }) => Promise<T> | T,
100
+ options?: SWROptions<T>,
101
+ ): {
102
+ /** The cached value, or fallbackData, or null. */
103
+ data: () => T | null;
104
+ error: () => any;
105
+ /** No data yet, and fetching. */
106
+ isLoading: () => boolean;
107
+ /** Fetching. */
108
+ isValidating: () => boolean;
109
+ /** Put data in the cache for every reader of the key, then (by default) fetch again. mutate() alone revalidates. */
110
+ mutate: (newData?: T | ((prev: T | null) => T), shouldRevalidate?: boolean) => Promise<T | void>;
111
+ revalidate: () => Promise<T | void>;
112
+ };
113
+
114
+ /**
115
+ * 'idle' is a real state: nothing cached and nothing in flight (a disabled
116
+ * query). Reporting it as loading is what renders a spinner that never comes
117
+ * down.
118
+ */
119
+ export type QueryStatus = 'idle' | 'loading' | 'success' | 'error';
120
+ /** Whether a request is on the wire, independent of whether data exists. */
121
+ export type FetchStatus = 'idle' | 'fetching';
122
+
123
+ export interface UseQueryOptions<T, D = T> {
124
+ /** The key. A function of signals moves the query to the key it returns. */
125
+ queryKey: QueryKeySource;
126
+ /**
127
+ * Fetches the key's value. `queryKey` is this query's own key as it wrote it
128
+ * (as an array), even when another spelling of it (`'todos:1'` for
129
+ * `['todos', 1]`) created the cache entry they share.
130
+ */
131
+ queryFn: (ctx: { queryKey: readonly unknown[]; signal: AbortSignal }) => Promise<T> | T;
132
+ /** A boolean, a signal or a thunk: automatic fetching starts when it turns true. Explicit refetch() is never gated. */
133
+ enabled?: boolean | (() => boolean);
134
+ /** Default 0. */
135
+ staleTime?: number;
136
+ /** How long an unread entry is kept. Default 5 minutes. `cacheTime` is the same option. */
137
+ gcTime?: number;
138
+ cacheTime?: number;
139
+ refetchOnWindowFocus?: boolean;
140
+ refetchOnReconnect?: boolean;
141
+ refetchInterval?: number | false;
142
+ /** Total attempts for a failing fetch. Default 3. */
143
+ retry?: number | boolean | ((failures: number, error: unknown) => boolean);
144
+ retryDelay?: (attempt: number) => number;
145
+ /** Called when a fetch this query started lands. */
146
+ onSuccess?: (data: T) => void;
147
+ onError?: (error: any) => void;
148
+ onSettled?: (data: T | null, error: any) => void;
149
+ select?: (data: T) => D;
150
+ /** Shown while the entry has no data; a function receives the previous key's data. */
151
+ placeholderData?: D | ((previous: D | undefined) => D | undefined);
152
+ /** Show the previous key's data while a new key loads. */
153
+ keepPreviousData?: boolean;
154
+ initialData?: T | (() => T);
155
+ initialDataUpdatedAt?: number;
156
+ /**
157
+ * Structural sharing (TanStack Query's default): a response equal to the
158
+ * cached data keeps the cached references, and a changed one keeps every
159
+ * part it did not change, so a keyed list sees the same row objects after
160
+ * a refetch. A function picks what is kept from (cached, response); false
161
+ * takes every response as it arrives. Default true.
162
+ */
163
+ structuralSharing?: boolean | ((prev: T | undefined, next: T) => T);
164
+ }
165
+
166
+ /** TanStack Query's shape. data() never suspends; for a value that suspends, use query(). */
167
+ export function useQuery<T = any, D = T>(options: UseQueryOptions<T, D>): {
168
+ data: () => D | undefined;
169
+ error: () => any;
170
+ status: () => QueryStatus;
171
+ fetchStatus: () => FetchStatus;
172
+ isLoading: () => boolean;
173
+ isFetching: () => boolean;
174
+ isError: () => boolean;
175
+ isSuccess: () => boolean;
176
+ isIdle: () => boolean;
177
+ /** Whether data() is placeholderData or the previous key's data. */
178
+ isPlaceholderData: () => boolean;
179
+ /** Whether the `enabled` gate is open. */
180
+ isEnabled: () => boolean;
181
+ /** When the data landed (ms since the epoch), 0 before. */
182
+ dataUpdatedAt: () => number;
183
+ /** Fetch now: never gated by `enabled`, never answered from the freshness window. Resolves with the data. */
184
+ refetch: () => Promise<T | undefined>;
185
+ };
186
+
187
+ /** Pages, plus the param each was fetched with. `pageParams[i]` names `pages[i]`. */
188
+ export interface InfiniteData<T> {
189
+ pages: T[];
190
+ pageParams: unknown[];
191
+ }
192
+
193
+ /**
194
+ * TanStack Query's shape. `data()` is the page CONTAINER, not a flat array:
195
+ * the rows are in `data().pages`. The pages are one cache entry; invalidating
196
+ * its key refetches page one and replaces the list.
197
+ */
198
+ export function useInfiniteQuery<T = any>(options: {
199
+ queryKey: QueryKeySource;
200
+ queryFn: (ctx: { queryKey: readonly unknown[]; pageParam: any; signal: AbortSignal }) => Promise<T> | T;
201
+ getNextPageParam?: (lastPage: T, pages: T[]) => unknown;
202
+ getPreviousPageParam?: (firstPage: T, pages: T[]) => unknown;
203
+ initialPageParam?: unknown;
204
+ enabled?: boolean | (() => boolean);
205
+ staleTime?: number;
206
+ gcTime?: number;
207
+ cacheTime?: number;
208
+ /** Default false: a focus refetch replaces the list with page one. */
209
+ refetchOnWindowFocus?: boolean;
210
+ refetchInterval?: number | false;
211
+ select?: (data: InfiniteData<T>) => any;
212
+ retry?: number | boolean | ((failures: number, error: unknown) => boolean);
213
+ retryDelay?: (attempt: number) => number;
214
+ /** Called with the page a fetch this query started returned. */
215
+ onSuccess?: (page: T) => void;
216
+ onError?: (error: any) => void;
217
+ onSettled?: (page: T | null, error: any) => void;
218
+ }): {
219
+ data: () => InfiniteData<T>;
220
+ error: () => any;
221
+ status: () => QueryStatus;
222
+ isLoading: () => boolean;
223
+ isError: () => boolean;
224
+ isSuccess: () => boolean;
225
+ isIdle: () => boolean;
226
+ isFetching: () => boolean;
227
+ isEnabled: () => boolean;
228
+ hasNextPage: () => boolean;
229
+ hasPreviousPage: () => boolean;
230
+ isFetchingNextPage: () => boolean;
231
+ isFetchingPreviousPage: () => boolean;
232
+ /** An empty list's next page is the first page. Resolves with the page fetched. */
233
+ fetchNextPage: () => Promise<T | undefined>;
234
+ fetchPreviousPage: () => Promise<T | undefined>;
235
+ refetch: () => Promise<T | undefined>;
236
+ };
237
+
238
+ // --- The cache ---
239
+
240
+ /**
241
+ * Mark the entries `keyOrPredicate` names stale, and fetch again those
242
+ * something shows (inside a transition, the refetch joins it). An array key
243
+ * is a PREFIX unless `exact` is set: invalidateQueries(['todos']) also
244
+ * invalidates ['todos', 1]. A predicate receives each normalized key. `hard`
245
+ * empties the entries first (a request already in flight still refills
246
+ * them). An entry refetches as the active reader that attached last (its
247
+ * fetcher, key and callbacks), as TanStack Query uses its last observer's
248
+ * options. Resolves once the refetches have landed; never rejects.
249
+ */
250
+ export function invalidateQueries(
251
+ keyOrPredicate: QueryKey | ((key: string) => boolean),
252
+ options?: { exact?: boolean; hard?: boolean },
253
+ ): Promise<void>;
254
+
255
+ /**
256
+ * The client side of a revalidated path: the entries read on `path` (a
257
+ * route's preload data, and every query read while the page was at that
258
+ * path) are invalidated, and the onRevalidate callbacks for it run. A server
259
+ * action with `revalidate: [path]` calls it. With what-router, a page's path
260
+ * is as the app writes it, without the base path and a trailing slash.
261
+ * Resolves once the refetches have landed.
262
+ */
263
+ export function invalidatePath(path: string): Promise<void>;
264
+
265
+ /** Call `callback` whenever invalidatePath(path) runs. Returns the unsubscribe. */
266
+ export function onRevalidate(path: string, callback: () => void): () => void;
267
+
268
+ /**
269
+ * Fetch `key` into the cache unless it holds a value fresher than `staleTime`,
270
+ * and resolve with it. The fetch calls `fetcher` with `key` as written, even
271
+ * while other readers of the entry are attached, or joins a fetch already in
272
+ * flight for the entry. It runs to completion and writes the cache even if
273
+ * every reader of the key unmounts meanwhile; a newer fetch of the key
274
+ * supersedes it, and it resolves with that one's value. Rejects with a failed
275
+ * fetch's error.
276
+ */
277
+ export function prefetchQuery<T = any, K extends QueryKey = QueryKey>(
278
+ key: K,
279
+ fetcher: (key: K, ctx: { signal: AbortSignal }) => Promise<T> | T,
280
+ options?: { staleTime?: number; retry?: number },
281
+ ): Promise<T>;
282
+
283
+ /** Put `updater` (a value, or a function of the current value) in the cache now, for every reader of the key. */
284
+ export function setQueryData<T = any>(key: QueryKey, updater: T | ((prev: T | undefined) => T)): void;
285
+
286
+ /** `undefined` for a key with nothing cached; `null` for one emptied by a hard invalidation. */
287
+ export function getQueryData<T = any>(key: QueryKey): T | null | undefined;
288
+
289
+ /**
290
+ * Empty the cache (logout): what is in flight is dropped, entries something
291
+ * shows stay attached to their readers, empty (a mounted query() fetches
292
+ * again), and the page's server data is not adopted again.
293
+ */
294
+ export function clearCache(): void;