@lunora/cli 1.0.0-alpha.40 → 1.0.0-alpha.401

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 (134) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +3 -1
  3. package/dist/bin.mjs +2 -10
  4. package/dist/index.d.mts +1034 -374
  5. package/dist/index.d.ts +1034 -374
  6. package/dist/index.mjs +1 -19
  7. package/dist/packem_chunks/dispatch.mjs +1 -0
  8. package/dist/packem_chunks/handler.mjs +1 -160
  9. package/dist/packem_chunks/handler10.mjs +1 -16
  10. package/dist/packem_chunks/handler11.mjs +1 -22
  11. package/dist/packem_chunks/handler12.mjs +1 -192
  12. package/dist/packem_chunks/handler13.mjs +3 -131
  13. package/dist/packem_chunks/handler14.mjs +1 -65
  14. package/dist/packem_chunks/handler15.mjs +1 -58
  15. package/dist/packem_chunks/handler16.mjs +1 -80
  16. package/dist/packem_chunks/handler17.mjs +7 -43
  17. package/dist/packem_chunks/handler18.mjs +1 -105
  18. package/dist/packem_chunks/handler19.mjs +1 -170
  19. package/dist/packem_chunks/handler2.mjs +1 -114
  20. package/dist/packem_chunks/handler20.mjs +3 -94
  21. package/dist/packem_chunks/handler21.mjs +3 -94
  22. package/dist/packem_chunks/handler22.mjs +1 -0
  23. package/dist/packem_chunks/handler23.mjs +2 -0
  24. package/dist/packem_chunks/handler24.mjs +99 -0
  25. package/dist/packem_chunks/handler25.mjs +2 -0
  26. package/dist/packem_chunks/handler26.mjs +9 -0
  27. package/dist/packem_chunks/handler27.mjs +1 -0
  28. package/dist/packem_chunks/handler3.mjs +1 -204
  29. package/dist/packem_chunks/handler4.mjs +3 -33
  30. package/dist/packem_chunks/handler5.mjs +1 -49
  31. package/dist/packem_chunks/handler6.mjs +1 -91
  32. package/dist/packem_chunks/handler7.mjs +1 -42
  33. package/dist/packem_chunks/handler8.mjs +2 -174
  34. package/dist/packem_chunks/handler9.mjs +1 -315
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +11 -594
  37. package/dist/packem_chunks/runDevCommand.mjs +2 -0
  38. package/dist/packem_chunks/runInitCommand.mjs +165 -1432
  39. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  40. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  41. package/dist/packem_shared/COMMANDS-aSTSMwZS.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyIsI3S1.mjs +1 -0
  43. package/dist/packem_shared/EXIT_CODE-D_XCixv8.mjs +1 -0
  44. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  45. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  46. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  47. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  48. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  49. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  50. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  51. package/dist/packem_shared/cli-CFsmCYWp.mjs +2 -0
  52. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  53. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  54. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  55. package/dist/packem_shared/command-BgjsvUFg.mjs +1 -0
  56. package/dist/packem_shared/commands-DvSfLvyt.mjs +13 -0
  57. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  58. package/dist/packem_shared/createRecordingSpawner-Ch7zuQQE.mjs +1 -0
  59. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  60. package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
  61. package/dist/packem_shared/docker-AqLAkOyY.mjs +1 -0
  62. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
  63. package/dist/packem_shared/import-BRM1hs7j.mjs +12 -0
  64. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  65. package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
  66. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  67. package/dist/packem_shared/mcp-config-file-CcDTeXIq.mjs +2 -0
  68. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  69. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  70. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  71. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  72. package/dist/packem_shared/plan-DVfi3TrN.mjs +5 -0
  73. package/dist/packem_shared/planDevCommand-IglbXy5A.mjs +1 -0
  74. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  75. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  76. package/dist/packem_shared/render-lunora-error-C3OJY5wk.mjs +2 -0
  77. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  78. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  79. package/dist/packem_shared/runAddCommand-BChdJQ5L.mjs +1 -0
  80. package/dist/packem_shared/runExportCommand-slAq5BCF.mjs +5 -0
  81. package/dist/packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs +11 -0
  82. package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
  83. package/dist/packem_shared/secret-key-8DPOH98z.mjs +1 -0
  84. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  85. package/dist/packem_shared/storage-DNzYhXR-.mjs +1 -0
  86. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  87. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  88. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  89. package/dist/packem_shared/wrangler-secrets-CTQPpalP.mjs +1 -0
  90. package/package.json +39 -19
  91. package/skills/README.md +35 -17
  92. package/skills/lunora/SKILL.md +157 -65
  93. package/skills/lunora-create-package/SKILL.md +97 -84
  94. package/skills/lunora-deploy/SKILL.md +175 -105
  95. package/skills/lunora-functions/SKILL.md +363 -56
  96. package/skills/lunora-migration-helper/SKILL.md +162 -137
  97. package/skills/lunora-performance-audit/SKILL.md +137 -95
  98. package/skills/lunora-quickstart/SKILL.md +137 -136
  99. package/skills/lunora-realtime/SKILL.md +201 -97
  100. package/skills/lunora-setup-auth/SKILL.md +162 -102
  101. package/skills/lunora-setup-hyperdrive/SKILL.md +130 -109
  102. package/skills/lunora-setup-hyperdrive-global/SKILL.md +93 -90
  103. package/skills/lunora-setup-mail/SKILL.md +85 -113
  104. package/skills/lunora-setup-scheduler/SKILL.md +132 -96
  105. package/skills/lunora-setup-storage/SKILL.md +189 -95
  106. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  107. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  108. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  109. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  110. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  111. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  112. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  113. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  114. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  115. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  116. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  117. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  118. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  119. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  120. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  121. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  122. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  123. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  124. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  125. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  126. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  127. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  128. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  129. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  130. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  131. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  132. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  133. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  134. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,37 +1,51 @@
