@atom.io/template-spa-astro-ssr 0.0.3 → 0.0.5

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/.reylo.yaml CHANGED
@@ -1 +1 @@
1
- direct_url: file:./drafts.sqlite
1
+ direct_url: file:./inventory.sqlite
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # SPA + Astro SSR
2
2
 
3
- A starter with module-scoped atom definitions, server-rendered Astro islands, and typed database refreshes. It uses atom.io, @atom.io/spa, resumability/astro, Reylo over node:sqlite, and tRPC. Requires Node 24.12 or newer and TypeScript 7.1's content mappers (currently beta).
3
+ A starter with module-scoped atom definitions, server-rendered Astro islands, and an inventory workflow with editable stock counts, persistent saves, and fresh database reads. It uses atom.io, @atom.io/spa, resumability/astro, Reylo over node:sqlite, and tRPC. Requires Node 24.12 or newer and TypeScript 7.1's content mappers (currently beta).
4
4
 
5
5
  ## Run
6
6
 
@@ -26,25 +26,25 @@ pnpm --filter @atom.io/template-spa-astro-ssr dev
26
26
 
27
27
  ```
28
28
 
29
- The workspace uses local unpublished packages; a packed release replaces workspace dependency ranges with published versions. Development, build, and typecheck commands initialize drafts.sqlite from schema.sql and insert missing example rows without overwriting edits. Reylo checks queries against that schema using .reylo.yaml. The generated database is ignored by Git and excluded from the package.
29
+ The workspace uses local unpublished packages; a packed release replaces workspace dependency ranges with published versions. Development, build, and typecheck commands initialize inventory.sqlite from schema.sql and insert missing example rows without overwriting edits. Reylo checks queries against that schema using .reylo.yaml. The generated database is ignored by Git and excluded from the package.
30
30
 
31
- This is an on-demand Node server application. The Astro Node adapter serves both pages and the tRPC endpoint. Start production from the template directory so it can find drafts.sqlite; supply persistent storage for that file when deploying. Initialize the database before starting a new deployment.
31
+ This is an on-demand Node server application. The Astro Node adapter serves both pages and the tRPC endpoint. Start production from the template directory so it can find inventory.sqlite; supply persistent storage for that file when deploying. Initialize the database before starting a new deployment.
32
32
 
33
33
  ## Rendering and caching
34
34
 
35
- The starter uses on-demand SSR with Astro’s built-in memoryCache provider. The public drafts page has a 60-second TTL and no stale-while-revalidate window. A cache miss reads SQLite in a request-owned store and caches the complete HTML response, including its resumption sidecar. Hits reuse that snapshot; the first request after expiry renders a new one. There are no prerendered pages. The tRPC endpoint is outside the cached route rule and returns Cache-Control: no-store, so resets always read the database.
35
+ The starter uses on-demand SSR with Astro’s built-in memoryCache provider. The public stock-counting page has a 60-second TTL and no stale-while-revalidate window. A cache miss reads SQLite in a request-owned store and caches the complete HTML response, including its resumption seeds. Hits reuse that snapshot; the first request after expiry renders a new one. There are no prerendered pages. The tRPC endpoint is outside the cached route rule and returns Cache-Control: no-store, so resets always read the database.
36
36
 
37
37
  The cache belongs to one server process: it is lost on restart and is not shared across replicas. This is a small, self-contained deployment default; choose an infrastructure-backed provider when multiple instances need shared caching or invalidation. Astro disables caching in development. Build and preview the template to exercise the production cache.
38
38
 
39
- This template’s example data is public. When adapting it, cache the complete HTML response together with its resumption sidecar. The markup and initial values must come from the same render. Choose a freshness window and invalidation policy that match the data; do not cache a live atom.io store or reuse it across requests. Cache only responses whose data can be shared by everyone using the cache entry. Personalized snapshots need private caching or a correctly scoped cache key.
39
+ This template’s example data is public. When adapting it, cache the complete HTML response together with its resumption seeds. The markup and initial values must come from the same render. Choose a freshness window and invalidation policy that match the data; do not cache a live atom.io store or reuse it across requests. Cache only responses whose data can be shared by everyone using the cache entry. Personalized snapshots need private caching or a correctly scoped cache key.
40
40
 
41
- The initial browser load consumes that snapshot without immediately refetching it. Expiring or invalidating the server cache affects future page loads, not an already running browser store. Keep the explicit reset/tRPC path fresh so Refresh from database can fetch the current row. ClientRouter navigation continues to preserve live browser state rather than replacing edits with another server snapshot.
41
+ The initial browser load consumes that snapshot without immediately refetching it. Expiring or invalidating the server cache affects future page loads, not an already running browser store. Keep the explicit reset/tRPC path fresh so Reload from database can fetch the current row. ClientRouter navigation continues to preserve live browser state rather than replacing edits with another server snapshot.
42
42
 
43
- SSG is also compatible with resumption: the sidecar is produced during the build and remains that snapshot until the next deployment. Use it for routes whose freshness can follow deployments, while retaining on-demand API routes for resets. Astro's [on-demand rendering](https://docs.astro.build/en/guides/on-demand-rendering/) and [route caching](https://docs.astro.build/en/guides/caching/) documentation describe the route-level controls and cache providers.
43
+ SSG is also compatible with resumption: the seed data is produced during the build and remains that snapshot until the next deployment. Use it for routes whose freshness can follow deployments, while retaining on-demand API routes for resets. Astro's [on-demand rendering](https://docs.astro.build/en/guides/on-demand-rendering/) and [route caching](https://docs.astro.build/en/guides/caching/) documentation describe the route-level controls and cache providers.
44
44
 
45
45
  ## Try it
46
46
 
47
- Both views use the same two module-scoped document tokens in one browser store and resumption scope. The initial notes come directly from SQLite during SSR. The first island hydrates its existing DOM without making an RPC request. Type into a draft before scrolling to the second view: that delayed island mounts fresh and immediately shows the edit. Typing or refreshing a document updates both views; other documents retain their values. Refresh from database resets the atom, whose client closure calls tRPC for the latest row. The returned revision identifies that read.
47
+ Both views use the same two module-scoped product tokens in one browser store and resumption scope. The initial stock counts come directly from SQLite during SSR. The first island hydrates its existing DOM without making an RPC request. Change a quantity before scrolling to the second view: that delayed island mounts fresh and immediately shows the edit. Editing, saving, or reloading a product updates both views; other products retain their values. Reload from database resets the atom, whose client closure calls tRPC for the latest row. Saving checks the database revision and increments it. If another count has been saved since yours loaded, the mutation rejects the stale write; reload before trying again.
48
48
 
49
49
  Visit How it works and return. Astro's ClientRouter removes the old DOM and SPA releases the island subscriptions, while the application store and resumption scope stay alive. Returning islands render fresh from those live values, so an incoming server response cannot overwrite your edits. Refresh explicitly to fetch new server data. A full page load starts a new application from SSR again. Shared client requests receive the application scope's AbortSignal; navigation keeps that scope alive, while a full page exit aborts it. Resetting does not cancel earlier requests by itself.
50
50
 
@@ -71,29 +71,57 @@ export default defineConfig({
71
71
 
72
72
  ```
