@xnetjs/react 0.0.2 → 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.
package/README.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  React hooks for xNet -- the primary API for building xNet applications.
4
4
 
5
+ > **Status:** Mixed
6
+ > Stable root contract: `XNetProvider`, `useXNet`, `useQuery`, `useMutate`, `useNode`, `useIdentity`, `ErrorBoundary`, `OfflineIndicator`
7
+ > Experimental entrypoints: `@xnetjs/react/database`, `@xnetjs/react/experimental`
8
+ > Internal entrypoint: `@xnetjs/react/internal`
9
+
10
+ See [`docs/reference/api-lifecycle-matrix.md`](../../docs/reference/api-lifecycle-matrix.md) for the current lifecycle table and migration guidance.
11
+
5
12
  ## Installation
6
13
 
7
14
  ```bash
@@ -36,7 +43,11 @@ function App() {
36
43
  config={{
37
44
  nodeStorage: new MemoryNodeStorageAdapter(),
38
45
  authorDID: identity.did,
39
- signingKey: privateKey
46
+ signingKey: privateKey,
47
+ runtime: {
48
+ mode: 'worker',
49
+ fallback: 'main-thread'
50
+ }
40
51
  }}
41
52
  >
42
53
  <TaskApp />
@@ -45,6 +56,8 @@ function App() {
45
56
  }
46
57
  ```
47
58
 
59
+ `XNetProvider` now exposes runtime policy explicitly. Use `useXNet().runtimeStatus` to inspect the requested mode, active mode, and any visible fallback when bootstrapping web, Electron, or test environments.
60
+
48
61
  ## Hook Categories
49
62
 
50
63
  ```mermaid
@@ -134,10 +147,174 @@ const { data: task } = useQuery(TaskSchema, taskId)
134
147
  const { data: todoTasks } = useQuery(TaskSchema, {
135
148
  where: { status: 'todo' },
136
149
  orderBy: { createdAt: 'desc' },
137
- limit: 20
150
+ page: { first: 20 }
151
+ })
152
+ ```
153
+
154
+ Legacy `limit` and `offset` options remain supported. Prefer `page.first` for new bounded reads; it lowers to the same descriptor as `limit` until cursor pagination lands.
155
+
156
+ **Cursor pagination:**
157
+
158
+ ```tsx
159
+ const {
160
+ data: tasks,
161
+ fetchNextPage,
162
+ hasMore,
163
+ isFetchingNextPage
164
+ } = useInfiniteQuery(TaskSchema, {
165
+ where: { status: 'todo' },
166
+ orderBy: { updatedAt: 'desc' },
167
+ pageSize: 50
168
+ })
169
+
170
+ await fetchNextPage()
171
+ ```
172
+
173
+ `useInfiniteQuery` is a convenience wrapper over the same `useQuery` descriptor runtime. It requests pages with `page.after`, accumulates loaded pages, and returns both flattened `data` and per-page `pages`.
174
+
175
+ Use `page.count` to control count work when a source cannot answer exact totals cheaply:
176
+
177
+ ```tsx
178
+ const { pageInfo } = useQuery(TaskSchema, {
179
+ orderBy: { updatedAt: 'desc' },
180
+ page: { first: 50, count: 'estimate' }
181
+ })
182
+
183
+ console.log(pageInfo.totalCount, pageInfo.countMode) // number | null, exact | estimate | none
184
+ ```
185
+
186
+ **Materialized views:**
187
+
188
+ Use `materializedView` for hot saved views that should reuse a storage-backed result ID list across renders and pages.
189
+
190
+ ```tsx
191
+ const {
192
+ data: openTasks,
193
+ materialized,
194
+ plan
195
+ } = useQuery(TaskSchema, {
196
+ where: { status: 'todo' },
197
+ orderBy: { updatedAt: 'desc' },
198
+ page: { first: 50 },
199
+ materializedView: {
200
+ viewId: 'tasks.todo.by-updated-desc',
201
+ maxAgeMs: 30_000
202
+ }
203
+ })
204
+
205
+ console.log(materialized?.cacheHit, plan?.materializedRefreshReason)
206
+ ```
207
+
208
+ `viewId` should be stable, descriptive, and scoped to the view semantics, such as `tasks.todo.by-updated-desc`. Use `maxAgeMs` when a cached view may be reused for a bounded time even if no writes invalidate it. Set `forceRefresh: true` for explicit refresh actions; the query result exposes `materialized.cacheHit`, `materialized.rowCount`, and diagnostic `plan.materializedRefreshReason`.
209
+
210
+ Materialized views are an optimization for plaintext, storage-queryable local data. Stores with read authorization or encrypted node content bypass storage materialization and evaluate after auth/decryption so hidden or encrypted properties are not leaked through index counts, SQL, or materialized row IDs.
211
+
212
+ **Local and remote reads:**
213
+
214
+ `useQuery` defaults to local reads. Main-thread runtimes can opt into progressive remote reads by supplying a `remoteNodeQueryClient` to `XNetProvider` and requesting a remote execution mode.
215
+
216
+ ```tsx
217
+ <XNetProvider
218
+ config={{
219
+ nodeStorage,
220
+ authorDID,
221
+ signingKey,
222
+ remoteNodeQueryClient: hubQueryClient,
223
+ remoteNodeQueryRouting: {
224
+ localRowThreshold: 10_000,
225
+ hybridRowThreshold: 100_000
226
+ }
227
+ }}
228
+ >
229
+ <App />
230
+ </XNetProvider>
231
+ ```
232
+
233
+ ```tsx
234
+ const { data, source, completeness, staleness, verification, error } = useQuery(TaskSchema, {
235
+ where: { status: 'todo' },
236
+ page: { first: 50, count: 'estimate' },
237
+ mode: 'local-then-remote',
238
+ source: 'hub'
138
239
  })
139
240
  ```