1
1
  ---
2
2
  name: lunora-realtime
3
- description: Wires Lunora's live data into a client. Use for `LunoraClient`/`LunoraProvider`,
4
- reactive `useQuery`/`useSubscription`, `useMutation` with optimistic updates,
5
- pagination, connection status, the React/Vue/Solid/Svelte adapters, and the
6
- `@lunora/db` TanStack binding.
3
+ description: Wires Lunora's live data into a client app. Covers `LunoraClient` and the per-framework provider, reactive `useQuery`/`useSubscription`, `useMutation` with optimistic updates, `usePaginatedQuery`, `shardKey` routing, connection status, presence, the React/Vue/Solid/Svelte/Angular/React Native adapters, and the `@lunora/db` TanStack DB binding. Use when building UI that reads or writes Lunora functions, when asked to "show live data", "make this update in real time", "add optimistic updates", "add infinite scroll/pagination", or "show offline/reconnecting state", when editing components that import `@lunora/react`/`vue`/`solid`/`svelte`/`angular`/`react-native` or `lunorash/client`, when a live query stays `undefined`, freezes, or doesn't update, or when choosing between a live query, a stream, a live topic (`defineLiveStream`, `useLiveTopic`, `ctx.live.publish`, SSE), a whisper, a room and a socket, such as "push an event to the browser" or "notify the page when X happens".
7
4
  ---
8
5
 
9
6
  # Lunora Realtime
10
7
 
11
8
  Consume Lunora functions reactively from the client. Queries are live
12
- subscriptions over WebSocket — a `useQuery` re-renders the instant a mutation
9
+ subscriptions over WebSocket — a `useQuery` re-renders as soon as a mutation
13
10
  changes the rows it reads — and mutations can paint optimistically with
14
11
  automatic rollback.
15
12
 
16
- ## When to Use
13
+ ## Choosing a Channel
17
14
 