73
73
 
74
- SPA compiles the .spa.tsx components. Resumability removes inline server closures before browser import analysis, including their dynamic imports. Reylo compiles SQL imports on the server. The browser imports the tRPC router only as a type: no database module, query, or router implementation reaches executable browser code.
74
+ SPA compiles the .tsx components. Resumability removes inline server closures before browser import analysis, including their dynamic imports. Reylo compiles SQL imports on the server. The browser imports the tRPC router only as a type: no database module, query, or router implementation reaches executable browser code.
75
75
 
76
- ## One query, two entry points
76
+ ## Read and save inventory
77
77
 
78
78
  ```sql
79
- SELECT id, title, body FROM drafts WHERE id = :id;
79
+ SELECT id, sku, name, stock, revision FROM products WHERE id = :id;
80
80
 
81
81
  ```
82
82
 
83
83
  ```ts
84
- import { randomUUID } from "node:crypto"
85
84
  import { DatabaseSync } from "node:sqlite"
86
85
 
87
- import readDraftQuery from "./read-draft.sql"
86
+ import { TRPCError } from "@trpc/server"
88
87
 
89
- /** Both SSR and tRPC use this function and its inferred query result. */
90
- // oxlint-disable-next-line typescript/explicit-module-boundary-types -- Infer the response from Reylo's content-mapped SQL type; tsc verifies the full RPC contract.
91
- export function readDraft(id: number) {
92
- const database = new DatabaseSync(`drafts.sqlite`, { readOnly: true })
88
+ import readProductQuery from "./read-product.sql"
89
+
90
+ /** SSR and tRPC share the same inferred query result. */
91
+ // oxlint-disable-next-line typescript/explicit-module-boundary-types -- Infer Reylo's SQL result; the type tests verify the transport contract.
92
+ export function readProduct(id: number) {
93
+ const database = new DatabaseSync(`inventory.sqlite`, { readOnly: true })
94
+ try {
95
+ const product = readProductQuery.runSync(database, { id })
96
+ if (!product)
97
+ throw new TRPCError({
98
+ code: `NOT_FOUND`,
99
+ message: `Product ${id} does not exist`,
100
+ })
101
+ return product
102
+ } finally {
103
+ database.close()
104
+ }
105
+ }
106
+
107
+ // oxlint-disable-next-line typescript/explicit-module-boundary-types -- Preserve the query's inferred return type through the mutation.
108
+ export function saveStock(id: number, stock: number, revision: number) {
109
+ const database = new DatabaseSync(`inventory.sqlite`)
93
110
  try {
94
- const draft = readDraftQuery.runSync(database, { id })
95
- if (!draft) throw new Error(`Draft ${id} does not exist`)
96
- return { ...draft, revision: randomUUID() }
111
+ database.exec(`BEGIN IMMEDIATE`)
112
+ const result = database
113
+ .prepare(
114
+ `UPDATE products SET stock = ?, revision = revision + 1 WHERE id = ? AND revision = ?`,
115
+ )
116
+ .run(stock, id, revision)
117
+ if (!result.changes)
118
+ throw new TRPCError({
119
+ code: `CONFLICT`,
120
+ message: `Stock changed since you loaded it. Reload before saving.`,
121
+ })
122
+ const product = readProductQuery.runSync(database, { id })!
123
+ database.exec(`COMMIT`)
124
+ return product
97
125
  } finally {
98
126
  database.close()
99
127
  }
@@ -101,20 +129,29 @@ export function readDraft(id: number) {
101
129
 
102
130
  ```
