@molecule/app-query-solid 0.0.0-stage → 1.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
@@ -1,3 +1,802 @@
1
- # Temporary Holding Version
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-11-14T17:17:22.084Z
7
+ -->
2
8
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
9
+ # @molecule/app-query-solid
10
+
11
+ Solid primitives for `@molecule/app-query`.
12
+
13
+ **Load page data with {@link useQuery}, not `fetch` inside a `createEffect`.** A hand-written
14
+ load effect that cancels its request on cleanup (a `cancelled` flag, or an `AbortController`)
15
+ re-runs its cleanup on EVERY re-run whenever one of its tracked dependencies is a function
16
+ created inline each run — `const [messages, setError] = useApiErrors()` returning arrow
17
+ functions is the usual source. The effect's own guard (`if (loaded === slug) return`) then
18
+ returns without refetching, so the response is discarded whenever it arrives after a
19
+ re-run: always on a remote server, never on localhost, which is why the page passes locally
20
+ and fails on the live URL. `useQuery` subscribes once per key, keeps its request stable
21
+ across updates, and aborts it only when the key changes or the page unmounts.
22
+
23
+ {@link useQuery} observes one document from the app's shared cache and
24
+ returns cached data on the first read; {@link usePrefetch} and
25
+ {@link intentPrefetchProps} warm a document when a person is about to
26
+ open it. Together they make a detail page open with no loading state.
27
+
28
+ This package needs a bonded client: install `@molecule/app-query` with a bond
29
+ (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
30
+ `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
31
+
32
+ **Keep displayed records on the query cache.** Render `query.data` directly. A custom
33
+ mutation handler publishes its saved response with `query.setData(saved)`; every observer
34
+ and the next visit receive it, and subsequent refreshes still update the view. A local
35
+ signal copy hydrated only once per record hides later query answers. Editable form
36
+ drafts remain local until saved. Prefer {@link createQueryResource} for a complete resource;
37
+ its writes already publish the response and refresh its tracked collections.
38
+
39
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
40
+ > It is written to be read by coding agents as much as by people, and is generated from this
41
+ > package's source — edit `src/index.ts` JSDoc, not this file.
42
+
43
+ ## Quick Start
44
+
45
+ ```tsx
46
+ import { Match, Show, Switch } from 'solid-js'
47
+ import { getClient, isHttpError } from '@molecule/app-http'
48
+ import { t } from '@molecule/app-i18n'
49
+ import { intentPrefetchProps, useQuery } from '@molecule/app-query-solid'
50
+
51
+ interface PackageDocument {
52
+ name: string
53
+ description: string
54
+ }
55
+
56
+ const packageQuery = (name: string) => ({
57
+ key: ['package', name],
58
+ fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
59
+ try {
60
+ const response = await getClient().get<PackageDocument | null>(
61
+ `/data/packages/${encodeURIComponent(name)}.json`,
62
+ { signal },
63
+ )
64
+ return response.data
65
+ } catch (error) {
66
+ if (isHttpError(error) && error.status === 404) return null
67
+ throw error
68
+ }
69
+ },
70
+ })
71
+
72
+ function PackageLink(props: { name: string }) {
73
+ return (
74
+ <a href={`/packages/${props.name}`} {...intentPrefetchProps(packageQuery(props.name))}>
75
+ {props.name}
76
+ </a>
77
+ )
78
+ }
79
+
80
+ function PackagePage(props: { name: string }) {
81
+ // The options are an accessor, so a changed name (route param, input) re-keys
82
+ // the observer on the same mounted component, the way React re-renders useQuery.
83
+ const query = useQuery(() => packageQuery(props.name))
84
+ const loaded = (): PackageDocument | null => {
85
+ if (query.status === 'error') return null
86
+ if (query.status === 'idle' || query.status === 'loading') return null
87
+ if (query.data === undefined || query.data === null) return null
88
+ return query.data
89
+ }
90
+ return (
91
+ <Switch>
92
+ <Match when={query.status === 'error'}>
93
+ <p role="alert">
94
+ {t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' })}
95
+ </p>
96
+ </Match>
97
+ <Match when={query.status === 'idle' || query.status === 'loading'}>
98
+ <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
99
+ </Match>
100
+ <Match when={query.data === undefined || query.data === null}>
101
+ <p>{t('packages.notFound', undefined, { defaultValue: 'Package not found.' })}</p>
102
+ </Match>
103
+ <Match when={loaded()} keyed>
104
+ {(doc) => (
105
+ <article>
106
+ <h1>{doc.name}</h1>
107
+ <p>{doc.description}</p>
108
+ </article>
109
+ )}
110
+ </Match>
111
+ </Switch>
112
+ )
113
+ }
114
+ ```
115
+
116
+ A list whose page and filter live in the URL: derive the key from the route and pass
117
+ `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
118
+ until the next page answers. The app's HTTP client sends the session, so the viewer is part of
119
+ what the answer depends on: key on it and pass the same value as `principal` — an account
120
+ switch then drops the previous account's rows at once. Pass `null` while the session is still
121
+ being restored (`status === 'loading'`; the HTTP client holds the request until then anyway),
122
+ so restoring a session never swaps a key that already rendered rows.
123
+
124
+ ```tsx
125
+ import { For, Show } from 'solid-js'
126
+ import { unwrapList } from '@molecule/app-http'
127
+ import { useAuth, useHttpClient, useListRoute, useTranslation } from '@molecule/app-solid'
128
+ import { useQuery } from '@molecule/app-query-solid'
129
+
130
+ interface Invoice {
131
+ id: string
132
+ number: string
133
+ }
134
+
135
+ function InvoiceList() {
136
+ const http = useHttpClient()
137
+ const { t } = useTranslation()
138
+ const { status, user } = useAuth<{ id: string }>()
139
+ const list = useListRoute({ pageSize: 20, filters: { status: {} } })
140
+ const viewer = (): string => (user() ? String(user().id) : 'anonymous')
141
+ const query = useQuery(() =>
142
+ status() === 'loading' || !list.canLoad
143
+ ? null
144
+ : {
145
+ key: ['invoices', viewer(), list.filters, list.page],
146
+ principal: viewer(),
147
+ keepPreviousData: true,
148
+ fetch: async (signal: AbortSignal) =>
149
+ unwrapList<Invoice>(
150
+ await http.get('/api/invoices', {
151
+ signal,
152
+ params: { ...list.filters, limit: list.pageSize, offset: list.offset },
153
+ }),
154
+ ),
155
+ },
156
+ )
157
+
158
+ // Status renders outside the item list (it is not an item), and the empty state
159
+ // describes only the key on screen, never a retained previous page.
160
+ return (
161
+ <section>
162
+ <Show when={query.isFetching || status() === 'loading'}>
163
+ <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
164
+ </Show>
165
+ <Show when={query.status === 'error'}>
166
+ <p role="alert">
167
+ {t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}
168
+ </p>
169
+ </Show>
170
+ <ul>
171
+ <For each={query.data ?? []}>
172
+ {(invoice) => (
173
+ <li>
174
+ <a href={`/invoices/${invoice.id}`}>{invoice.number}</a>
175
+ </li>
176
+ )}
177
+ </For>
178
+ </ul>
179
+ <Show when={!query.isPreviousData && query.data?.length === 0}>
180
+ <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
181
+ </Show>
182
+ <a href={list.href({ page: list.page + 1 })}>
183
+ {t('common.next', undefined, { defaultValue: 'Next page' })}
184
+ </a>
185
+ </section>
186
+ )
187
+ }
188
+ ```
189
+
190
+ A mutation or a failed load has to change a page that is ALREADY mounted, and
191
+ the cache never starts that request by itself: `set()` paints a mutation's own
192
+ response, `invalidate()` marks what it affects for the next mount, and an
193
+ explicit `fetch()` retries into the mounted page.
194
+
195
+ ```tsx
196
+ import { getClient } from '@molecule/app-http'
197
+ import { t } from '@molecule/app-i18n'
198
+ import { getQueryClient } from '@molecule/app-query'
199
+
200
+ // The key names what the document actually depends on — here the signed-in
201
+ // principal, the filter and the page. Another principal's feed is a
202
+ // different document, so an invalidation scoped to this one leaves it alone.
203
+ const feedKey = (principal: string, filter: string, page: number) =>
204
+ ['feed', principal, filter, page] as const
205
+
206
+ const feedOptions = (principal: string, filter: string, page: number) => ({
207
+ key: feedKey(principal, filter, page),
208
+ fetch: async (signal: AbortSignal) =>
209
+ (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
210
+ })
211
+
212
+ async function setFollowing(principal: string, authorId: string, follow: boolean) {
213
+ const client = getQueryClient()
214
+ const http = getClient()
215
+ const { data: body } = follow
216
+ ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
217
+ : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
218
+ // The response IS the document: paint it now, with no second round trip.
219
+ // (If it were only a count or a flag, skip set() and invalidate() instead.)
220
+ client.set(feedKey(principal, 'following', 1), body.feed)
221
+ // Future reads of every feed this principal owns are stale.
222
+ client.invalidate(['feed', principal])
223
+ }
224
+
225
+ function Retry(props: { principal: string }) {
226
+ return (
227
+ <button
228
+ onClick={() => {
229
+ // invalidate() alone would leave the mounted page on its error;
230
+ // an explicit fetch retries into it. useQuery shows the outcome.
231
+ void getQueryClient()
232
+ .fetch(feedOptions(props.principal, 'following', 1))
233
+ // The mounted useQuery observer presents this failure via status/error.
234
+ .catch((_error) => {})
235
+ }}
236
+ >
237
+ {t('common.retry', undefined, { defaultValue: 'Retry' })}
238
+ </button>
239
+ )
240
+ }
241
+ ```
242
+
243
+ One API resource described once, for every page that reads or changes it.
244
+ `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
245
+ as functions that put the server's record into the cache and fetch the lists on screen again,
246
+ so a page never mirrors a response into a local signal. A flag the API models as a sub-path
247
+ (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
248
+ record and is the `commit` of `useOptimisticValue`.
249
+
250
+ ```tsx
251
+ import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
252
+ import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-solid'
253
+ import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-solid'
254
+
255
+ interface Invoice {
256
+ id: string
257
+ number: string
258
+ flagged: boolean
259
+ }
260
+
261
+ export const invoices = createQueryResource<Invoice>({
262
+ name: 'invoices',
263
+ path: '/invoices',
264
+ http: getClient,
265
+ readList: (response) => unwrapList<Invoice>(response),
266
+ readOne: (response) => unwrapSingle<Invoice>(response),
267
+ })
268
+
269
+ function InvoicePage(props: { id: string }) {
270
+ const { user } = useAuth<{ id: string }>()
271
+ const { t } = useTranslation()
272
+ const viewer = (): string => {
273
+ const current = user()
274
+ return current ? String(current.id) : 'anonymous'
275
+ }
276
+ const query = useQuery(() => invoices.detail(viewer(), props.id))
277
+ return (
278
+ <QueryContent
279
+ query={query}
280
+ pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
281
+ missing={
282
+ <p role="alert">
283
+ {t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}
284
+ </p>
285
+ }
286
+ error={() => (
287
+ <p role="alert">
288
+ {t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}
289
+ </p>
290
+ )}
291
+ >
292
+ {(invoice) => <FlagButton invoice={invoice()} viewer={viewer()} />}
293
+ </QueryContent>
294
+ )
295
+ }
296
+
297
+ function FlagButton(props: { invoice: Invoice; viewer: string }) {
298
+ const { t } = useTranslation()
299
+ // An accessor, so each saved or refreshed invoice syncs into the same controller.
300
+ const flag = useOptimisticValue(() => ({
301
+ value: props.invoice.flagged,
302
+ commit: async (on: boolean) =>
303
+ (await invoices.toggle(props.viewer, props.invoice.id, 'flag', on)).flagged,
304
+ }))
305
+ return (
306
+ <button type="button" aria-pressed={flag.value()} onClick={() => flag.update((on) => !on)}>
307
+ {flag.value()
308
+ ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
309
+ : t('invoice.flag', undefined, { defaultValue: 'Flag' })}{' '}
310
+ {props.invoice.number}
311
+ </button>
312
+ )
313
+ }
314
+ ```
315
+
316
+ A pager needs the whole response, including its total. Keep that read on the same resource
317
+ as its mutations, including alternate list paths; a separate hand-written `QueryOptions`
318
+ is outside the resource's refresh tracking.
319
+
320
+ ```typescript
321
+ import { getClient } from '@molecule/app-http'
322
+ import { createQueryResource } from '@molecule/app-query-solid'
323
+
324
+ interface TicketPage {
325
+ tickets: { id: string; subject: string }[]
326
+ total: number
327
+ }
328
+ const tickets = createQueryResource<TicketPage['tickets'][number]>({
329
+ name: 'tickets',
330
+ path: '/tickets',
331
+ http: getClient,
332
+ readOne: (response) => response.data as TicketPage['tickets'][number],
333
+ })
334
+ const page = tickets.listPage(
335
+ 'agent-1',
336
+ { limit: 10, offset: 20 },
337
+ (response) => response.data as TicketPage,
338
+ )
339
+ // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
340
+ // and tickets.refresh('agent-1') refresh this page too.
341
+ // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
342
+ // Use one canonical page reader per path; list() still returns only its own rows.
343
+ // For immediate deletion from an opaque page, add a fifth argument:
344
+ // (page, id) => {
345
+ // const rows = page.tickets.filter((row) => String(row.id) !== id)
346
+ // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
347
+ // }
348
+ ```
349
+
350
+ A resource mutation also waits out a pre-mutation list request before fetching again;
351
+ joining that older in-flight read alone would leave the new record absent.
352
+ Successful deletion removes a row immediately, including one just created through the
353
+ resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
354
+ successful create can recreate the identity. Opaque listPage envelopes need their own
355
+ removeFromPage adapter; no row or total property is guessed.
356
+
357
+ ## Type
358
+
359
+ `feature`
360
+
361
+ ## Installation
362
+
363
+ ```bash
364
+ npm install @molecule/app-query-solid @molecule/app-query solid-js
365
+ ```
366
+
367
+ ## API
368
+
369
+ ### Interfaces
370
+
371
+ #### `ResourceResponse`
372
+
373
+ The part of an HTTP response a resource reads.
374
+
375
+ ```typescript
376
+ interface ResourceResponse {
377
+ /** The parsed response body. */
378
+ data: unknown
379
+ }
380
+ ```
381
+
382
+ #### `ResourceHttp`
383
+
384
+ The HTTP client a resource calls: the app's own bonded client (`getClient()` from
385
+ `@molecule/app-http`) has this shape. Only what a resource uses is named here.
386
+
387
+ ```typescript
388
+ interface ResourceHttp {
389
+ /** Reads `path`; `signal` cancels it and `params` become the query string. */
390
+ get(
391
+ path: string,
392
+ options?: { signal?: AbortSignal; params?: Record<string, unknown> },
393
+ ): Promise<ResourceResponse>
394
+ /** Creates at `path`. */
395
+ post(path: string, body?: unknown): Promise<ResourceResponse>
396
+ /** Replaces at `path`. */
397
+ put(path: string, body?: unknown): Promise<ResourceResponse>
398
+ /** Changes part of the record at `path`. */
399
+ patch(path: string, body?: unknown): Promise<ResourceResponse>
400
+ /** Removes at `path`. */
401
+ delete(path: string): Promise<ResourceResponse>
402
+ }
403
+ ```
404
+
405
+ #### `QueryResourceConfig`
406
+
407
+ What {@link createQueryResource} needs to know about one resource.
408
+
409
+ ```typescript
410
+ interface QueryResourceConfig<T> {
411
+ /** The first element of every cache key of this resource, e.g. `'invoices'`. */
412
+ name: string
413
+ /** The collection's path under the API base, e.g. `'/invoices'`. */
414
+ path: string
415
+ /** The app's HTTP client, read on every call so a client bonded later is the one used. */
416
+ http: () => ResourceHttp
417
+ /** The field a record is addressed by in a URL. Defaults to `'id'`. */
418
+ id?: keyof T & string
419
+ /** The HTTP method the API updates a record with. Defaults to `'put'`. */
420
+ updateMethod?: 'put' | 'patch'
421
+ /** Reads the records out of a list response. Defaults to the body itself. */
422
+ readList?: (response: ResourceResponse) => T[]
423
+ /** Reads the record out of a detail or write response. Defaults to the body itself. */
424
+ readOne?: (response: ResourceResponse) => T | null
425
+ }
426
+ ```
427
+
428
+ #### `QueryResource`
429
+
430
+ The reads and writes {@link createQueryResource} returns.
431
+
432
+ ```typescript
433
+ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
434
+ /**
435
+ * `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
436
+ * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
437
+ */
438
+ list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
439
+ /**
440
+ * Options for a collection's whole page (rows plus totals), or a filtered collection path.
441
+ * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
442
+ * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
443
+ * Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
444
+ * immediately and keep stale list responses from restoring them.
445
+ */
446
+ listPage<Page>(
447
+ viewer: string,
448
+ params: Record<string, unknown>,
449
+ readPage: (response: ResourceResponse) => Page,
450
+ path?: string,
451
+ removeFromPage?: (page: Page, id: string) => Page,
452
+ ): QueryOptions<Page>
453
+ /**
454
+ * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
455
+ * observes nothing). A missing record resolves to null, not to an error.
456
+ */
457
+ detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null
458
+ /** Creates a record, shows it in the cache and refreshes the lists on screen. */
459
+ create(viewer: string, input: Create): Promise<T>
460
+ /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
461
+ update(viewer: string, id: string, input: Update): Promise<T>
462
+ /** Removes a record from detail and tracked row lists, then refreshes those lists. */
463
+ remove(viewer: string, id: string): Promise<void>
464
+ /**
465
+ * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
466
+ * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
467
+ * of `useOptimisticValue`.
468
+ * The saved detail is published before tracked lists finish refreshing; this promise waits
469
+ * for those refreshes. Render the shared controller's value and let it queue inverse clicks
470
+ * during that interval. A page-local busy guard can drop a click on the newly changed label.
471
+ */
472
+ toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
473
+ /** Fetches the lists on screen again, after a change this resource did not make itself. */
474
+ refresh(viewer: string): Promise<void>
475
+ }
476
+ ```
477
+
478
+ #### `UseQueryResult`
479
+
480
+ A mounted query's state and its explicit cache and refresh actions. The state
481
+ fields read as plain values at read time (each reads the observer's current
482
+ state), so a JSX binding that reads them re-renders when the document
483
+ changes, and a test can snapshot the object at any moment.
484
+
485
+ ```typescript
486
+ interface UseQueryResult<T> extends QueryState<T> {
487
+ /**
488
+ * Publish a saved document to this key and all its observers. Render `data`
489
+ * directly instead of copying it to local state: later cache updates then
490
+ * remain visible. A function receives this key's current cached document,
491
+ * never retained previous-page data. Returning `undefined` leaves the cache
492
+ * unchanged. A disabled (`null`) query does nothing, including not calling an
493
+ * updater. Like React state setters, wrap a function-valued document in an
494
+ * updater. A saved callback stays bound to its original key. The write
495
+ * supersedes older in-flight reads, using the bonded client's `set` contract.
496
+ */
497
+ setData: (value: T | ((previous: T | undefined) => T | undefined)) => void
498
+ /**
499
+ * Fetch this key again, even when its cached document is fresh. Observers
500
+ * receive the updated state. Resolves with that state, including an error
501
+ * when the request fails; a disabled (`null`) query resolves idle without a
502
+ * request.
503
+ */
504
+ refetch: () => Promise<QueryState<T>>
505
+ }
506
+ ```
507
+
508
+ #### `QueryContentProps`
509
+
510
+ A loaded document owns its controls; absent documents expose only status content.
511
+
512
+ ```typescript
513
+ interface QueryContentProps<T> {
514
+ /** State from useQuery, or any compatible query observer. */
515
+ query: Pick<QueryState<T>, 'data' | 'status' | 'error'>
516
+ /**
517
+ * Mounted only with a real document, including false, zero and an empty list. Runs once
518
+ * per loaded stretch with the document as an accessor (Solid's `<Show>` idiom): a new
519
+ * document reaches the same mounted content, so read it where it is used (`data()`).
520
+ */
521
+ children: (data: Accessor<NonNullable<T>>) => JSX.Element
522
+ /** Initial idle/loading content. Render a status node, never a fake item or action. */
523
+ pending?: JSX.Element
524
+ /** Content for a loaded null record. Null is distinct from an unfinished request. */
525
+ missing?: JSX.Element
526
+ /** A failed initial read. Cached data stays visible if its refresh fails. */
527
+ error?: (error: unknown) => JSX.Element
528
+ }
529
+ ```
530
+
531
+ #### `IntentPrefetchProps`
532
+
533
+ The handlers {@link intentPrefetchProps} returns.
534
+
535
+ ```typescript
536
+ interface IntentPrefetchProps {
537
+ onPointerEnter: () => void
538
+ onFocus: () => void
539
+ onTouchStart: () => void
540
+ }
541
+ ```
542
+
543
+ ### Functions
544
+
545
+ #### `prefetchQuery(options)`
546
+
547
+ Warms the cache for a document, when the connection can afford it (see
548
+ `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
549
+ in-flight document is skipped, and failures are swallowed.
550
+
551
+ ```typescript
552
+ function prefetchQuery<T>(options: QueryOptions<T>): void
553
+ ```
554
+
555
+ - `options` — Key, fetch, freshness.
556
+
557
+ #### `createQueryResource(config)`
558
+
559
+ Describe one API resource once and get its reads and writes on the shared cache.
560
+
561
+ A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
562
+ re-solve the same problems on every screen: a late answer for the previous page lands
563
+ over the current one, and a list still shows what it showed before a comment was added.
564
+ Here the reads are `useQuery` options (one key per
565
+ viewer, page and filter; the previous rows stay until the next answer) and every write puts
566
+ the server's own record into the cache and fetches the lists on screen again.
567
+
568
+ The factory supplies data operations. Mount a keyed
569
+ control inside `QueryContent` (your framework's query package: `@molecule/app-query-react`,
570
+ `-vue`, …) so it receives a loaded record and stays mounted during refresh.
571
+ For a server-backed toggle, use `useOptimisticValue` from your framework binding
572
+ (`@molecule/app-react`, `@molecule/app-vue`, …), or `OptimisticToggleButton` from its UI
573
+ package (`@molecule/app-ui-react`, …) for a boolean. Pass `toggle` as its
574
+ commit adapter, return the saved flag/count, and render the controller's value for the action
575
+ label too. Do not block clicks while that commit is pending. The resource example in
576
+ `@molecule/app-query-react` composes these APIs; a custom handler must provide the same
577
+ readiness and ordering itself.
578
+
579
+ Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
580
+ and the query provider are whatever the app bonded.
581
+
582
+ ```typescript
583
+ function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
584
+ config: QueryResourceConfig<T>,
585
+ ): QueryResource<T, Create, Update>
586
+ ```
587
+
588
+ - `config` — The resource's name, path, HTTP client and response readers.
589
+
590
+ **Returns:** List and detail query options, and create, update, remove, toggle and refresh.
591
+
592
+ #### `QueryContent(props)`
593
+
594
+ The loaded-data branch receives a non-null document. Pending, failed initial reads and
595
+ missing records never mount that branch, so its actions cannot swallow an early click.
596
+ Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
597
+ belong outside the list or record container rendered by `children`, and so does a refresh
598
+ line; the default fallbacks render nothing.
599
+
600
+ `children` runs ONCE per loaded stretch and receives the document as an accessor (Solid's
601
+ `<Show>` idiom), so a new document — a cache publication, a refresh, another key's record —
602
+ reaches the SAME mounted content, the way React re-renders the same components with it:
603
+ their local state (an optimistic toggle's pending save, an open menu) survives. Read the
604
+ accessor where the value is used: `{(invoice) => <FlagButton invoice={invoice()} />}`.
605
+
606
+ ```typescript
607
+ function QueryContent<T>(props: QueryContentProps<T>): JSX.Element
608
+ ```
609
+
610
+ - `props` — Query state, loaded content and optional status fallbacks.
611
+
612
+ **Returns:** Loaded content or the appropriate fallback, switching as the state changes.
613
+
614
+ #### `usePrefetch()`
615
+
616
+ A stable `prefetch(options)` function for event handlers.
617
+
618
+ ```typescript
619
+ function usePrefetch(): <T>(options: QueryOptions<T>) => void
620
+ ```
621
+
622
+ **Returns:** The prefetch function.
623
+
624
+ #### `intentPrefetchProps(options)`
625
+
626
+ Event handlers that warm a document at the first sign of intent: the
627
+ pointer arriving, keyboard focus, or a touch starting. Spread them onto a
628
+ link: `<a {...intentPrefetchProps(packageQuery(name))} />`.
629
+
630
+ ```typescript
631
+ function intentPrefetchProps<T>(options: QueryOptions<T>): IntentPrefetchProps
632
+ ```
633
+
634
+ - `options` — Key, fetch, freshness.
635
+
636
+ **Returns:** The handlers.
637
+
638
+ #### `useQuery(options)`
639
+
640
+ The document for the options' key, kept current: cached data is read on the
641
+ very first render (so a warmed page never flashes a loading state), a stale
642
+ or missing document is fetched, and every change re-renders what reads the
643
+ result. Pass `null` to observe nothing. A key change resets to that key's
644
+ state; the hook never hands a caller another key's document — unless the
645
+ caller opts into {@link QueryOptions.keepPreviousData}, and then only within
646
+ one {@link QueryOptions.principal}.
647
+
648
+ The request is stable across re-renders — a parent state change neither
649
+ restarts it nor cancels it, so a response that arrives after one still
650
+ lands. It is aborted only when the key changes or the component unmounts
651
+ (the `signal` given to `options.fetch`). Use this instead of a hand-written
652
+ `createEffect` + `fetch`: an effect whose `onCleanup` sets a `cancelled`
653
+ flag, and whose tracked dependencies include a function rebuilt each run,
654
+ cancels its own request on every run and then skips the refetch.
655
+ An explicit `refetch()` is an awaited cache fetch; it can finish after the
656
+ observer unmounts, like an explicit `client.fetch(options)` caller.
657
+
658
+ A component body runs once in Solid, so pass the options as an accessor when
659
+ any part of them can change (`() => packageQuery(props.name)`): a changed
660
+ key — or principal, or `keepPreviousData` flag — is then followed on the SAME
661
+ mounted hook, the way React re-renders `useQuery` with a new options object.
662
+
663
+ For a LIST, put the route's page, filter and selected view in the key and
664
+ pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
665
+ then keeps the rows already on screen until the new page answers, instead of
666
+ rendering a loading state over an empty list. The key names everything the
667
+ answer depends on, and the app's HTTP client sends the session, so a list the
668
+ server can filter or personalize per viewer puts the viewer in its key and
669
+ passes the same value as `principal` (`'anonymous'` when signed out): an
670
+ account switch then drops the previous account's document immediately. Only
671
+ an endpoint that answers every viewer the same takes a viewer-free key with
672
+ `principal: 'public'`.
673
+
674
+ For custom mutation handlers, `setData(saved)` publishes the server's response to this
675
+ key and every observer. Use `setData(current => next)` for a local cache update. Render
676
+ `data` directly; a component-local copy stops observing later server responses. Prefer
677
+ `createQueryResource` when the API's reads and writes can share one resource definition.
678
+ Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
679
+ so a visible action cannot return early because its initial record is still missing.
680
+ Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
681
+ from `@molecule/app-solid` or `OptimisticToggleButton` from `@molecule/app-ui-solid` to keep
682
+ their displayed label and queued clicks on the same state while a save finishes.
683
+
684
+ ```typescript
685
+ function useQuery<T>(options: QueryOptionsSource<T>): UseQueryResult<T>
686
+ ```
687
+
688
+ - `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`; or an accessor of either (the options a component recomputes from its props — every change is followed on the same instance).
689
+
690
+ **Returns:** The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
691
+
692
+ ## Injection Notes
693
+
694
+ ### Requirements
695
+
696
+ Peer dependencies:
697
+
698
+ - `@molecule/app-query` ^1.2.0
699
+ - `solid-js` ^1.8.0
700
+
701
+ ### Runtime Dependencies
702
+
703
+ - `@molecule/app-query`
704
+ - `solid-js`
705
+
706
+ - **`useQuery` reads the cache synchronously on the first render.** A
707
+ document prefetched from a hovered link, or seeded with `client.set()`
708
+ from a server-rendered JSON island, renders at once — no spinner, no
709
+ layout shift. Render loading from `status === 'idle' || status === 'loading'`;
710
+ `undefined` data can also accompany a completed error. A completed `null`
711
+ response is missing, not pending. The detail example treats only HTTP 404
712
+ or a successful null response as missing; other errors stay load failures.
713
+ The app's bonded HTTP client rejects non-2xx responses. Native `fetch`
714
+ resolves them, so a custom fetcher must check `response.ok` before JSON.
715
+ - **A component body runs once in Solid: pass the options as an accessor.**
716
+ `useQuery(() => packageQuery(props.name))` follows a changed name (route
717
+ param, input, parent state) on the same mounted hook, the way React
718
+ re-renders `useQuery` with a new options object. Options built once from
719
+ props are read once — a later prop change would not re-key the observer.
720
+ - **Mount a detail region and its actions only after its initial document arrives.**
721
+ A visible container is not a loaded document: a caller may wait for that container and
722
+ read its text once, or click its button, while `data` is still undefined. Put the loading
723
+ message outside the detail region, as in `PackagePage` above. Keep record-dependent
724
+ controls absent or natively disabled until the record exists; returning early inside
725
+ an enabled click handler loses that click. `client.set()` protects a cache mutation
726
+ from an older read, but cannot recover a click whose handler never sent the mutation.
727
+ - **The key is the identity.** Building `options` inside the accessor is
728
+ fine; the hook resubscribes only when the key's value changes, not when
729
+ the `fetch` closure does.
730
+ - **A key change normally resets to the new key's state.** For a list's own
731
+ page/filter/view change, opt into `keepPreviousData` with a `principal`;
732
+ `isPreviousData` tells you the rows on screen belong to the key you just
733
+ left. A completed response (including an empty list) replaces them, and a
734
+ changed principal drops them, so an account switch never shows the previous
735
+ account's rows. Do not emulate this with a local signal mirror of the
736
+ query data — that mirror is what serves stale rows under a new page, or
737
+ blanks the list on an update.
738
+ - **The key names the viewer whenever the answer can depend on it.** The
739
+ app's HTTP client sends the session, so the server may filter or
740
+ personalize even a list that guests can see (a `favorited` or `following`
741
+ flag), and the cache serves a key's document to whoever observes it,
742
+ across sign-in and sign-out. Key such a list on the viewer
743
+ (`user() ? String(user().id) : 'anonymous'`), pass the same value as
744
+ `principal`, and pass `null` while the session is still being restored
745
+ (`status === 'loading'`; the HTTP client holds the request until then
746
+ anyway), so restoring a session never swaps a key that already rendered
747
+ rows. A viewer-free key with `principal: 'public'` is only for an endpoint
748
+ that answers every viewer the same. A protected `useListRoute` view also
749
+ passes `null` while `canLoad` is false.
750
+ - **Render loading, empty and error status outside the item list**, and never
751
+ give a placeholder the item's own class or element shape: a list read by
752
+ the item class (or by `:first-child`) must contain only real items. An
753
+ empty array is a loaded empty state, not a missing response; render it
754
+ only when `isPreviousData` is not set, because a retained document belongs
755
+ to the key you just left.
756
+ - `intentPrefetchProps` spreads three handlers onto a link. It is a plain
757
+ function (not a primitive), so it works inside `<For>` too.
758
+ - Prefetching respects the browser's data-saver setting and skips 2G
759
+ connections (`shouldPrefetch()` in the core) — do not bypass that for
760
+ "important" links; the person can still click.
761
+ - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
762
+ entry and updates every observer of that key. After a mutation whose response is not the
763
+ whole document, `await query.refetch()` reloads the displayed list. It resolves with the
764
+ resulting state (including `status: 'error'` on failure); a disabled query stays idle.
765
+ Prefer `client.set(key, response)` when the mutation already returned the whole document.
766
+ - Errors are not thrown from the hook; read `status === 'error'` and
767
+ `error`. `client.invalidate()` does NOT refetch a mounted page — it only
768
+ marks documents stale, so the page keeps its error (or its old document)
769
+ until the app retries with `client.fetch(options)` or the page subscribes
770
+ again (a key change or a re-mount).
771
+ - After a mutation, `client.set(key, response)` paints the server's own
772
+ answer at once and supersedes an older fetch already in flight for that
773
+ key, so its response cannot undo the mutation. An existing `fetch()` caller
774
+ still settles independently of the cache write; read `client.get(key)` for the newest document.
775
+ `client.invalidate(prefix)` marks the affected reads stale for their next
776
+ mount. Which key and which scope is the app's decision: the cache does not
777
+ infer it from auth or form state.
778
+
779
+ Render resource-dependent lists and controls through {@link QueryContent}. Its child function
780
+ receives only loaded, non-null data; loading and error content never mount item actions.
781
+ It renders cached content during refresh and treats an empty list, false and zero as data.
782
+ The child runs once per loaded stretch and receives the document as an ACCESSOR (Solid's
783
+ `<Show>` idiom), so a saved or refreshed document reaches the same mounted controls, as React
784
+ re-renders them: call it where the value is read (`record()`), never once into a constant.
785
+ Put the list, or the record's own container (its card, header or profile block), inside the
786
+ child and every status line (loading, error, `isFetching` refresh) beside it, never inside it:
787
+ a reader that finds the container and reads its paragraph must read the record, not "Loading…".
788
+
789
+ ```tsx
790
+ <QueryContent
791
+ query={query}
792
+ pending={<p role="status">{loadingLabel}</p>}
793
+ missing={<p>{missingLabel}</p>}
794
+ error={() => <p role="alert">{errorLabel}</p>}
795
+ >
796
+ {(record) => <RecordActions record={record()} />}
797
+ </QueryContent>
798
+ ```
799
+
800
+ Keep every resource identity in the query key. A boundary cannot correct a query that supplies
801
+ another record's cached data. For a list, map real rows inside the child; never style a status
802
+ placeholder as a row. QueryContent is headless and owns no translations or styling.