18
- - Wiring a frontend to a Lunora backend (React, Vue, Solid, Svelte).
19
- - Adding optimistic updates, pagination, or presence to the UI.
20
- - Choosing between live hooks and the `@lunora/db` collection layer.
15
+ Decide by what you are sending. If the client could get it by running a query,
16
+ use a live query: it is typed, runs under the caller's identity, and works across
17
+ shards. Reach past it only for the rest.
18
+
19
+ | You want | Use |
20
+ | -------------------------------------------------- | ------------------------------------------------------ |
21
+ | Rows that stay fresh | `useQuery` (WebSocket, typed through `api.*`) |
22
+ | A write / a side effect | `useMutation` / `useAction` |
23
+ | Chunks of one long call (model tokens) | `query.stream()` + `useStream` (`durable` to resume) |
24
+ | Chunks of one HTTP request | `httpRoute.get(path).stream()` + `useHttpStream` |
25
+ | A server-published event that is not a row | live topic: `defineLiveStream` + `useLiveTopic` |
26
+ | A client-to-clients ephemeral message (cursors) | whisper (`client.whisper`; authorize with `onWhisper`) |
27
+ | A room with server join / message / leave handlers | `defineRoom` + `client.connectRoom` |
28
+ | A dedicated socket at your own path | `defineWebSocket` + `client.connectWebSocket(path)` |
29
+ | Who is online | `usePresence` |
30
+
31
+ Live topics are the untyped one: the topic is a string and the payload is
32
+ `unknown`. Full guide: the "Choosing a data channel" docs page.
21
33
 
22
34
  ## When Not to Use
23
35
 
24
36
  - Writing the server functions themselves — that's `lunora-functions`.
25
37
  - Initial project/provider scaffolding — that's `lunora-quickstart`.
38
+ - Sign-in UI and the `Authenticated` gates — that's `lunora-setup-auth`.
26
39
 
27
40
  ## Provider Setup
28
41
 
29
- Create the `LunoraClient` once at module scope and wrap the app. The client owns
30
- the WebSocket, the optimistic cache, and the offline queue.
42
+ Create the `LunoraClient` once at module scope; it owns the WebSocket, the
43
+ optimistic cache, and the offline queue, so creating it inside a component
44
+ reopens the socket on every render.
31
45
 
32
46
  ```tsx
33
- import { LunoraClient } from "@lunora/client";
34
47
  import { LunoraProvider } from "@lunora/react";
48
+ import { LunoraClient } from "lunorash/client";
35
49
 
36
50
  const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;
37
51
  const client = new LunoraClient({ url });
@@ -39,80 +53,97 @@ const client = new LunoraClient({ url });
39
53
  // <LunoraProvider client={client}>…</LunoraProvider>
40
54
  ```
41
55
 
42
- Vue / Solid / Svelte have matching providers in `@lunora/vue`, `@lunora/solid`,
43
- `@lunora/svelte`; the hook names and semantics below mirror across them.
56
+ The adapters differ in how they register the client and name their primitives:
57
+
58
+ | Package | Register the client | Live read / write |
59
+ | ---------------------- | ------------------------------------------------------------ | ---------------------------------------------- |
60
+ | `@lunora/react` | `<LunoraProvider client={client}>` | `useQuery` / `useMutation` |
61
+ | `@lunora/vue` | `app.use(createLunora(client))` (or `provideLunora(client)`) | `useQuery` / `useMutation` |
62
+ | `@lunora/solid` | `<LunoraProvider client={client}>` | `createQuery` / `createMutation` |
63
+ | `@lunora/svelte` | `setLunoraClient(client)` in the root layout | `query` / `mutation` stores |
64
+ | `@lunora/angular` | `provideLunora()` in `ApplicationConfig` | `liveQuery` / `mutate`, `injectLunoraClient()` |
65
+ | `@lunora/react-native` | `createLunoraClient({ url, storage })` + `LunoraProvider` | re-exports `@lunora/react` hooks |
66
+
67
+ The rest of this skill uses the React names; the others mirror the same
68
+ semantics (`usePaginatedQuery` → `createPaginatedQuery` / `paginatedQuery`,
69
+ `useConnectionStatus` → `createConnectionStatus` / `connectionStatus`, …).
70
+ React Native passes `storage: AsyncStorage` so the offline queue survives a
71
+ restart; `@lunora/react-native/auth` bridges a better-auth Expo session.
72
+ `@lunora/astro` and `@lunora/nuxt` (Nitro) integrate Lunora into the SSR server.
44
73
 
45
74
  ## Live Queries
46
75
 