103
131
 
104
- SSR calls readDraft directly. The tRPC procedure validates its input and calls the same function:
132
+ SSR calls readProduct directly. Saving uses a transaction and a conditional revision update to prevent lost stock counts. The tRPC procedure validates its input and calls the same function:
105
133
 
106
134
  ```ts
107
135
  import { initTRPC } from "@trpc/server"
108
136
  import { z } from "zod"
109
137
 
110
- import { readDraft } from "./drafts.ts"
138
+ import { readProduct, saveStock } from "./inventory.ts"
111
139
 
112
140
  const t = initTRPC.create()
113
141
  export const appRouter = t.router({
114
- drafts: t.router({
142
+ inventory: t.router({
115
143
  get: t.procedure
116
144
  .input(z.object({ id: z.number().int().positive() }))
117
- .query(({ input }) => readDraft(input.id)),
145
+ .query(({ input }) => readProduct(input.id)),
146
+ setStock: t.procedure
147
+ .input(
148
+ z.object({
149
+ id: z.number().int().positive(),
150
+ stock: z.number().int().nonnegative(),
151
+ revision: z.number().int().positive(),
152
+ }),
153
+ )
154
+ .mutation(({ input }) => saveStock(input.id, input.stock, input.revision)),
118
155
  }),
119
156
  })
120
157
  export type AppRouter = typeof appRouter
@@ -129,25 +166,33 @@ Reylo infers the row type from SQL and the database schema. The return type flow
129
166
  import { atomFamily, type Loadable } from "atom.io"
130
167
  import { resumable } from "resumability"
131
168
 
132
- import { api, type Draft } from "./api.ts"
169
+ import { api, type Product } from "./api.ts"
133
170
 
134
- export const documentIds = [1, 2] as const
171
+ export const productIds = [1, 2] as const
135
172
 
136
- export const draftAtoms = atomFamily<Loadable<Draft>, number, Error>({
137
- key: `draft`,
173
+ export const productAtoms = atomFamily<Loadable<Product>, number, Error>({
174
+ key: `product`,
138
175
  default: (id) =>
139
176
  resumable({
140
- key: [`draft`, id],
177
+ key: [`product`, id],
141
178
  server: async ({ signal }) => {
142
- const { readDraft } = await import(`./server/drafts.ts`)
179
+ const { readProduct } = await import(`./server/inventory.ts`)
143
180
  signal.throwIfAborted()
144
- return readDraft(id)
181
+ return readProduct(id)
145
182
  },
146
- client: ({ signal }) => api.drafts.get.query({ id }, { signal }),
183
+ client: ({ signal }) => api.inventory.get.query({ id }, { signal }),
147
184
  }),
148
185
  catch: [Error],
149
186
  })
150
187
 
188
+ export const saveStatusAtoms = atomFamily<
189
+ { saving: boolean; message: string },
190
+ number
191
+ >({
192
+ key: `saveStatus`,
193
+ default: { saving: false, message: `` },
194
+ })
195
+
151
196
  ```
152
197
 
153
198
  The family key supplies the query input and resumability key. Atom definitions live on the module graph. All browser views share values; each SSR request has its own store. First browser reads consume the seed. Subsequent defaults use tRPC, with errors available through useLoadable for retry.
@@ -156,73 +201,42 @@ The family key supplies the query input and resumability key. Atom definitions l
156
201
 