140
241
 
242
+ `mode: 'local-then-remote'` renders the local snapshot first, then merges hub or federated results by node ID while preserving the newest `updatedAt` version. Remote failures keep the local snapshot and expose `error`, `source: 'hybrid'`, and partial `completeness` metadata. `mode: 'remote'` uses the remote client as the primary source and does not hydrate local results first.
243
+
244
+ `source: 'auto'` keeps the read local by default, then lets the main-thread bridge request a `local-then-remote` refresh when a configured `remoteNodeQueryClient` exists and the first local result crosses `remoteNodeQueryRouting` thresholds. Search and spatial descriptors can also opt into remote completion through the same threshold config.
245
+
246
+ `mode: 'stream'` keeps the same React API while allowing a remote client to push `snapshot`, `insert`, `update`, `delete`, `reset`, `progress`, and `error` events into the bridge cache. The main-thread bridge starts a remote stream when the query is subscribed, stops it when the last subscriber unmounts, and falls back to a one-shot remote query when a client exposes `query()` but not `stream()`. Stream queries expose `stream` metadata on the hook result and appear in the Query Debugger stream timeline when devtools are mounted.
247
+
248
+ ```tsx
249
+ const { data, stream } = useQuery(TaskSchema, {
250
+ where: { status: 'todo' },
251
+ mode: 'stream',
252
+ source: 'hub'
253
+ })
254
+
255
+ console.log(stream?.lastEvent, stream?.status, stream?.progress?.phase)
256
+ ```
257
+
258
+ ```ts
259
+ const hubQueryClient = {
260
+ async query(request) {
261
+ return hub.fetchNodeQuery(request)
262
+ },
263
+ stream(request, observer) {
264
+ const stream = hub.openNodeQueryStream(request)
265
+ stream.on('event', (event) => observer.next(event))
266
+ stream.on('error', (error) => observer.error?.(error))
267
+ stream.on('close', () => observer.complete?.())
268
+ return () => stream.close()
269
+ },
270
+ subscribeInvalidations(observer) {
271
+ const unsubscribe = hub.onNodeQueryInvalidation((event) => {
272
+ observer.next({
273
+ type: 'node-query/invalidate',
274
+ schemaId: event.schemaId,
275
+ nodeIds: event.nodeIds,
276
+ reason: 'poke'
277
+ })
278
+ })
279
+ return unsubscribe
280
+ }
281
+ }
282
+ ```
283
+
284
+ Remote metadata is surfaced on the hook result:
285
+
286
+ - `completeness` explains whether remote data is complete, partial, or unknown.
287
+ - `staleness` reports whether the remote source is fresh, stale, or unknown.
288
+ - `verification` reports whether remote nodes were verified, unverified, failed, or mixed.
289
+
290
+ Remote invalidation pokes refresh matching active remote-capable queries without clearing their current local or hybrid snapshot. Worker remote transport and hub-side authorization enforcement are still roadmap items tracked in the exploration.
291
+
292
+ **Advanced AST reads:**
293
+
294
+ `useFind` is the guarded bridge between the canonical `QueryAST` in `@xnetjs/data` and the current React read runtime. Today it executes node-query ASTs that lower cleanly to `useQuery` descriptors: schema match, `eq` predicates, `and` conjunctions, ordering, pagination, and loaded-snapshot aggregates. Relation includes, query sets, and non-equality predicates return a planner error with `blockers` instead of silently running a partial query.
295
+
296
+ ```tsx
297
+ import { count, defineNodeQueryAST, queryOperators } from '@xnetjs/data'
298
+ import { useFind } from '@xnetjs/react'
299
+
300
+ const task = queryOperators<(typeof TaskSchema)['_properties']>()
301
+
302
+ const openTaskQuery = defineNodeQueryAST(TaskSchema, {
303
+ where: task.eq('status', 'todo'),
304
+ orderBy: { updatedAt: 'desc' },
305
+ page: { first: 50, count: 'estimate' },
306
+ aggregates: [count('visibleTasks')]
307
+ })
308
+
309
+ const { data, aggregates, canExecute, blockers, plannerGate } = useFind(TaskSchema, openTaskQuery)
310
+ ```
311
+
312
+ `aggregates.scope` is currently `loaded-snapshot`, so grouped and scalar aggregates are computed from the rows loaded into the hook result. Use this for visible summaries and saved/shared descriptors that should pass planner validation before React subscribes. Keep relation includes, query sets, and storage/hub aggregate pushdown behind the canonical AST planner until the dedicated executors land.
313
+
314
+ **Query API roadmap:**
315
+
316
+ `useQuery` is the stable read hook for xNet applications today. The consolidated roadmap for richer local and remote reads, pagination metadata, streaming, realtime sync, materialized views, search, spatial queries, and future relation-aware planning is documented in [0139 Improving The useQuery API](../../docs/explorations/0139_[x]_IMPROVING_THE_USEQUERY_API.md), with execution follow-up tracked in the [useQuery API roadmap implementation plan](../../docs/plans/usequery-api-roadmap/README.md).
317
+
141
318
  ### `useMutate` -- Write Data