47
- `useQuery(reference, args)` opens a subscription and returns the value, or
48
- `undefined` while it loads. The reference comes from codegen
49
- (`api.<file>.<name>`).
76
+ `useQuery(reference, args, options?)` opens a subscription and returns the
77
+ value, or `undefined` while it loads. References come from codegen and are
78
+ typed end to end, so no cast is needed:
50
79
 
51
80
  ```tsx
52
81
  import { useQuery } from "@lunora/react";
53
82
 
54
- import { api } from "../../lunora/_generated/api";
55
- import type { Doc } from "../../lunora/_generated/dataModel";
83
+ import { api } from "../lunora/_generated/api";
56
84
 
57
- const todos = useQuery(api.todos.list, {}) as Doc<"todos">[] | undefined;
85
+ const todos = useQuery(api.todos.list, {});
86
+ const messages = useQuery(api.messages.list, { channelId }, { shardKey: channelId, onError: report });
58
87
  ```
59
88
 
60
- - `undefined` means "loading" — render a skeleton/spinner for it.
61
- - The subscription tears down on unmount and re-runs only when `args` change or
62
- the underlying rows change. Keep `args` narrow so a write elsewhere doesn't
63
- re-push unrelated data (see `lunora-performance-audit`).
64
- - `useSubscription` is the lower-level primitive for streaming subscriptions;
65
- `usePreloadedQuery` + `lunoraQueryOptions` support SSR/preload handoff via
66
- `@lunora/react/server`.
89
+ - `undefined` means loading and `[]` means loaded-and-empty; branch on both.
90
+ - Pass `"skip"` as `args` to disable the query (no network call, no
91
+ subscription) — e.g. until a required id is known.
92
+ - Pass `onError` to see a server-pushed error (an RLS denial, a query that starts
93
+ throwing). Without it the error is dropped and the value silently freezes at
94
+ its last good result.
95
+ - `shardKey`: for a `.shardBy(...)` table, pin every read and write to the
96
+ shard's key (`{ shardKey: channelId }` on both `useQuery` and the mutation
97
+ call). Without it the runtime has to fan out across every shard.
98
+ - The subscription re-runs only when `args` or the rows it read change. Keep
99
+ `args` narrow so unrelated writes don't re-push data (see
100
+ `lunora-performance-audit`).
101
+ - `useSubscription` is the push-only variant (no initial HTTP fetch) returning
102
+ `{ data, error }`. For SSR, `@lunora/react/server` exports `preloadQuery`,
103
+ `fetchQuery`, and `lunoraQueryOptions`; hand the result to
104
+ `usePreloadedQuery` on the client.
105
+ - References in folders are nested: `lunora/billing/invoices.ts` →
106
+ `api.billing.invoices.<fn>`. Client code only ever imports `api`;
107
+ `internal` functions are not callable from the client.
67
108
 
68
109
  ## Authorization & Live Queries
69
110
 
70
- Subscriptions re-run the query handler **server-side under anonymous
71
- identity**. The one-shot `fetch` RPC behind the initial load carries the
72
- caller's identity, but the live WebSocket channel (the subscription seed and
73
- every write-driven refresh) does not — it evaluates as anonymous.
74
-
75
- This matters for any query that authorizes or filters on the authenticated
76
- user:
77
-
78
- - A query guarded by `.use(rls(...))` or one that reads `ctx.auth.userId`
79
- directly returns the user's rows on the **initial** HTTP fetch, but its
80
- **live** updates evaluate anonymously and may resolve to an empty/denied
81
- set.
82
- - This **fails closed** — the live channel shows _less_ data, never another
83
- user's data, so there is no leak. But it is a correctness caveat: the
84
- initial render and the live updates can disagree.
111
+ Live queries are identity-aware. At the WebSocket upgrade the runtime stamps
112
+ the caller's verified identity onto the socket, and every subscription re-run
113
+ executes under that identity, so:
85
114
 
86
- The supported pattern today is to scope per-user data **outside** of
87
- `ctx.auth` inside a subscribed query:
115
+ - `.use(rls(...))` and `ctx.auth.userId` behave the same in a subscription as in
116
+ a one-shot read. Shape subscriptions AND-merge their predicate with the
117
+ table's RLS read policy.
118
+ - An anonymous socket carries no identity, so an RLS/`ctx.auth` query fails
119
+ closed (empty or denied) rather than leaking rows.
120
+ - When the credential carries an expiry, the server sends `TOKEN_EXPIRED` and
121
+ closes with code `4001`. `LunoraClient` reconnects and re-resolves identity
122
+ automatically; surface it in the UI only if a re-login is required.
88
123
 