157
202
  ```astro
158
203
  ---
159
- import Resumption from "resumability/Resumption.astro"
160
- import Drafts from "../Drafts.spa.tsx"
204
+ import Inventory from "../Inventory.tsx"
161
205
  import Page from "../layouts/Page.astro"
162
206
  ---
163
- <Page title="Your drafts">
164
- <Resumption>{() => (
165
- <>
166
- <header class="intro">
167
- <p class="eyebrow">A server head start</p>
168
- <h1>Pick up where the server left off.</h1>
169
- <p>
170
- These notes arrive from SQLite. Edit one, or refresh it from the
171
- database. Both views share the same atom.io state.
172
- </p>
173
- </header>
174
- <section class="workspace" aria-labelledby="work-heading">
175
- <h2 id="work-heading">Your editor <small>Loads immediately</small></h2>
176
- <Drafts id="work" client:load />
177
- </section>
178
- <section class="workspace" aria-labelledby="personal-heading">
179
- <h2 id="personal-heading">
180
- Another view <small>Same shared documents · loads when visible</small>
181
- </h2><Drafts id="personal" client:visible />
182
- </section>
183
- </>
184
- )}</Resumption>
207
+ <Page title="Stock count">
208
+ <header class="intro">
209
+ <p class="eyebrow">Stockroom</p>
210
+ <h1>Count what’s on the shelf.</h1>
211
+ <p>
212
+ Update the count after checking a shelf, then save the new inventory. Both
213
+ views share your counts, including changes you haven’t saved yet.
214
+ </p>
215
+ </header>
216
+ <section class="workspace" aria-labelledby="work-heading">
217
+ <h2 id="work-heading">
218
+ Morning stock count <small>Loads immediately</small>
219
+ </h2>
220
+ <Inventory id="work" client:load />
221
+ </section>
222
+ <section class="workspace" aria-labelledby="personal-heading">
223
+ <h2 id="personal-heading">
224
+ Packing station <small>Same shared inventory · loads when visible</small>
225
+ </h2><Inventory id="personal" client:visible />
226
+ </section>
185
227
  </Page>
186
228
 
187
229
  ```
188
230
 
189
- The first workspace uses client:load; the second uses client:visible. Both render their initial data on the server. Deferred child functions keep Astro's eager framework-slot evaluation inside Resumption's async collection scope. One Resumption wrapper covers both views and collects each document once. Its sidecar precedes all the islands, so either can activate first. Keep the wrapper around page content inside the HTML body, not around the document itself.
190
-
191
- Drafts.prepareStore initializes the store already selected by SPA:
192
-
193
- ```ts
194
- import type { AstroStorePreparation } from "@atom.io/spa/astro"
195
- import { getFromStore } from "atom.io/internal"
196
- import { createResumption } from "resumability/client"
197
- import { documentIds, draftAtoms } from "./model.ts"
198
-
199
- export const prepareDrafts: AstroStorePreparation = async (
200
- store,
201
- _props,
202
- { element, application },
203
- ) => {
204
- if (element) {
205
- const scope = application.get(createResumption, () => {
206
- const created = createResumption()
207
- application.onCleanup(created.dispose)
208
- store.runDefault = (run) =>
209
- created.run(run, { resume: application.canResume })
210
- return created
211
- })
212
- scope.add(element.closest(`astro-resumption`)!)
213
- }
214
- await Promise.all(documentIds.map((id) => getFromStore(store, draftAtoms, id)))
215
- }
216
-
217
- ```
231
+ The first workspace uses client:load; the second uses client:visible. Both render their initial data on the server. Resumability owns the request collection and supplies SPA's renderer with completed values to attach to each island's HTML. A later island can hydrate first even when it reused the earlier island's cached state on the server. No wrapper or deferred child function is needed.
218
232
 
219
- On the server, Resumption's async collection supplies the scope. In the browser, application.get creates one resumption scope and registers its cleanup once. Each preparation adds the surrounding sidecar; consumed keys cannot be reseeded. Store.runDefault activates that scope whenever a default executes, including lazy family members and transactional resets. Application.canResume controls whether unread seeds may initialize client-capable defaults: after an edit or navigation, those defaults use the client path. The callback awaits the initial reads before rendering or hydration. There are no model factories, model props, or store-to-model registries.
233
+ With both integrations installed, SPA automatically waits for async state read by the island on the server. Browser defaults use resumability's host scope without changing the shared store's default evaluator. No component preparation callback or preload list is needed. Each island imports its own seed attributes, and consumed keys cannot be reseeded. After an edit or navigation, unread client-capable defaults use the client producer instead of stale initial data.
220
234
 
221
- SPA owns the request lifetime through the end of streaming and the browser application lifetime across navigation. Individual islands own only their DOM and subscriptions. Shared preparation resources survive an individual island failing or unmounting. Resumability stays independent of SPA, atom.io, Reylo, and tRPC. Treat all sidecar data as public browser-visible data.
235
+ Resumability owns its collection through the end of streaming and the browser resumption scope across navigation. SPA owns request-local stores and the browser application; individual shared islands own only their DOM and subscriptions. Shared data resources survive an individual island failing or unmounting. Private stores bind a private resumption scope so their pending work ends with the island. Resumability stays independent of SPA, atom.io, Reylo, and tRPC, and also supports plain Astro database constants without a state library. Treat all seed data as public browser-visible data.
222
236
 
223
237
  ## Validation
224
238
 
