@softistx/riva 0.0.0-stage → 0.1.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 (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/dist/batch.d.ts +5 -0
  4. package/dist/batch.d.ts.map +1 -0
  5. package/dist/chunks/index-2g2s3y31.js +58 -0
  6. package/dist/chunks/index-2g2s3y31.js.map +10 -0
  7. package/dist/chunks/index-46sbdyt0.js +84 -0
  8. package/dist/chunks/index-46sbdyt0.js.map +12 -0
  9. package/dist/chunks/index-5xnfwj57.js +21 -0
  10. package/dist/chunks/index-5xnfwj57.js.map +10 -0
  11. package/dist/chunks/index-asz1gnp1.js +50 -0
  12. package/dist/chunks/index-asz1gnp1.js.map +10 -0
  13. package/dist/chunks/index-e4vzsfy1.js +253 -0
  14. package/dist/chunks/index-e4vzsfy1.js.map +11 -0
  15. package/dist/chunks/index-tn8ankny.js +137 -0
  16. package/dist/chunks/index-tn8ankny.js.map +10 -0
  17. package/dist/chunks/index-vz93xwnj.js +35 -0
  18. package/dist/chunks/index-vz93xwnj.js.map +10 -0
  19. package/dist/chunks/index-y6bzw104.js +53 -0
  20. package/dist/chunks/index-y6bzw104.js.map +11 -0
  21. package/dist/client.d.ts +48 -0
  22. package/dist/client.d.ts.map +1 -0
  23. package/dist/computed.d.ts +21 -0
  24. package/dist/computed.d.ts.map +1 -0
  25. package/dist/data/index.d.ts +19 -0
  26. package/dist/data/index.d.ts.map +1 -0
  27. package/dist/data/index.js +60 -0
  28. package/dist/data/index.js.map +10 -0
  29. package/dist/data/types.d.ts +12 -0
  30. package/dist/data/types.d.ts.map +1 -0
  31. package/dist/duration.d.ts +5 -0
  32. package/dist/duration.d.ts.map +1 -0
  33. package/dist/effect.d.ts +5 -0
  34. package/dist/effect.d.ts.map +1 -0
  35. package/dist/entities/api.d.ts +18 -0
  36. package/dist/entities/api.d.ts.map +1 -0
  37. package/dist/entities/denormalize.d.ts +13 -0
  38. package/dist/entities/denormalize.d.ts.map +1 -0
  39. package/dist/entities/identity.d.ts +11 -0
  40. package/dist/entities/identity.d.ts.map +1 -0
  41. package/dist/entities/index.d.ts +6 -0
  42. package/dist/entities/index.d.ts.map +1 -0
  43. package/dist/entities/index.js +414 -0
  44. package/dist/entities/index.js.map +16 -0
  45. package/dist/entities/json.d.ts +15 -0
  46. package/dist/entities/json.d.ts.map +1 -0
  47. package/dist/entities/normalize.d.ts +11 -0
  48. package/dist/entities/normalize.d.ts.map +1 -0
  49. package/dist/entities/policy.d.ts +41 -0
  50. package/dist/entities/policy.d.ts.map +1 -0
  51. package/dist/entities/store.d.ts +47 -0
  52. package/dist/entities/store.d.ts.map +1 -0
  53. package/dist/env.d.ts +15 -0
  54. package/dist/env.d.ts.map +1 -0
  55. package/dist/errors.d.ts +38 -0
  56. package/dist/errors.d.ts.map +1 -0
  57. package/dist/flush.d.ts +11 -0
  58. package/dist/flush.d.ts.map +1 -0
  59. package/dist/graph.d.ts +47 -0
  60. package/dist/graph.d.ts.map +1 -0
  61. package/dist/index.d.ts +14 -0
  62. package/dist/index.d.ts.map +1 -0
  63. package/dist/index.js +502 -0
  64. package/dist/index.js.map +18 -0
  65. package/dist/infinite/index.d.ts +3 -0
  66. package/dist/infinite/index.d.ts.map +1 -0
  67. package/dist/infinite/index.js +207 -0
  68. package/dist/infinite/index.js.map +13 -0
  69. package/dist/infinite/infinite.d.ts +8 -0
  70. package/dist/infinite/infinite.d.ts.map +1 -0
  71. package/dist/infinite/more.d.ts +19 -0
  72. package/dist/infinite/more.d.ts.map +1 -0
  73. package/dist/infinite/refetch.d.ts +16 -0
  74. package/dist/infinite/refetch.d.ts.map +1 -0
  75. package/dist/infinite/slots.d.ts +22 -0
  76. package/dist/infinite/slots.d.ts.map +1 -0
  77. package/dist/infinite/types.d.ts +68 -0
  78. package/dist/infinite/types.d.ts.map +1 -0
  79. package/dist/key.d.ts +3 -0
  80. package/dist/key.d.ts.map +1 -0
  81. package/dist/mutation-run.d.ts +5 -0
  82. package/dist/mutation-run.d.ts.map +1 -0
  83. package/dist/mutation.d.ts +53 -0
  84. package/dist/mutation.d.ts.map +1 -0
  85. package/dist/query-cache.d.ts +33 -0
  86. package/dist/query-cache.d.ts.map +1 -0
  87. package/dist/query-entry.d.ts +85 -0
  88. package/dist/query-entry.d.ts.map +1 -0
  89. package/dist/query-observe.d.ts +9 -0
  90. package/dist/query-observe.d.ts.map +1 -0
  91. package/dist/query-run.d.ts +12 -0
  92. package/dist/query-run.d.ts.map +1 -0
  93. package/dist/query.d.ts +100 -0
  94. package/dist/query.d.ts.map +1 -0
  95. package/dist/retry.d.ts +18 -0
  96. package/dist/retry.d.ts.map +1 -0
  97. package/dist/scope.d.ts +16 -0
  98. package/dist/scope.d.ts.map +1 -0
  99. package/dist/signal.d.ts +22 -0
  100. package/dist/signal.d.ts.map +1 -0
  101. package/dist/ssr/codec.d.ts +10 -0
  102. package/dist/ssr/codec.d.ts.map +1 -0
  103. package/dist/ssr/dehydrate.d.ts +37 -0
  104. package/dist/ssr/dehydrate.d.ts.map +1 -0
  105. package/dist/ssr/hydrate.d.ts +20 -0
  106. package/dist/ssr/hydrate.d.ts.map +1 -0
  107. package/dist/ssr/index.d.ts +5 -0
  108. package/dist/ssr/index.d.ts.map +1 -0
  109. package/dist/ssr/index.js +136 -0
  110. package/dist/ssr/index.js.map +11 -0
  111. package/dist/store/def.d.ts +31 -0
  112. package/dist/store/def.d.ts.map +1 -0
  113. package/dist/store/index.d.ts +3 -0
  114. package/dist/store/index.d.ts.map +1 -0
  115. package/dist/store/index.js +215 -0
  116. package/dist/store/index.js.map +14 -0
  117. package/dist/store/instance.d.ts +14 -0
  118. package/dist/store/instance.d.ts.map +1 -0
  119. package/dist/store/run.d.ts +12 -0
  120. package/dist/store/run.d.ts.map +1 -0
  121. package/dist/store/store.d.ts +10 -0
  122. package/dist/store/store.d.ts.map +1 -0
  123. package/dist/store/types.d.ts +70 -0
  124. package/dist/store/types.d.ts.map +1 -0
  125. package/dist/store/view.d.ts +10 -0
  126. package/dist/store/view.d.ts.map +1 -0
  127. package/docs/README.md +19 -0
  128. package/docs/guide/data.md +36 -0
  129. package/docs/guide/entities.md +90 -0
  130. package/docs/guide/errors.md +31 -0
  131. package/docs/guide/infinite.md +62 -0
  132. package/docs/guide/mutations.md +73 -0
  133. package/docs/guide/queries.md +93 -0
  134. package/docs/guide/signals.md +72 -0
  135. package/docs/guide/ssr.md +65 -0
  136. package/docs/guide/store.md +88 -0
  137. package/docs/troubleshooting.md +343 -0
  138. package/package.json +84 -5
@@ -0,0 +1,62 @@
1
+ # Infinite lists: `@softistx/riva/infinite`
2
+
3
+ A cursor-paginated list is a query whose data is the pages loaded so far. It reads like any query (`client.get`, `subscribe`, `ensure`, `invalidate`, `setData`, staleness, `gcTime`, `retry`, `cache`) and adds `fetchNext` and `fetchPrevious`. The default page shape is a Relay connection (`edges[].node`, `pageInfo` with `hasNextPage`, `hasPreviousPage`, `startCursor`, `endCursor`).
4
+
5
+ ```ts
6
+ import { createRivaClient } from '@softistx/riva';
7
+ import { entities } from '@softistx/riva/entities';
8
+ import { type Connection, infinite } from '@softistx/riva/infinite';
9
+
10
+ type Patient = { __typename: 'Patient'; id: string; name: string };
11
+ type Page = { patients: Connection<Patient> };
12
+
13
+ const feed = infinite({
14
+ id: 'patientsFeed',
15
+ cache: entities(), // every page is normalized: a node edit shows everywhere
16
+ staleTime: '30s',
17
+ fetch: async (v: { search: string; after?: string }, { signal }): Promise<Page> =>
18
+ (await fetch(`/api/patients?search=${v.search}&after=${v.after ?? ''}`, { signal })).json(),
19
+ connection: (page) => page.patients,
20
+ // cursor: { after: 'cursor' }, // when the variable is not named `after` (and `before`)
21
+ });
22
+
23
+ const client = createRivaClient();
24
+ await feed.ensure(client, { search: 'a' }); // the first page
25
+ await feed.fetchNext(client, { search: 'a' }); // appends the next page
26
+ await feed.fetchPrevious(client, { search: 'a' }); // prepends the previous page
27
+
28
+ const s = client.get(feed, { search: 'a' });
29
+ s.data?.nodes; // every loaded node, flattened (memoized per data)
30
+ s.data?.pages; // the pages as fetched
31
+ s.hasNext; s.hasPrevious; s.isFetchingNext; s.isFetchingPrevious;
32
+ ```
33
+
34
+ ## Options
35
+
36
+ Every `query` option applies (`id`, `staleTime`, `gcTime`, `retry`, `retryDelay`, `refetchOnFocus`, `refetchOnReconnect`, `refetchEvery`, `cache`; see [queries](./queries.md)), plus:
37
+
38
+ | Option | Default | Effect |
39
+ | --- | --- | --- |
40
+ | `fetch(vars, ctx)` | required | Gets the caller's variables plus the cursor; returns one page. |
41
+ | `connection(page)` | required | Reads `{ edges, pageInfo }` out of a page. |
42
+ | `cursor` | `{ after: 'after', before: 'before' }` | Names the cursor variables of `fetch`. Both must be declared in the variables. |
43
+
44
+ `Page` and `Node` are inferred from `fetch` and `connection`. The caller's variables are those of `fetch` without `after` and `before`; the library adds the cursor and strips a cursor variable the caller passes.
45
+
46
+ ## The state
47
+
48
+ `InfiniteState` is a `QueryState` with `data` (`{ nodes, pages }`), `hasNext`, `hasPrevious`, `isFetchingNext` and `isFetchingPrevious`.
49
+
50
+ ## How it behaves
51
+
52
+ - `fetchNext` and `fetchPrevious` return one promise while in flight (deduped), and resolve at once when there is no next or previous page, or no page loaded yet. They use `retry` and `retryDelay`. An error keeps the loaded pages and sets `status: 'error'` and `error`; the next successful page clears it. `cancel` aborts them as well as a refetch.
53
+ - A refetch (stale, `invalidate`, focus) re-runs every loaded page in order, from the first page's cursor, taking each next cursor from the fresh page before it, so inserted or removed items never skip or repeat a node. It stops when `hasNextPage` turns false (a list that shrank loads fewer pages) and swaps all pages in as one change; an error or abort keeps the old pages.
54
+ - `fetchNext` and `fetchPrevious` wait for a refetch in flight, then read the cursor from the fresh pages. A page that arrives after the list moved under it is not mixed in: it is fetched again from the new cursor. An `invalidate` made meanwhile is kept.
55
+ - With `cache: entities()`, nodes are shared with every other query. `writeEntity` and `invalidateEntity` reach the feed like any query.
56
+ - Pagination is forward-only for servers that do not take `before`: `hasPrevious` then stays false.
57
+
58
+ ## Writing to a feed
59
+
60
+ `setData` and `tx.set` on a feed take the stored shape, `{ pages, params }`, where `params[i]` is the cursor page `i` was fetched with (`{}` for the first, `{ after }` going forward, `{ before }` going back); `nodes` and the flags are derived and never stored. An optimistic edit of a node belongs in the entity layer, an added or removed node in `tx.set` on the pages.
61
+
62
+ Exports: `infinite`; types `Infinite`, `InfiniteOptions`, `InfiniteData`, `InfiniteList`, `InfiniteState`, `Connection`, `Edge`, `PageInfo`, `PageParam`, `Cursors`, `FeedVars`.
@@ -0,0 +1,73 @@
1
+ # Mutations
2
+
3
+ `mutation({ id, run, optimistic?, updates?, invalidates?, cache?, retry?, retryDelay? })` sends a change and shows its expected result at once. The definition is stateless; `run(client, vars, { signal? })` resolves with the server data, or rejects with the error after the rollback.
4
+
5
+ ```ts
6
+ import { at, createRivaClient, mutation, query } from '@softistx/riva';
7
+
8
+ const todos = query({ id: 'todos', fetch: async () => (await fetch('/api/todos')).json() as Promise<string[]> });
9
+
10
+ const addTodo = mutation<string, string>({
11
+ id: 'addTodo',
12
+ run: async (title, { signal }) =>
13
+ (await fetch('/api/todos', { method: 'POST', body: title, signal })).text(),
14
+ // shown at once, over the committed data; the updater gets the value below
15
+ optimistic: (title, tx) => tx.set(todos, undefined, (prev) => [...(prev ?? []), title]),
16
+ // on success: write the server result into the committed data...
17
+ updates: (tx, saved) => tx.set(todos, undefined, (prev) => [...(prev ?? []), saved]),
18
+ // ...and/or mark queries stale (observed ones refetch)
19
+ invalidates: [todos], // or [at(todos, vars)] for one entry, or (data, vars) => [...]
20
+ });
21
+
22
+ const client = createRivaClient();
23
+ await addTodo.run(client, 'Buy milk'); // rejects, with the layer dropped, on failure
24
+ ```
25
+
26
+ ## Options
27
+
28
+ | Option | Default | Effect |
29
+ | --- | --- | --- |
30
+ | `id` | required | Identifies the definition. |
31
+ | `run(vars, { signal })` | required | Sends the change; returns the server data. |
32
+ | `optimistic(vars, tx)` | none | Shows the expected result at once. Returns data for the entity layer (with `cache`), or writes with `tx.set`. |
33
+ | `updates(tx, data, vars)` | none | On success, writes the committed data. |
34
+ | `invalidates` | none | `[query]`, `[at(query, vars)]` or `(data, vars) => [...]`: queries to mark stale on success. |
35
+ | `cache` | none | A policy with `layer` and `commit` (`entities()` has both): normalizes the optimistic data and the result. |
36
+ | `retry` | `0` | A count, or `(failures, error) => boolean`. No timer is armed on the server. |
37
+ | `retryDelay` | `min(1000 * 2 ** failures, 30000)` | `(failures) => ms`. |
38
+
39
+ `tx.set(query, vars, dataOrUpdater)` writes one entry. In `optimistic` it adds a layer over the query's data, dropped when the mutation settles (the updater gets the value below). In `updates` it writes the committed data (the updater gets the committed value). `at(query, vars)` names one entry for `invalidates`, with `vars` checked against the query.
40
+
41
+ ## With the normalized cache
42
+
43
+ ```ts
44
+ import { entities } from '@softistx/riva/entities';
45
+
46
+ type Patient = { __typename: 'Patient'; id: string; name: string };
47
+
48
+ const renamePatient = mutation<{ id: string; name: string }, Patient>({
49
+ id: 'renamePatient',
50
+ cache: entities(),
51
+ run: async (v) => (await fetch(`/api/patients/${v.id}`, { method: 'PATCH', body: JSON.stringify(v) })).json(),
52
+ optimistic: (v) => ({ __typename: 'Patient', id: v.id, name: v.name }), // every query reading Patient:<id> shows it
53
+ });
54
+ ```
55
+
56
+ ## How it behaves
57
+
58
+ - **The layer.** While a mutation is in flight its optimistic writes sit above the committed cache. `client.get`, `subscribe` and computeds see the committed data with the layers applied in start order; the committed data is never mutated. A keyed layer never changes `status` or `isFetching`. A refetch that lands meanwhile updates the committed value and the layer stays on top.
59
+ - **Rollback.** On failure (after the retries, on an abort, or when the commit is refused with `RIVA_CACHE`) the layers are dropped and readers go back to the value below. Nothing else runs: no `updates`, no `invalidates`. A throwing `invalidates` function counts as a failure.
60
+ - **Success.** In one batch: the result is committed through `cache`, the layers are dropped, `updates` writes the committed data, then `invalidates` runs. If `updates` throws, the server result stays committed, the layers are dropped, the invalidations still run, and `run` rejects with the thrown error.
61
+ - **Order.** Mutations on one client resolve in start order. If B (started after A) succeeds first, its layer stays visible and its commit waits until A settles. If A fails, A's layer is dropped at once and B's still applies. Clients never share the order.
62
+ - **Abort.** `signal` aborts with `RivaAbortError` and rolls back, also while the mutation waits for an earlier one.
63
+ - **Server.** `run` works in a React Router action: layers are applied there too but nobody observes them.
64
+
65
+ ## Traps
66
+
67
+ - `optimistic` returning data only reaches the entities when `cache` has a `layer` method; without `cache`, write with `tx.set`.
68
+ - `tx.set` targets one entry: use the variables the reader uses.
69
+ - A data value that is itself a function is taken as an updater.
70
+ - After success the layer is dropped: without `updates`, `invalidates` or `cache`, nothing replaces it. Only observed queries refetch at once.
71
+ - A mutation that succeeded waits for earlier ones: an earlier `run` that never resolves holds it back, so pass a `signal` and abort it.
72
+
73
+ Exported types: `Mutation`, `MutationOptions`, `RunOptions`, `Tx`, `Invalidation`, `Target`.
@@ -0,0 +1,93 @@
1
+ # Queries
2
+
3
+ A query is a stateless definition: an `id` and a `fetch` that takes typed variables and returns data. The core is transport-agnostic: the GraphQL and REST adapters supply the id and the fetcher; here it runs over a plain `fetch`. Cache entries live in the `RivaClient`, keyed by the id and the stable-serialized variables.
4
+
5
+ ```ts
6
+ import { createRivaClient, query, RivaHttpError } from '@softistx/riva';
7
+
8
+ const user = query({
9
+ id: 'user',
10
+ staleTime: '30s', // "250ms" | "30s" | "5m" | "2h", or a number of ms
11
+ fetch: async (vars: { id: string }, { signal }) => {
12
+ const res = await fetch(`/api/users/${vars.id}`, { signal });
13
+ if (!res.ok) throw new RivaHttpError(res.status);
14
+ return (await res.json()) as { id: string; name: string };
15
+ },
16
+ });
17
+
18
+ const client = createRivaClient(); // one per request on the server
19
+ const data = await user.ensure(client, { id: '1' }); // fetch if missing or stale, else the cache
20
+ client.get(user, { id: '1' }); // { status, data, error, isFetching, updatedAt }: a pure read
21
+ const off = client.subscribe(user, { id: '1' }, (state) => console.log(state.status));
22
+ ```
23
+
24
+ `Vars` and `Data` are inferred from `fetch`. Variables are optional at call sites when the fetcher takes none.
25
+
26
+ ## Reading and driving a query
27
+
28
+ | Call | What it does |
29
+ | --- | --- |
30
+ | `def.ensure(client, vars, { signal? })` | Fetches if missing or stale and awaits; resolves the cache when fresh. |
31
+ | `client.get(def, vars)` | The state: a pure read, tracked in a computed or effect, never fetches. |
32
+ | `client.subscribe(def, vars, listener, { staleTime? })` | Observes: fetches when missing or stale, polls, refetches on focus and reconnect. Returns an unsubscribe. |
33
+ | `def.prefetch(client, vars)` | Fire and forget; never rejects. |
34
+ | `def.invalidate(client, vars?)` | Marks stale; observed entries refetch. Without variables: every entry of the definition. |
35
+ | `def.setData(client, vars, data)` | Writes a success with `updatedAt` now; a fetch in flight resolves its waiters with it. |
36
+ | `def.cancel(client, vars)` | Aborts the fetch and restores the previous state. An observed entry whose data reads `undefined` is fetched again after a cancel. |
37
+
38
+ ## The state
39
+
40
+ `QueryState<Data>` is `{ status, data, error, isFetching, updatedAt }`.
41
+
42
+ - `status` is `idle | pending | success | error`.
43
+ - A background refetch keeps `status: 'success'` and the old data with `isFetching: true`. An error keeps the last data.
44
+ - Data the cache can no longer read (an evicted entity) counts as stale: `ensure` fetches it and an observed entry refetches.
45
+
46
+ ## Options
47
+
48
+ | Option | Default | Effect |
49
+ | --- | --- | --- |
50
+ | `id` | required | Identifies the definition; ids must be unique. |
51
+ | `fetch(vars, { signal, client })` | required | Returns the data. |
52
+ | `staleTime` | `0` | How long data stays fresh. A `Duration`: a number of ms or `"250ms"`, `"30s"`, `"5m"`, `"2h"`. |
53
+ | `gcTime` | 5 min in a browser, `Infinity` on the server | How long an unobserved entry is kept. No timers on the server: a per-request client is just dropped. |
54
+ | `retry` | 3 in a browser, 0 on the server | A count, or `(failures, error) => boolean`. |
55
+ | `retryDelay` | `min(1000 * 2 ** failures, 30_000)` | `(failures) => ms`. |
56
+ | `refetchOnFocus` | `true` | Observed and stale entries only; browser only. |
57
+ | `refetchOnReconnect` | `true` | Same. |
58
+ | `refetchEvery` | none | Polls while observed; browser only, no timer is armed on the server. |
59
+ | `cache` | none (data kept as is) | A `CachePolicy`, such as `entities()` (see [entities](./entities.md)). |
60
+
61
+ Never retried: `RivaAbortError`, and a `RivaRequestError` with `retryable: false`. Any other error is retried per `retry`.
62
+
63
+ ## Dedupe and abort
64
+
65
+ - One in-flight fetch per key: concurrent `ensure` and `subscribe` share it.
66
+ - The fetcher gets `signal`. `ensure(client, vars, { signal })` rejects with `RivaAbortError` when the caller aborts; the shared fetch is aborted only when no other waiter or observer remains, and an aborted fetch never writes an error state.
67
+ - `client.subscribe(def, vars, listener, { staleTime })` overrides the definition's `staleTime` for this observer's first fetch decision only, for example to trust data an `ensure` just loaded.
68
+
69
+ ## Tests and other hosts
70
+
71
+ ```ts
72
+ const client = createRivaClient({
73
+ scheduler: { now, setTimeout, clearTimeout }, // replaces the clock and timers
74
+ events: { onFocus, onReconnect }, // replaces the window events
75
+ });
76
+ ```
77
+
78
+ ## Keys
79
+
80
+ `stableKey(id, vars)` derives the cache key: sorted object keys, `Date` as ISO, `undefined` dropped. Variables the key cannot serialize (function, symbol, bigint, cycle) throw `RIVA_KEY`. Never write a key by hand.
81
+
82
+ ## Errors
83
+
84
+ - `RivaRequestError` (`status?`, `retryable`, `cause`): a failed request. `RivaHttpError(status)` has code `HTTP_<status>`, retryable for 5xx, 408 and 429. `RivaNetworkError` (`RIVA_NETWORK`) is retryable. `RivaAbortError` (`RIVA_ABORT`) is never retried.
85
+ - `RIVA_DURATION`: an invalid duration string. `RIVA_KEY`: unserializable variables. `RIVA_CACHE`: data the entity cache cannot store.
86
+
87
+ Exported types: `Query`, `QueryOptions`, `QueryState`, `QueryStatus`, `EnsureOptions`, `SubscribeOptions`, `FetchContext`, `VarsArgs`, `Duration`, `Scheduler`, `ClientEvents`.
88
+
89
+ ## Traps
90
+
91
+ - With the default `staleTime` of 0, every `ensure` and every new observer refetches. Set a `staleTime` for data that may be reused, especially data hydrated from the server.
92
+ - Two definitions with one `id` share a cache entry.
93
+ - `invalidate` only refetches at once what is observed; an unobserved entry refetches on its next read.
@@ -0,0 +1,72 @@
1
+ # Signals, computeds and effects
2
+
3
+ Reactive values for local state. Use them for client state that is not fetched (a filter, a selected row, a cart). Definitions are stateless: the value of a signal lives in a `RivaClient`, one per request on the server, so values never leak between requests.
4
+
5
+ ## The basics
6
+
7
+ ```ts
8
+ import { batch, computed, createRivaClient, signal, untracked } from '@softistx/riva';
9
+
10
+ const count = signal(0);
11
+ const double = computed((get) => get(count) * 2); // lazy, cached, tracked dynamically
12
+
13
+ const client = createRivaClient();
14
+ client.subscribe(double, (v) => console.log('double', v));
15
+ client.set(count, 2); // logs "double 4"
16
+ client.set(count, (n) => n + 1); // logs "double 6"
17
+ client.get(double); // 6
18
+ ```
19
+
20
+ `client.get`, `client.set`, `client.subscribe`, `client.effect`, `client.run` and `client.batch` are the whole API outside any ambient scope. `client.subscribe(def, listener)` returns an unsubscribe function.
21
+
22
+ ## Ambient reads
23
+
24
+ Inside `client.run`, signals and computeds read through that client, so a definition can call `.get()` and `.set()` itself:
25
+
26
+ ```ts
27
+ client.run(() => {
28
+ count.set(10);
29
+ batch(() => {
30
+ count.set(11);
31
+ count.set(12);
32
+ }); // one notification at the end
33
+ untracked(() => count.get()); // read without becoming a dependency
34
+ });
35
+ ```
36
+
37
+ - `batch(fn)` groups writes into one notification; reads inside see the new values at once.
38
+ - `untracked(fn)` reads without registering a dependency in the surrounding computed or effect.
39
+ - Without a client in scope, `count.get()` throws `RivaScopeError` (`RIVA_SCOPE`). In a browser, `setDefaultClient(client)` sets one default; `setDefaultClient(undefined)` clears it. On the server it throws, because a module-level client would leak between requests. A host supplies the scope with `setScopeResolver` (see [ssr](./ssr.md)).
40
+
41
+ ## Effects
42
+
43
+ ```ts
44
+ client.effect(() => {
45
+ const n = client.get(count);
46
+ return () => console.log('leaving', n); // runs before each re-run and on dispose
47
+ });
48
+ ```
49
+
50
+ - `client.effect(fn)` always runs. The free function `effect(fn)` re-runs on the ambient client in a browser and is a **no-op on the server**.
51
+ - The cleanup the effect returns runs before each re-run.
52
+ - An effect that keeps writing its own source throws `RIVA_LOOP` after 100 re-runs in one flush.
53
+
54
+ ## Options
55
+
56
+ | Call | Options | Defaults |
57
+ | --- | --- | --- |
58
+ | `signal(initial, opts?)` | `name?: string`, `equals?: (a, b) => boolean`, `ssr?: boolean` | `equals` is `Object.is`; `ssr` is `false` |
59
+ | `computed(fn, opts?)` | `name?: string`, `equals?: (a, b) => boolean` | `equals` is `Object.is` |
60
+
61
+ - Subscribers fire only when the value changes by `equals`, once per change, never on a half-updated graph.
62
+ - `ssr: true` with a unique `name` sends the value in an SSR snapshot once it differs from its initial value (see [ssr](./ssr.md)). Every other signal stays local.
63
+ - `computed(fn)` receives `get`; dependencies are tracked dynamically, per run.
64
+ - Exported types: `Signal`, `SignalOptions`, `ReadonlySignal`, `Computed`, `ComputedOptions`, `Readable`, `Getter`, `Listener`, `Unsubscribe`, `EffectFn`.
65
+
66
+ ## Traps
67
+
68
+ - A computed that reads itself throws `RIVA_CYCLE`.
69
+ - A listener or effect that throws never stops the others: every notification runs, then the single error is rethrown as is, and several become an `AggregateError`.
70
+ - After an `await` inside `client.run`, the ambient scope may be gone in a browser-only setup: read through `client.get(def)` instead. The React Router host keeps the scope across awaits.
71
+
72
+ See [troubleshooting](../troubleshooting.md) for the messages.
@@ -0,0 +1,65 @@
1
+ # Server rendering: `@softistx/riva/ssr`
2
+
3
+ Moves what a request fetched to the browser, so the first render needs no second fetch. It holds no state of its own: a snapshot is plain JSON.
4
+
5
+ ```ts
6
+ import { createRivaClient } from '@softistx/riva';
7
+ import { dehydrate, hydrate } from '@softistx/riva/ssr';
8
+
9
+ const client = createRivaClient();
10
+
11
+ // On the server, once the request's loaders are done:
12
+ const snapshot = dehydrate(client); // JSON-safe, hand it to the page
13
+
14
+ // In the browser, before the first render:
15
+ hydrate(client, snapshot);
16
+ ```
17
+
18
+ The snapshot's fields are an opaque format that may change: never build or edit one, only pass on what `dehydrate` returned. With React Router, `@softistx/riva-react-router` does both for you.
19
+
20
+ ## Embedding the snapshot safely
21
+
22
+ Hand it to the page through the host's loader data (React Router serializes it safely). If you inline it in a `<script>` yourself, escape `<` so a value such as `</script>` cannot close the tag:
23
+
24
+ ```ts
25
+ const json = JSON.stringify(snapshot).replace(/</g, '\\u003c');
26
+ const html = `<script id="riva" type="application/json">${json}</script>`;
27
+ ```
28
+
29
+ ## `dehydrate(client)`
30
+
31
+ - Writes the settled query entries (successes and errors; idle and in-flight ones are skipped), read as readers see the committed data: a normalized or infinite entry travels denormalized and is stored again by its own cache policy on arrival. Optimistic layers never travel.
32
+ - Each entry carries its age, not the server's clock, so a skewed clock cannot make fresh data stale.
33
+ - Signals travel only when they opt in with `ssr: true`, have a unique `name` and changed from their initial value (`signal(0, { name: 'cart', ssr: true })`). Every other signal stays local, riva's own included.
34
+ - Dates survive, as do `NaN` and the infinities. A bigint, a function, a symbol, a `Map`, a `Set`, an instance of a class or a cycle is refused with `RIVA_SSR`, naming its path.
35
+ - A failed entry travels as its code, status and `retryable`, with no message and no stack, so a server detail cannot leak. Anything that was not a `RivaError` travels as `RIVA_UNKNOWN`.
36
+
37
+ ## `hydrate(client, snapshot, opts?)`
38
+
39
+ | Option | Default | Effect |
40
+ | --- | --- | --- |
41
+ | `deferObserved` | `false` | For a render: nothing that could reach an observed entry is written. The entries something observes, those with a cache policy (they share entities) and those not created yet are **returned** as a snapshot to apply later, outside the render, with `hydrate(client, deferred)`. Its ages are understated by the delay. |
42
+
43
+ - It seeds entries and signals the client has not created yet, at the moment their definition is first used, so the hydrating code needs none of the definitions.
44
+ - An entry the client already has is replaced only by a newer snapshot, and never while it is fetching or carries optimistic layers. An existing signal is never overwritten.
45
+ - A fresh entry is not fetched again: data hydrated with the definition's `staleTime` stays fresh for it. The default `staleTime` is 0, so set one for hydrated data (see [troubleshooting](../troubleshooting.md#data-refetches-right-after-hydration)).
46
+ - A failed entry comes back as a `RivaError` (a `RivaRequestError` when it had a status) with an empty message; `RIVA_NETWORK`, `HTTP_<n>` and `RIVA_ABORT` come back as `RivaNetworkError`, `RivaHttpError` and `RivaAbortError`.
47
+
48
+ ## The ambient scope: `setScopeResolver(fn)`
49
+
50
+ Lets a host supply the ambient client, for example from a request context kept in an `AsyncLocalStorage`. `fn` is `() => RivaClient | undefined`; `client.run` still wins, then the resolver, then the browser's default client. With no resolver, or one that returns `undefined`, a server read with no client throws `RIVA_SCOPE`. There is one resolver per process: a second call replaces the first.
51
+
52
+ ```ts
53
+ import { AsyncLocalStorage } from 'node:async_hooks';
54
+ import type { RivaClient } from '@softistx/riva';
55
+ import { setScopeResolver } from '@softistx/riva/ssr';
56
+
57
+ const als = new AsyncLocalStorage<RivaClient>();
58
+ setScopeResolver(() => als.getStore());
59
+ ```
60
+
61
+ ## Codec
62
+
63
+ `encode(value)` and `decode(value)` are the codec the snapshot uses (Dates and non-finite numbers survive). They are exported for transports of your own; `@softistx/riva/data` uses them for variables.
64
+
65
+ Exports: `dehydrate`, `hydrate`, `encode`, `decode`, `setScopeResolver`, the type `Snapshot`.
@@ -0,0 +1,88 @@
1
+ # Stores: `@softistx/riva/store`
2
+
3
+ One definition per domain groups its state, computeds and actions. Every state key is a signal named `<name>.<key>` and every computed a riva computed, so both are read as definitions (`.get()`, `client.get()`, `useValue()`). Like any definition, a store is stateless: its values live per `RivaClient`, one instance per client.
4
+
5
+ ```ts
6
+ import { createRivaClient, mutation } from '@softistx/riva';
7
+ import { store, type StoreContext } from '@softistx/riva/store';
8
+
9
+ const saveBook = mutation<{ book: Book }, Book>({ id: 'saveBook', run: postBook });
10
+
11
+ export const BookStore = store({
12
+ name: 'books', // required, unique on a client; prefixes the signal names
13
+ ssr: true, // every state key travels in an SSR snapshot (default false)
14
+ state: { items: [] as Book[], filter: '', saving: false },
15
+ computed: {
16
+ visible: (s) => s.items.filter((b) => b.title.includes(s.filter)), // s: the state, tracked per key
17
+ total: (s) => s.items.length,
18
+ discount: (s, get) => (get(UserStore.vip) ? 0.1 : 0), // other stores through their definitions
19
+ },
20
+ actions: {
21
+ add(s, book: Book) {
22
+ s.items = [...s.items, book]; // top-level assignment; one call, one notification
23
+ },
24
+ filterBy(s, q: string) {
25
+ s.filter = q;
26
+ },
27
+ async save(s, book: Book, { mutate }: StoreContext) {
28
+ s.saving = true;
29
+ const saved = await mutate(saveBook, { book });
30
+ s.items = [...s.items, saved];
31
+ s.saving = false;
32
+ },
33
+ },
34
+ });
35
+
36
+ const client = createRivaClient();
37
+ client.get(BookStore.visible); // explicit client
38
+ client.run(() => {
39
+ BookStore.total.get(); // ambient read
40
+ BookStore.add(book); // an action, on the ambient client
41
+ BookStore.reset(); // every state key back to its initial value
42
+ });
43
+ const [s, a] = BookStore.bind(client); // a read-only view of state and computeds, and the actions
44
+ await a.save(book); // `s` stays bound to `client` across the await
45
+ ```
46
+
47
+ ## Options of `store(opts)`
48
+
49
+ | Option | Default | Effect |
50
+ | --- | --- | --- |
51
+ | `name` | required | Unique on a client; prefixes the signal names. |
52
+ | `ssr` | `false` | Every state key travels as `<name>.<key>` in an SSR snapshot (computeds never do). |
53
+ | `state` | required | The initial state, by key. |
54
+ | `computed` | none | `{ key: (s, get) => value }`. |
55
+ | `actions` | none | `{ key: (s, ...args, ctx) => … }`. |
56
+
57
+ ## Writing
58
+
59
+ - **Only actions write**, by top-level assignment on `s`. A state key is typed `ReadonlySignal` (no `set`), and a write made any other way (`BookStore.items.set(…)`, `client.set(BookStore.items, …)`, a computed, an unknown key) throws `RIVA_STORE`. The exceptions are `hydrate` and `reset()`.
60
+ - Values are immutable: replace them (`s.items = [...s.items, b]`). In development (`process.env.NODE_ENV` not `production`) a stored value is deep-frozen, so `s.items.push(b)` throws, a hydrated value too.
61
+ - **Batched.** Every action runs in a batch: one call, one notification. After an `await`, the writes of one synchronous segment make one notification at its end; unrelated writes made on that client in that segment are held until then.
62
+ - `s` is revoked once the action settles: a later write throws `RIVA_STORE`, reads still work.
63
+
64
+ ## The context
65
+
66
+ An action is `(s, ...args, ctx)`; callers pass only `args`. Annotating `ctx: StoreContext` is mandatory: it types the context and removes it from the callers' signature. `StoreContext` is `{ client, fetch, mutate }`, where `fetch(query, vars?)` is `query.ensure(client, …)` and `mutate(mutation, vars?)` is `mutation.run(client, …)`.
67
+
68
+ The context goes right after the declared arguments: a default value before it moves it. **An action whose last parameter is optional or defaulted must also declare `ctx?: StoreContext` last** (`inc(s, by?: number, ctx?: StoreContext)`): without it the context lands in that parameter, and the action fails to type.
69
+
70
+ ## Computeds
71
+
72
+ They receive `(s, get)`: `s` holds the state only (no other computed), `get(def)` reads any other definition, another store's included. A cycle is refused with `RIVA_CYCLE`.
73
+
74
+ ## Names
75
+
76
+ `name` is required. A state, computed or action key cannot repeat, nor be `kind`, `name`, `reset`, `bind` or `then` (refused at definition, and a type error). Two stores with one name on a client are refused with `RIVA_STORE` on the server when the second is first used; in a browser the newer definition takes over (hot reload) and the older one is dropped from that client.
77
+
78
+ ## `reset` and SSR
79
+
80
+ - `reset(client?)` puts every state key back to its initial value (the same reference, so the key no longer travels in a snapshot) in one notification. A write an async action makes after the reset still applies.
81
+ - With `ssr: true` every state key travels; by default nothing does. A snapshot seeds a store first used after `hydrate` (see [ssr](./ssr.md)).
82
+
83
+ ## Traps
84
+
85
+ - Mutating in place (`s.items.push`) throws in development and silently skips the notification in production: always assign a new value.
86
+ - The deep signals (per-path reactivity on nested state) and store families (one instance per key) come later.
87
+
88
+ Exports: `store`; types `Store`, `StoreOptions`, `StoreContext`, `Action`, `Args`, `Bound`, `View`. `ReadonlySignal` comes from the main entry. In React, `useStore` is in `@softistx/riva-react/store`.