89
- - Partition the data by shard with `.shardBy(userId)` (or tenant/room), so the
90
- subscription is already scoped to the right state, or
91
- - Pass the identifier as an **explicit query arg**
92
- (`useQuery(api.todos.list, { userId })`) and filter on the arg rather than on
93
- `ctx.auth`.
94
-
95
- Reserve `rls()` / `ctx.auth`-based filtering for non-subscribed reads (one-shot
96
- actions/queries) where identity is always present.
124
+ Use `.shardBy(...)` and narrow args for performance, `rls()` / `ctx.auth` for
125
+ authorization. They compose.
97
126
 
98
127
  ## Mutations + Optimistic Updates
99
128
 
100
- `useMutation(reference)` returns `{ mutate, pending }`. Pass an `optimistic`
101
- callback to paint the next state immediately; if the server rejects the call the
102
- runtime rolls the cache back automatically.
129
+ `useMutation(reference)` returns `{ mutate, pending, data, error, reset }`.
130
+ Destructure it — the hook result itself isn't callable. `mutate` returns a
131
+ promise that rejects on failure. Pass `optimisticUpdate` to paint the next state
132
+ immediately; if the server rejects the call the cache rolls back.
103
133
 
104
134
  ```tsx
105
135
  import { useMutation } from "@lunora/react";
106
136
 
107
- import type { Doc, Id } from "../../lunora/_generated/dataModel";
137
+ import { api } from "../lunora/_generated/api";
138
+ import type { Doc, Id } from "../lunora/_generated/dataModel";
108
139
 
109
140
  const { mutate: add, pending } = useMutation(api.todos.add);
110
141
 
111
142
  await add(
112
143
  { text },
113
144
  {
114
- optimistic: (current) => {
115
- const list = (current as Doc<"todos">[] | undefined) ?? [];
145
+ optimisticUpdate: (store) => {
146
+ const list = store.getQuery(api.todos.list, {}) ?? [];
116
147
  const provisional: Doc<"todos"> = {
117
148
  _id: `optimistic_${Date.now()}` as Id<"todos">,
118
149
  _creationTime: Date.now(),
@@ -120,58 +151,131 @@ await add(
120
151
  done: false,
121
152
  createdAt: Date.now(),
122
153
  };
123
- return [provisional, ...list];
154
+ store.setQuery(api.todos.list, {}, [provisional, ...list]);
124
155
  },
125
156
  },
126
157
  );
127
158
  ```
128
159
 
129
- - The `optimistic` callback receives the current cached value and returns the
130
- provisional one. When the server delta arrives it replaces the optimistic
131
- entry; on failure the cache reverts.
132
- - `pending` is `true` while the call is in flight — disable the submit button
133
- with it.
134
- - **Offline queue:** mutations made while disconnected are queued by
135
- `LunoraClient` and replayed on reconnect (client-id-keyed, so they aren't
136
- double-applied).
160
+ - `optimisticUpdate` names the query it patches because nothing can infer that
161
+ `todos.add` affects `todos.list`. `store.getAllQueries(fn)` lists every
162
+ subscribed args variant of a query so you can patch each one.
163
+ - The provisional row must match the query's element shape, including
164
+ `_id`/`_creationTime`, or the UI flickers when the real row lands.
165
+ - The per-call `optimistic: (current) => next` shortcut only patches a
166
+ subscription under the mutation's own reference and args (a counter, a doc by
167
+ id). For the add-updates-list shape above it is a silent no-op.
168
+ - `pending` stays `true` until every overlapping call from this hook settles;
169
+ use it to disable the submit button.
170
+ - Offline, mutations are queued by `LunoraClient` and replayed on reconnect,
171
+ keyed by client id so they aren't applied twice.
137
172
 
138
173
  ## Pagination, Connection, Presence
139
174
 