225
- The browser check runs against both the production Node server and the Astro dev server. It inspects real SSR content, verifies that initial hydration preserves textarea nodes and IDs while a delayed island replaces stale DOM, and asserts zero RPC requests during hydration. In production, it verifies byte-identical cached HTML and sidecars after SQLite changes, waits for the real 60-second TTL to expire, and checks that a new snapshot is rendered and cached. Development checks verify fresh SSR instead. Repeated resets fetch changed rows through tRPC with no-store headers, including after resuming an older cached snapshot; resets do not rewrite the page cache. It also checks shared document state, client:load and client:visible scheduling, fresh mounts and preserved edits after navigation, and removal of server modules from browser scripts. Browser exceptions fail the check. Type tests reject invalid RPC input and verify the inferred response fields.
239
+ The browser check runs against both the production Node server and the Astro dev server. It inspects real SSR content, verifies that initial hydration preserves quantity inputs and IDs while a delayed island replaces stale DOM, and asserts zero RPC requests during hydration. A full reload activates the later server island first and verifies that both hydrate their original nodes using their own seeds. In production, it verifies byte-identical cached HTML and seed attributes after SQLite changes, waits for the real 60-second TTL to expire, and checks that a new snapshot is rendered and cached. Development checks verify fresh SSR instead. Repeated resets fetch changed rows through tRPC with no-store headers, including after resuming an older cached snapshot; resets do not rewrite the page cache. It also checks shared product state, client:load and client:visible scheduling, fresh mounts and preserved edits after navigation, successful saves, rejection of competing stock counts, and removal of server modules from browser scripts. Browser exceptions fail the check. Type tests reject invalid RPC input and verify the inferred response fields.
226
240
 
227
241
  ## License
228
242
 
package/README.mdx CHANGED
@@ -2,15 +2,14 @@ import Workspace from "./exhibits/workspace.sh" with { type: "code" };
2
2
  import Run from "./exhibits/run.sh" with { type: "code" };
3
3
  import Config from "./astro.config.ts" with { type: "code" };
4
4
  import Islands from "./src/pages/index.astro" with { type: "code" };
5
- import Model from "./src/model.ts" with { type: "code" };
6
- import Prepare from "./src/prepare-drafts.ts" with { type: "code" };
7
- import Query from "./src/server/read-draft.sql" with { type: "code" };
8
- import ReadDraft from "./src/server/drafts.ts" with { type: "code" };
5
+ import State from "./src/state.ts" with { type: "code" };
6
+ import Query from "./src/server/read-product.sql" with { type: "code" };
7
+ import ReadProduct from "./src/server/inventory.ts" with { type: "code" };
9
8
  import Router from "./src/server/router.ts" with { type: "code" };
10
9
 
11
10
  # SPA + Astro SSR
12
11
 
13
- A starter with module-scoped atom definitions, server-rendered Astro islands, and typed database refreshes. It uses atom.io, @atom.io/spa, resumability/astro, Reylo over node:sqlite, and tRPC. Requires Node 24.12 or newer and TypeScript 7.1's content mappers (currently beta).
12
+ A starter with module-scoped atom definitions, server-rendered Astro islands, and an inventory workflow with editable stock counts, persistent saves, and fresh database reads. It uses atom.io, @atom.io/spa, resumability/astro, Reylo over node:sqlite, and tRPC. Requires Node 24.12 or newer and TypeScript 7.1's content mappers (currently beta).
14
13
 
15
14
  ## Run
16
15
 
@@ -20,25 +19,25 @@ Inside the atom.io workspace:
20
19
 
21
20
  <Workspace />
22
21
 
23
- The workspace uses local unpublished packages; a packed release replaces workspace dependency ranges with published versions. Development, build, and typecheck commands initialize drafts.sqlite from schema.sql and insert missing example rows without overwriting edits. Reylo checks queries against that schema using .reylo.yaml. The generated database is ignored by Git and excluded from the package.
22
+ The workspace uses local unpublished packages; a packed release replaces workspace dependency ranges with published versions. Development, build, and typecheck commands initialize inventory.sqlite from schema.sql and insert missing example rows without overwriting edits. Reylo checks queries against that schema using .reylo.yaml. The generated database is ignored by Git and excluded from the package.
24
23
 
25
- This is an on-demand Node server application. The Astro Node adapter serves both pages and the tRPC endpoint. Start production from the template directory so it can find drafts.sqlite; supply persistent storage for that file when deploying. Initialize the database before starting a new deployment.
24
+ This is an on-demand Node server application. The Astro Node adapter serves both pages and the tRPC endpoint. Start production from the template directory so it can find inventory.sqlite; supply persistent storage for that file when deploying. Initialize the database before starting a new deployment.
26
25
 
27
26
  ## Rendering and caching
28
27
 