142
319
 
143
320
  Create, update, and delete nodes.
@@ -190,6 +367,33 @@ await mutate([
190
367
  ])
191
368
  ```
192
369
 
370
+ **Bulk deterministic imports:**
371
+
372
+ `useMutate().bulk()` exposes the same batch write path as `NodeStore.batchWrite()` through the active
373
+ DataBridge. Use it for importer, restore, migration, or AI-assisted bulk-edit surfaces where the UI
374
+ needs counters and phase timings instead of per-node mutation results.
375
+
376
+ ```tsx
377
+ const { bulk, isPending } = useMutate()
378
+
379
+ const result = await bulk({
380
+ kind: 'deterministic-import',
381
+ drafts: socialDrafts,
382
+ policy: {
383
+ indexMode: 'touched',
384
+ notificationMode: 'batch',
385
+ syncMode: 'defer'
386
+ }
387
+ })
388
+
389
+ console.log(result.nodeIds.length, result.timings.applyMs, result.storage?.propertyRowsWritten)
390
+ ```
391
+
392
+ Bulk writes are still signed NodeStore writes. The batch policy controls indexing and live
393
+ notification cost; `syncMode: 'defer'` is available for runtimes that can coalesce outbound
394
+ replication. `touched` indexes are the default import choice for immediate query correctness without a
395
+ whole-schema rebuild.
396
+
193
397
  ### `useNode` -- Rich Text Editing
194
398
 
195
399
  Load a node with its Y.Doc for collaborative rich text editing.