140
- - `usePaginatedQuery` / `useInfiniteQuery` — cursor pagination over a query that
141
- ends in `.paginate(...)` on the server.
175
+ The server query takes `paginationOpts` and returns `.paginate(...)` (see
176
+ `lunora-functions`). The hook supplies the cursor:
177
+
178
+ ```tsx
179
+ const { results, status, loadMore, error } = usePaginatedQuery(api.messages.page, { channelId }, { initialNumItems: 20 });
180
+ // status: "LoadingFirstPage" | "CanLoadMore" | "LoadingMore" | "Exhausted"
181
+ ```
182
+
183
+ Pages are live ranges: inserts and deletes inside a loaded page grow or shrink
184
+ it in place without duplicating rows. There is no total count; subscribe to a
185
+ separate count query for "42 of 1,203". `useInfiniteQuery` is the
186
+ TanStack-style alternative.
187
+
142
188
  - `useConnectionStatus` — live socket state for an offline/reconnecting banner.
143
- - `usePresence` — who's-here + heartbeat (pairs with the `presence` registry
189
+ - `usePresence` — who's-here with heartbeat (pairs with the `presence` registry
144
190
  item).
145
- - `useAuth` + the `Authenticated` / `Unauthenticated` / `AuthLoading` gates —
146
- see `lunora-setup-auth`.
191
+ - `useAuth` + `Authenticated` / `Unauthenticated` / `AuthLoading` — see
192
+ `lunora-setup-auth`.
193
+
194
+ ## Live Topics
195
+
196
+ For an event with no query behind it ("a comment was posted"), the server
197
+ publishes to a named topic and the browser follows topics over one shared SSE
198
+ connection (shared when the connection options match). Declare the stream once, mount its two handlers on the HTTP router,
199
+ and follow topics with the adapter's hook (all return `{ lastEvent, error }`):
200
+
201
+ | Package | Primitive |
202
+ | ---------------------- | ------------------------- |
203
+ | `@lunora/react`, `vue` | `useLiveTopic` |
204
+ | `@lunora/solid` | `createLiveTopic` |
205
+ | `@lunora/svelte` | `liveTopic` (a store) |
206
+ | `@lunora/angular` | `liveTopic` (signals) |
207
+ | `@lunora/react-native` | re-exports `useLiveTopic` |
208
+
209
+ ```tsx
210
+ const { lastEvent, error } = useLiveTopic({ url: "/live/posts/connect", topic: `post:${postId}`, onEvent: (payload) => refresh(payload) });
211
+ ```
212
+
213
+ - Several hooks with the same URL, credentials, headers, `retryDelay`, `maxDelayMs` and
214
+ `sessionKey` share a single connection; the last to unmount closes it. On a
215
+ cookie-authenticated stream pass `sessionKey` (the user id), or the connection
216
+ outlives a sign-out and keeps the previous user's topics.
217
+ - Publish from server code with `ctx.live.publish(topic, payload, { stream })`.
218
+ `ctx.live` exists only on actions, HTTP actions, queue consumers and scheduled
219
+ actions, NOT on a query or mutation. It is always present on an HTTP action
220
+ but typed optional on an `action` and a queue consumer, so write
221
+ `ctx.live?.publish(...)` there. To tell a page about a write, have the
222
+ mutation `ctx.scheduler.runAfter(0, internal.x.publish, args)`: it is held until
223
+ the commit, so a rolled-back write sends nothing. If the page already has a
224
+ `useQuery` over those rows, skip the event.
225
+ - Without `onSubscribe` every subscribe is DENIED (unless `allowAnonymousControl`
226
+ admits anonymous callers). Only a literal `true` allows.
227
+ - Delivery is at least once (a retried action publishes again) and shard-local
228
+ (no fan-out across Durable Objects). Put an id in the payload to dedupe.
229
+ - React Native's stock `fetch` does not stream, so events never arrive; use a
230
+ streaming `fetch` such as `expo/fetch`.
231
+ - Live streams are native on Cloudflare and celld, emulated on Node. Codegen
232
+ refuses an app that reads `ctx.live` on a target that withholds them.
147
233
 
148
234
  ## `@lunora/db` — TanStack DB Collections
149
235
 