29
- The starter uses on-demand SSR with Astro’s built-in memoryCache provider. The public drafts page has a 60-second TTL and no stale-while-revalidate window. A cache miss reads SQLite in a request-owned store and caches the complete HTML response, including its resumption sidecar. Hits reuse that snapshot; the first request after expiry renders a new one. There are no prerendered pages. The tRPC endpoint is outside the cached route rule and returns Cache-Control: no-store, so resets always read the database.
28
+ The starter uses on-demand SSR with Astro’s built-in memoryCache provider. The public stock-counting page has a 60-second TTL and no stale-while-revalidate window. A cache miss reads SQLite in a request-owned store and caches the complete HTML response, including its resumption seeds. Hits reuse that snapshot; the first request after expiry renders a new one. There are no prerendered pages. The tRPC endpoint is outside the cached route rule and returns Cache-Control: no-store, so resets always read the database.
30
29
 
31
30
  The cache belongs to one server process: it is lost on restart and is not shared across replicas. This is a small, self-contained deployment default; choose an infrastructure-backed provider when multiple instances need shared caching or invalidation. Astro disables caching in development. Build and preview the template to exercise the production cache.
32
31
 
33
- This template’s example data is public. When adapting it, cache the complete HTML response together with its resumption sidecar. The markup and initial values must come from the same render. Choose a freshness window and invalidation policy that match the data; do not cache a live atom.io store or reuse it across requests. Cache only responses whose data can be shared by everyone using the cache entry. Personalized snapshots need private caching or a correctly scoped cache key.
32
+ This template’s example data is public. When adapting it, cache the complete HTML response together with its resumption seeds. The markup and initial values must come from the same render. Choose a freshness window and invalidation policy that match the data; do not cache a live atom.io store or reuse it across requests. Cache only responses whose data can be shared by everyone using the cache entry. Personalized snapshots need private caching or a correctly scoped cache key.
34
33
 
35
- The initial browser load consumes that snapshot without immediately refetching it. Expiring or invalidating the server cache affects future page loads, not an already running browser store. Keep the explicit reset/tRPC path fresh so Refresh from database can fetch the current row. ClientRouter navigation continues to preserve live browser state rather than replacing edits with another server snapshot.
34
+ The initial browser load consumes that snapshot without immediately refetching it. Expiring or invalidating the server cache affects future page loads, not an already running browser store. Keep the explicit reset/tRPC path fresh so Reload from database can fetch the current row. ClientRouter navigation continues to preserve live browser state rather than replacing edits with another server snapshot.
36
35
 
37
- SSG is also compatible with resumption: the sidecar is produced during the build and remains that snapshot until the next deployment. Use it for routes whose freshness can follow deployments, while retaining on-demand API routes for resets. Astro's [on-demand rendering](https://docs.astro.build/en/guides/on-demand-rendering/) and [route caching](https://docs.astro.build/en/guides/caching/) documentation describe the route-level controls and cache providers.
36
+ SSG is also compatible with resumption: the seed data is produced during the build and remains that snapshot until the next deployment. Use it for routes whose freshness can follow deployments, while retaining on-demand API routes for resets. Astro's [on-demand rendering](https://docs.astro.build/en/guides/on-demand-rendering/) and [route caching](https://docs.astro.build/en/guides/caching/) documentation describe the route-level controls and cache providers.
38
37
 
39
38
  ## Try it
40
39
 
41
- Both views use the same two module-scoped document tokens in one browser store and resumption scope. The initial notes come directly from SQLite during SSR. The first island hydrates its existing DOM without making an RPC request. Type into a draft before scrolling to the second view: that delayed island mounts fresh and immediately shows the edit. Typing or refreshing a document updates both views; other documents retain their values. Refresh from database resets the atom, whose client closure calls tRPC for the latest row. The returned revision identifies that read.
40
+ Both views use the same two module-scoped product tokens in one browser store and resumption scope. The initial stock counts come directly from SQLite during SSR. The first island hydrates its existing DOM without making an RPC request. Change a quantity before scrolling to the second view: that delayed island mounts fresh and immediately shows the edit. Editing, saving, or reloading a product updates both views; other products retain their values. Reload from database resets the atom, whose client closure calls tRPC for the latest row. Saving checks the database revision and increments it. If another count has been saved since yours loaded, the mutation rejects the stale write; reload before trying again.
42
41
 
43
42
  Visit How it works and return. Astro's ClientRouter removes the old DOM and SPA releases the island subscriptions, while the application store and resumption scope stay alive. Returning islands render fresh from those live values, so an incoming server response cannot overwrite your edits. Refresh explicitly to fetch new server data. A full page load starts a new application from SSR again. Shared client requests receive the application scope's AbortSignal; navigation keeps that scope alive, while a full page exit aborts it. Resetting does not cancel earlier requests by itself.
44
43
 
@@ -46,15 +45,15 @@ Visit How it works and return. Astro's ClientRouter removes the old DOM and SPA
46
45
 
47
46
  <Config />
48
47
 
49
- SPA compiles the .spa.tsx components. Resumability removes inline server closures before browser import analysis, including their dynamic imports. Reylo compiles SQL imports on the server. The browser imports the tRPC router only as a type: no database module, query, or router implementation reaches executable browser code.
48
+ SPA compiles the .tsx components. Resumability removes inline server closures before browser import analysis, including their dynamic imports. Reylo compiles SQL imports on the server. The browser imports the tRPC router only as a type: no database module, query, or router implementation reaches executable browser code.
50
49
 
51
- ## One query, two entry points
50
+ ## Read and save inventory
52
51
 
53
52
  <Query />
54
53
 
55
- <ReadDraft />
54
+ <ReadProduct />
56
55
 
57
- SSR calls readDraft directly. The tRPC procedure validates its input and calls the same function:
56
+ SSR calls readProduct directly. Saving uses a transaction and a conditional revision update to prevent lost stock counts. The tRPC procedure validates its input and calls the same function:
58
57
 
59
58
  <Router />
60
59
 
@@ -62,7 +61,7 @@ Reylo infers the row type from SQL and the database schema. The return type flow
62
61
 
63
62
  ## Module-scoped atom defaults
64
63
 
65
- <Model />
64
+ <State />
66
65
 
67
66
  The family key supplies the query input and resumability key. Atom definitions live on the module graph. All browser views share values; each SSR request has its own store. First browser reads consume the seed. Subsequent defaults use tRPC, with errors available through useLoadable for retry.
68
67
 
@@ -70,19 +69,15 @@ The family key supplies the query input and resumability key. Atom definitions l
70
69
 
71
70
  <Islands />
72
71
 
73
- The first workspace uses client:load; the second uses client:visible. Both render their initial data on the server. Deferred child functions keep Astro's eager framework-slot evaluation inside Resumption's async collection scope. One Resumption wrapper covers both views and collects each document once. Its sidecar precedes all the islands, so either can activate first. Keep the wrapper around page content inside the HTML body, not around the document itself.
72
+ The first workspace uses client:load; the second uses client:visible. Both render their initial data on the server. Resumability owns the request collection and supplies SPA's renderer with completed values to attach to each island's HTML. A later island can hydrate first even when it reused the earlier island's cached state on the server. No wrapper or deferred child function is needed.
74
73
 
75
- Drafts.prepareStore initializes the store already selected by SPA:
74
+ With both integrations installed, SPA automatically waits for async state read by the island on the server. Browser defaults use resumability's host scope without changing the shared store's default evaluator. No component preparation callback or preload list is needed. Each island imports its own seed attributes, and consumed keys cannot be reseeded. After an edit or navigation, unread client-capable defaults use the client producer instead of stale initial data.
76
75
 
77
- <Prepare />
78
-
79
- On the server, Resumption's async collection supplies the scope. In the browser, application.get creates one resumption scope and registers its cleanup once. Each preparation adds the surrounding sidecar; consumed keys cannot be reseeded. Store.runDefault activates that scope whenever a default executes, including lazy family members and transactional resets. Application.canResume controls whether unread seeds may initialize client-capable defaults: after an edit or navigation, those defaults use the client path. The callback awaits the initial reads before rendering or hydration. There are no model factories, model props, or store-to-model registries.
80
-
81
- SPA owns the request lifetime through the end of streaming and the browser application lifetime across navigation. Individual islands own only their DOM and subscriptions. Shared preparation resources survive an individual island failing or unmounting. Resumability stays independent of SPA, atom.io, Reylo, and tRPC. Treat all sidecar data as public browser-visible data.
76
+ Resumability owns its collection through the end of streaming and the browser resumption scope across navigation. SPA owns request-local stores and the browser application; individual shared islands own only their DOM and subscriptions. Shared data resources survive an individual island failing or unmounting. Private stores bind a private resumption scope so their pending work ends with the island. Resumability stays independent of SPA, atom.io, Reylo, and tRPC, and also supports plain Astro database constants without a state library. Treat all seed data as public browser-visible data.
82
77
 
83
78
  ## Validation
84
79
 
85
- The browser check runs against both the production Node server and the Astro dev server. It inspects real SSR content, verifies that initial hydration preserves textarea nodes and IDs while a delayed island replaces stale DOM, and asserts zero RPC requests during hydration. In production, it verifies byte-identical cached HTML and sidecars after SQLite changes, waits for the real 60-second TTL to expire, and checks that a new snapshot is rendered and cached. Development checks verify fresh SSR instead. Repeated resets fetch changed rows through tRPC with no-store headers, including after resuming an older cached snapshot; resets do not rewrite the page cache. It also checks shared document state, client:load and client:visible scheduling, fresh mounts and preserved edits after navigation, and removal of server modules from browser scripts. Browser exceptions fail the check. Type tests reject invalid RPC input and verify the inferred response fields.
80
+ The browser check runs against both the production Node server and the Astro dev server. It inspects real SSR content, verifies that initial hydration preserves quantity inputs and IDs while a delayed island replaces stale DOM, and asserts zero RPC requests during hydration. A full reload activates the later server island first and verifies that both hydrate their original nodes using their own seeds. In production, it verifies byte-identical cached HTML and seed attributes after SQLite changes, waits for the real 60-second TTL to expire, and checks that a new snapshot is rendered and cached. Development checks verify fresh SSR instead. Repeated resets fetch changed rows through tRPC with no-store headers, including after resuming an older cached snapshot; resets do not rewrite the page cache. It also checks shared product state, client:load and client:visible scheduling, fresh mounts and preserved edits after navigation, successful saves, rejection of competing stock counts, and removal of server modules from browser scripts. Browser exceptions fail the check. Type tests reject invalid RPC input and verify the inferred response fields.
86
81
 