150
- For richer client state (indexed local collections, cross-query joins, a durable
151
- offline-transactions outbox), use `@lunora/db` instead of raw hooks. Scaffold
152
- with `vis generate lunora-collections` (wires `defineCollections` from your
153
- schema + functions into live TanStack DB collections). Reach for it when the app
154
- needs client-side indexes/joins or a persistent optimistic outbox; raw `useQuery`
155
- /`useMutation` are enough for straightforward live lists.
156
-
157
- ## Common Pitfalls
158
-
159
- 1. **Creating `LunoraClient` inside a component.** It re-opens the socket every
160
- render — create it once at module scope.
161
- 2. **Treating `undefined` as empty.** `undefined` is "loading", `[]` is "loaded,
162
- empty" — branch on both.
163
- 3. **Broad query args.** A subscription keyed too broadly re-renders on
164
- unrelated writes; scope `args` to what the component shows.
165
- 4. **Optimistic shape drift.** The provisional value must match the query's
166
- element shape (including `_id`/`_creationTime`) or the UI flickers when the
167
- real delta lands.
236
+ For indexed local collections, cross-query joins, or a durable offline outbox,
237
+ use `@lunora/db` (peer deps `@tanstack/db`, `@tanstack/offline-transactions`).
238
+ Plain `useQuery` / `useMutation` are enough for straightforward live lists.
239
+
240
+ ```ts
241
+ import { defineCollections } from "@lunora/db";
242
+ import type { LunoraClient } from "lunorash/client";
243
+
244
+ import { api } from "../lunora/_generated/api";
245
+ import type { Doc, Id } from "../lunora/_generated/dataModel";
246
+
247
+ export const createCollections = (client: LunoraClient) =>
248
+ defineCollections(client, {
249
+ messages: {
250
+ list: api.messages.list,
251
+ scopeBy: "channelId", // the .shardBy column
252
+ insert: {
253
+ mutation: api.messages.send,
254
+ optimistic: (input: Omit<Doc<"messages">, "_id" | "_creationTime">, id) => ({ _id: id as Id<"messages">, _creationTime: Date.now(), ...input }),
255
+ toArgs: (row) => ({ channelId: row.channelId, id: row._id, text: row.text }),
256
+ },
257
+ },
258
+ });
259
+ // → db.collections.* (feed useLiveQuery), db.actions.* (optimistic writes),
260
+ // db.scope.* (re-point sharded collections), db.executor (the outbox)
261
+ ```
262
+
263
+ Call `defineCollections` once and treat its collections as the single source of
264
+ truth per table. Optimistic writes and sync deltas land only on that instance,
265
+ so a second instance or a copy of the rows in your own store drifts: derived
266
+ indexes (trees, search, undo captures) built from the copy miss new rows and
267
+ hold stale ones, while `useLiveQuery` still looks correct.
168
268
 
169
269
  ## Checklist
170
270
 
171
- - [ ] `LunoraClient` created once at module scope; app wrapped in the provider.
172
- - [ ] Live reads use `useQuery`; `undefined` handled as loading.
173
- - [ ] Writes use `useMutation`; `pending` disables submit; `optimistic` matches
174
- the row shape.
175
- - [ ] Query `args` scoped narrowly to avoid over-broad re-renders.
176
- - [ ] Pagination via `usePaginatedQuery`/`useInfiniteQuery` over `.paginate`.
177
- - [ ] Considered `@lunora/db` if the app needs local indexes/joins or an outbox.
271
+ - [ ] `LunoraClient` created once at module scope and registered the way the
272
+ adapter expects.
273
+ - [ ] `undefined` handled as loading; `"skip"` used while args are incomplete;
274
+ `onError` wired where a failure must be visible.
275
+ - [ ] Reads and writes on `.shardBy` tables pass `shardKey`.
276
+ - [ ] Mutations destructure `mutate`; `pending` disables submit;
277
+ `optimisticUpdate` rows match the query's element shape.
278
+ - [ ] Lists that grow use `usePaginatedQuery` over a `.paginate` query.
279
+ - [ ] `@lunora/db`: one `defineCollections` instance; no parallel copy of rows.
280
+ - [ ] Events that are not rows use a live topic, published from an action (via
281
+ `ctx.scheduler` after a write); data a query could return stays a `useQuery`.