87
82
  ## License
88
83
 
package/_gitignore CHANGED
@@ -3,4 +3,4 @@ dist/
3
3
  .astro/
4
4
  .env
5
5
  test-results/
6
- drafts.sqlite*
6
+ *.sqlite*
@@ -0,0 +1,8 @@
1
+ import type { SpaElement } from "@atom.io/spa"
2
+
3
+ import Inventory from "../src/Inventory.tsx"
4
+
5
+ export default function PrivateInventory(props: { id: string }): SpaElement {
6
+ return <Inventory id={props.id} />
7
+ }
8
+ PrivateInventory.isolate = true
@@ -0,0 +1,5 @@
1
+ ---
2
+ import Inventory from "../src/Inventory.tsx"
3
+ ---
4
+
5
+ <Inventory id="stock-count" client:load />
@@ -0,0 +1,5 @@
1
+ ---
2
+ import PrivateInventory from "./PrivateInventory.tsx"
3
+ ---
4
+
5
+ <PrivateInventory id="station-count" client:load />
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atom.io/template-spa-astro-ssr",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "Astro, SPA, and resumable atom defaults with SQLite server data.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,13 +22,13 @@
22
22
  ".reylo.yaml"
23
23
  ],
24
24
  "dependencies": {
25
- "@astrojs/node": "11.1.9",
26
- "@atom.io/spa": "0.0.3",
27
- "@trpc/client": "11.23.0",
28
- "@trpc/server": "11.24.0",
29
- "astro": "7.4.5",
30
- "atom.io": "0.54.4",
31
- "resumability": "0.0.1",
25
+ "@astrojs/node": "11.1.11",
26
+ "@atom.io/spa": "0.0.5",
27
+ "@trpc/client": "11.25.0",
28
+ "@trpc/server": "11.25.0",
29
+ "astro": "7.4.7",
30
+ "atom.io": "0.54.6",
31
+ "resumability": "0.0.2",
32
32
  "reylo": "0.7.0",
33
33
  "zod": "4.6.7"
34
34
  },
@@ -36,11 +36,11 @@
36
36
  "@reylosql/sqlite": "0.6.0",
37
37
  "@types/node": "26.6.6",
38
38
  "galley.md": "0.3.1",
39
- "oxlint": "1.91.0",
40
- "oxlint-tsgolint": "7.0.2005",
41
- "playwright": "1.64.1",
42
- "typescript": "7.1.0-dev.20261103.1",
43
- "vite": "8.3.5"
39
+ "oxlint": "1.92.0",
40
+ "oxlint-tsgolint": "7.0.2006",
41
+ "playwright": "1.65.0",
42
+ "typescript": "7.1.0-dev.20261106.1",
43
+ "vite": "8.3.6"
44
44
  },
45
45
  "engines": {
46
46
  "node": ">=24.12.0"
package/schema.sql CHANGED
@@ -1,5 +1,7 @@
1
- CREATE TABLE IF NOT EXISTS drafts (
1
+ CREATE TABLE IF NOT EXISTS products (
2
2
  id INTEGER PRIMARY KEY,
3
- title TEXT NOT NULL,
4
- body TEXT NOT NULL
3
+ sku TEXT NOT NULL UNIQUE,
4
+ name TEXT NOT NULL,
5
+ stock INTEGER NOT NULL CHECK (stock >= 0),
6
+ revision INTEGER NOT NULL DEFAULT 1
5
7
  ) STRICT;
package/scripts/seed.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  import { readFileSync } from "node:fs"
2
2
  import { DatabaseSync } from "node:sqlite"
3
3
 
4
- const database = new DatabaseSync(`drafts.sqlite`)
4
+ const database = new DatabaseSync(`inventory.sqlite`)
5
5
  try {
6
6
  database.exec(readFileSync(new URL(`../schema.sql`, import.meta.url), `utf8`))
7
7
  const insert = database.prepare(
8
- `INSERT OR IGNORE INTO drafts (id, title, body) VALUES (?, ?, ?)`,
8
+ `INSERT OR IGNORE INTO products (id, sku, name, stock) VALUES (?, ?, ?, ?)`,
9
9
  )
10
- for (const id of [1, 2])
11
- insert.run(id, `Draft ${id}`, `A note from SQLite for document ${id}.`)
10
+ insert.run(1, `COF-250`, `House blend · 250 g`, 24)
11
+ insert.run(2, `TEA-100`, `Breakfast tea · 100 g`, 18)
12
12
  } finally {
13
13
  database.close()
14
14
  }