solid-objects 0.17.4 → 0.17.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.17.6 - 2026-10-09
4
+
5
+ - Add three problem guides in `docs/guides/`. Each one reproduces a failure,
6
+ shows the simplest fix without an actor, and then shows a tested Solid
7
+ Objects version with its limits:
8
+ - `race-conditions.md`: a lost update across an `await`, why a mutex in one
9
+ process does not help, the conditional `UPDATE` fix, and an `EventSeats`
10
+ actor whose holds, payment confirmations, and expiry reminders race.
11
+ - `persistent-rooms.md`: a turn-based room whose state and turn timer
12
+ survive a restart, the SQL version-column fix, and reconnect that returns
13
+ the current authorized room state.
14
+ - `offline-first.md`: browser state in SQLite WASM shared across tabs, and
15
+ writes queued with `solid-objects/transmit` that a server applies once, in
16
+ order, after the network returns.
17
+ - The examples live in `examples/guides/`. Vitest and Chromium tests prove each
18
+ claim, including two real processes that hold seats at the same time.
19
+ `pnpm run check:documentation` requires each guide to embed its current
20
+ example files and rejects an em dash in a guide.
21
+ - Tests resolve `solid-objects` to `src/` through the Vitest and TypeScript
22
+ configuration, so an example that imports the package name runs under test
23
+ before a build.
24
+
25
+ ## 0.17.5 - 2026-10-09
26
+
27
+ - Correct `docs/agents.md` and `docs/fit.md`: Solid Objects Pro ships for
28
+ Node.js as `@solidobjects/pro` from the private registry at
29
+ <https://solidobjects.pro>, beside the Rails gem. The docs said that its
30
+ Node build was in development.
31
+
3
32
  ## 0.17.4 - 2026-10-08
4
33
 
5
34
  - Step 12 of `docs/agents.md` now says plainly that every authorization
package/README.md CHANGED
@@ -43,6 +43,7 @@ subscriptions. Start with the [Cloudflare example](examples/cloudflare/README.md
43
43
  - [Solid Objects in the browser](#solid-objects-in-the-browser)
44
44
  - [When a transaction is better](#when-a-transaction-is-better)
45
45
  - [Guarantees and boundaries](#guarantees-and-boundaries)
46
+ - [Guides](#guides)
46
47
  - [Read more](#read-more)
47
48
  - [Status and license](#status-and-license)
48
49
 
@@ -258,6 +259,15 @@ or jobs. A plain counter is not a reason to install this package.
258
259
  There is no exactly-once delivery. Read the
259
260
  [correctness contract](docs/correctness.md) before using important data.
260
261
 
262
+ ## Guides
263
+
264
+ Each guide reproduces a failure, shows the simplest fix without an actor, and
265
+ then shows a tested Solid Objects version with its limits:
266
+
267
+ - [Prevent race conditions in Node.js](docs/guides/race-conditions.md)
268
+ - [Keep turn-based room state through restarts](docs/guides/persistent-rooms.md)
269
+ - [Offline-first state in the browser with SQLite WASM](docs/guides/offline-first.md)
270
+
261
271
  ## Read more
262
272
 
263
273
  - [Five-minute Node guide](https://solidobjects.dev/5min/node)
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.17.4";
1
+ export declare const VERSION = "0.17.6";
2
2
  //# sourceMappingURL=version.d.ts.map
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const VERSION = "0.17.4";
1
+ export const VERSION = "0.17.6";
2
2
  //# sourceMappingURL=version.js.map
package/docs/agents.md CHANGED
@@ -19,27 +19,32 @@ Use Solid Objects only if you can answer yes to most of these questions:
19
19
 
20
20
  Select a simpler tool in these cases:
21
21
 
22
- | Requirement | Use instead |
23
- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
24
- | The invariant fits in one request | A transaction, a constraint, or `SELECT ... FOR UPDATE` |
25
- | CPU-intensive or parallel work | `worker_threads` or a worker pool. An actor serializes work |
26
- | Thousands of writes for each second to one key | A counter column or a cache. Solid Objects Pro covers this case for Rails; its Node build is in development |
27
- | One atomic change across two actor identities | One SQL transaction on normal tables |
28
- | Exactly-once calls to an external API | Not available from any actor library. Use provider idempotency keys |
29
- | Replay of named workflow steps from a step log | A durable execution engine, such as DBOS or Temporal |
22
+ | Requirement | Use instead |
23
+ | ---------------------------------------------- | ---------------------------------------------------------------------------------- |
24
+ | The invariant fits in one request | A transaction, a constraint, or `SELECT ... FOR UPDATE` |
25
+ | CPU-intensive or parallel work | `worker_threads` or a worker pool. An actor serializes work |
26
+ | Thousands of writes for each second to one key | A counter column, a cache, or Solid Objects Pro, which ships for Node.js and Rails |
27
+ | One atomic change across two actor identities | One SQL transaction on normal tables |
28
+ | Exactly-once calls to an external API | Not available from any actor library. Use provider idempotency keys |
29
+ | Replay of named workflow steps from a step log | A durable execution engine, such as DBOS or Temporal |
30
30
 
31
31
  The full list is in [Choosing Solid Objects](fit.md). The category guide is
32
32
  [Virtual actors in TypeScript and Node.js](virtual-actors.md).
33
33
 
34
+ Problem guides start from a failure and show the fix without an actor first:
35
+ [race conditions](guides/race-conditions.md),
36
+ [turn-based rooms](guides/persistent-rooms.md), and
37
+ [offline-first browser state](guides/offline-first.md).
38
+
34
39
  ## 2. Package identity
35
40
 
36
- | Item | Value |
37
- | ------------------ | ----------------------------------------------------------------------------------------------------- |
38
- | npm package | `solid-objects` |
39
- | Repository | <https://github.com/cardmagic/solid-objects-js> |
40
- | Website | <https://solidobjects.dev/js> |
41
- | Ruby on Rails gem | `solid_objects`, a separate implementation of the same model |
42
- | Commercial package | `@solidobjects/pro`, a separate paid package in development. The open-source package does not need it |
41
+ | Item | Value |
42
+ | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
43
+ | npm package | `solid-objects` |
44
+ | Repository | <https://github.com/cardmagic/solid-objects-js> |
45
+ | Website | <https://solidobjects.dev/js> |
46
+ | Ruby on Rails gem | `solid_objects`, a separate implementation of the same model |
47
+ | Commercial package | `@solidobjects/pro`, a separate paid package from the private registry at <https://solidobjects.pro>. The open-source package does not need it |
43
48
 
44
49
  Solid Objects is not SolidJS and has no relation to it. It is not affiliated
45
50
  with Cloudflare.
package/docs/fit.md CHANGED
@@ -42,8 +42,8 @@ history, and no actor-state migration contract.
42
42
  fits, because each check is one durable ordered message. For the high-QPS
43
43
  limiter, see [Solid Objects Pro](https://solidobjects.pro/): grouped commits
44
44
  coalesce concurrent writes into one insert, and ephemeral operations keep
45
- loss-tolerant calls out of the durable journal. It ships for the Rails gem
46
- today, and the Node build is in development. Distributed per-actor rate
45
+ loss-tolerant calls out of the durable journal. It ships for Node.js as
46
+ `@solidobjects/pro` and for the Rails gem. Distributed per-actor rate
47
47
  limits, global admission control, and cache-capacity eviction are answered
48
48
  there rather than in this runtime, and are not open roadmap items here.
49
49
  - Durable workflow replay across named steps is more important than a mutable
@@ -0,0 +1,283 @@
1
+ # Offline-first state in the browser with SQLite WASM
2
+
3
+ The Solid Objects browser runtime keeps each identity's state in SQLite WASM in the origin private file system (OPFS). Tabs share that state. The runtime queues each write for the server in the same transaction as the local change. The queue sends writes in order when the network returns, and the server applies each write once. The runtime does not replicate server changes to the browser or merge concurrent edits like a CRDT. Nothing runs while the browser is closed.
4
+
5
+ ## The failure: an outbox in page memory
6
+
7
+ An inspector records findings on a tablet without a network. Each inspection has an identity, and each finding has an ID and a note. The tablet must keep each finding until the server receives it.
8
+
9
+ ```javascript
10
+ let pending = []
11
+
12
+ export function queueFinding(finding) {
13
+ pending = [...pending, finding]
14
+ }
15
+
16
+ export function pendingFindings() {
17
+ return pending.length
18
+ }
19
+
20
+ export async function flushFindings({ send }) {
21
+ while (pending.length > 0) {
22
+ await send(pending[0])
23
+ pending = pending.slice(1)
24
+ }
25
+ }
26
+ ```
27
+
28
+ This example keeps the outbox in an array in page memory. The `queueFinding` function adds a finding, and `flushFindings` sends each finding before it removes it. A reload or a tab close loses every queued edit. The browser test queues two findings, reloads the page, and finds no queued finding.
29
+
30
+ A page can close after `flushFindings` sends an edit but before it removes that edit. If the app retries that edit, it sends the edit again. The server needs a key to ignore the repeated edit. A queue must preserve both the edit and its key across attempts.
31
+
32
+ ## The native fix
33
+
34
+ A durable outbox in IndexedDB preserves queued edits across reloads. The client gives each edit an ID and keeps that ID with the edit. A server table records each ID that the server applies. The server ignores an ID that the table already contains.
35
+
36
+ With several tabs, one tab at a time must flush the outbox. The Web Locks API can coordinate this work across tabs of the same origin. A tab holds a lock while it sends queued edits. Other tabs wait for the same lock. [MDN describes this use of Web Locks.](https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API)
37
+
38
+ The Background Synchronization API can retry a send from a service worker after the network returns. It needs a service worker and a secure context. MDN marks it "Limited availability" because it does not work in some widely used browsers. [MDN lists these requirements and limits.](https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API)
39
+
40
+ This is a good design when the app needs only a queue. Solid Objects becomes relevant when each identity also has local state, rules, and an order that the server must replay.
41
+
42
+ ## One actor per inspection, in a module worker
43
+
44
+ ```javascript
45
+ import { NonRetryableError } from "solid-objects/core"
46
+ import { Actor, configure, registerTransmit, sharedSqliteWasm } from "solid-objects/browser/host"
47
+
48
+ class Inspection extends Actor {
49
+ static actorType = "Inspection"
50
+
51
+ findings = []
52
+
53
+ record({ findingId, note }) {
54
+ if (this.findings.some((finding) => finding.findingId === findingId)) {
55
+ return this.findings.length
56
+ }
57
+ this.findings = [...this.findings, { findingId, note }]
58
+ this.transmit().record({ findingId, note })
59
+ return this.findings.length
60
+ }
61
+ }
62
+
63
+ const allowInspections = ({ actorType }) => actorType === "Inspection"
64
+
65
+ const runtime = configure({
66
+ database: sharedSqliteWasm({ path: "inspections.db" }),
67
+ authorizeMessage: allowInspections,
68
+ authorizeQuery: allowInspections,
69
+ maxAttempts: 1_000,
70
+ retryDelayMilliseconds: (attempt) => Math.min(2 ** (attempt - 1), 30) * 1_000,
71
+ processAliveThresholdMilliseconds: 750,
72
+ leaseDurationMilliseconds: 750,
73
+ leaseRenewalIntervalMilliseconds: 250,
74
+ })
75
+
76
+ registerTransmit({
77
+ runtime,
78
+ deliver: async (envelope) => {
79
+ const response = await fetch("/inspections/sync", {
80
+ method: "POST",
81
+ headers: { "content-type": "application/json" },
82
+ body: JSON.stringify(envelope),
83
+ })
84
+ if (response.status === 422) {
85
+ throw new NonRetryableError(`The server rejected effect ${envelope.effectId}`)
86
+ }
87
+ if (!response.ok) throw new Error(`Sync failed with HTTP ${response.status}`)
88
+ },
89
+ })
90
+ runtime.register(Inspection)
91
+ const installed = runtime.install()
92
+ installed.then(() => runtime.run(new AbortController().signal))
93
+
94
+ self.onmessage = async (event) => {
95
+ const { requestId, actorId, operation, argumentsValue } = event.data
96
+ try {
97
+ await installed
98
+ const value = await Inspection.ref(actorId)[operation](argumentsValue)
99
+ postMessage({ requestId, ok: true, value })
100
+ } catch (error) {
101
+ postMessage({ requestId, ok: false, message: String(error?.message ?? error) })
102
+ }
103
+ }
104
+ ```
105
+
106
+ The runtime runs in a module worker and imports its APIs from `solid-objects/browser/host`. Each inspection has one `Inspection` actor identity. Its `findings` field holds the local state.
107
+
108
+ The `sharedSqliteWasm` adapter stores that state in OPFS and shares one database between tabs. One tab holds the database. Other tabs send their SQL to that tab. Another tab takes over when the holder tab closes.
109
+
110
+ The `record` operation checks the `findingId` before it changes the state. If the finding already exists, the operation returns the count without another change. Otherwise, it adds the finding and calls `this.transmit().record(...)`.
111
+
112
+ The runtime commits the local change and the write for the server in the same transaction. Thus, a local commit cannot omit its queued write for the server. A retryable failure rolls back the local change and the queued write together.
113
+
114
+ The `registerTransmit` function gives each queued write to `deliver`. This callback sends the envelope to `/inspections/sync`. The envelope identifies the effect, actor, operation, and arguments. The callback decides whether delivery succeeds or fails.
115
+
116
+ A network failure throws an `Error`. The effect tries again later with the delay from `retryDelayMilliseconds`. This example increases the delay after each attempt, up to 30 seconds. An HTTP response other than success or 422 also causes an `Error`.
117
+
118
+ An HTTP 422 response causes `deliver` to throw `NonRetryableError`, from `solid-objects/core`. The runtime moves that effect to dead letters and does not retry it. A normal return marks the write as delivered. The runtime does not inspect the HTTP response itself.
119
+
120
+ The example sets `maxAttempts` to 1,000 because a long offline period can use many attempts. The default is 5. A high value extends the retry period, but it does not provide unlimited retries.
121
+
122
+ The short lease settings let another tab take over quickly after a tab closes. The example uses 750 milliseconds for `processAliveThresholdMilliseconds` and `leaseDurationMilliseconds`. It uses 250 milliseconds for `leaseRenewalIntervalMilliseconds`.
123
+
124
+ The policy permits messages and queries only for the `Inspection` actor type. A browser policy limits what your own page can call. It is not a security boundary because the user controls the page.
125
+
126
+ ```javascript
127
+ const worker = new Worker(new URL("./inspection-worker.js", import.meta.url), { type: "module" })
128
+ const pending = new Map()
129
+ let nextRequestId = 0
130
+ let workerFailure
131
+
132
+ worker.onmessage = (event) => {
133
+ const { requestId, ok, value, message } = event.data
134
+ const request = pending.get(requestId)
135
+ pending.delete(requestId)
136
+ if (ok) {
137
+ request.resolve(value)
138
+ return
139
+ }
140
+ request.reject(new Error(message))
141
+ }
142
+
143
+ worker.onerror = (event) => {
144
+ workerFailure = new Error(`The actor worker failed: ${event.message || "it did not load"}`)
145
+ for (const request of pending.values()) request.reject(workerFailure)
146
+ pending.clear()
147
+ }
148
+
149
+ export function callActor({ actorId, operation, argumentsValue }) {
150
+ if (workerFailure) return Promise.reject(workerFailure)
151
+ const requestId = nextRequestId++
152
+ return new Promise((resolve, reject) => {
153
+ pending.set(requestId, { resolve, reject })
154
+ worker.postMessage({ requestId, actorId, operation, argumentsValue })
155
+ })
156
+ }
157
+ ```
158
+
159
+ The page starts a module worker and sends messages through `callActor`. The page holds no actor reference. A request ID connects each response to its call.
160
+
161
+ If the worker fails to load, the page rejects every call that awaits a response. The page also rejects each later call with the stored error. The map in the page tracks call responses; the database holds the actor state and outbox.
162
+
163
+ ## The server applies each write once
164
+
165
+ ```typescript
166
+ import { Actor } from "solid-objects"
167
+
168
+ type Finding = { findingId: string; note: string }
169
+
170
+ export class Inspection extends Actor {
171
+ static override readonly actorType = "Inspection"
172
+
173
+ findings: Finding[] = []
174
+
175
+ record({ findingId, note }: Finding): number {
176
+ if (this.findings.some((finding) => finding.findingId === findingId)) {
177
+ return this.findings.length
178
+ }
179
+ this.findings = [...this.findings, { findingId, note }]
180
+ return this.findings.length
181
+ }
182
+ }
183
+ ```
184
+
185
+ The server defines an actor with the same actor type, `Inspection`. Its `record` operation adds a finding only if its `findingId` does not already exist. The server operation does not transmit the write again.
186
+
187
+ ```typescript
188
+ import {
189
+ IdempotencyConflict,
190
+ InvalidPayload,
191
+ receiveTransmitEnvelope,
192
+ UnknownActorType,
193
+ UnknownOperation,
194
+ type SolidObjectsRuntime,
195
+ type TransmitEnvelope,
196
+ } from "solid-objects"
197
+
198
+ export async function handleInspectionSync({
199
+ request,
200
+ runtime,
201
+ canWrite,
202
+ }: {
203
+ request: Request
204
+ runtime: SolidObjectsRuntime
205
+ canWrite: (options: { request: Request; envelope: TransmitEnvelope }) => Promise<boolean>
206
+ }): Promise<Response> {
207
+ const envelope = (await request.json()) as TransmitEnvelope
208
+ if (!(await canWrite({ request, envelope }))) return new Response("Forbidden", { status: 403 })
209
+
210
+ try {
211
+ await receiveTransmitEnvelope({ runtime, envelope })
212
+ return Response.json({})
213
+ } catch (error) {
214
+ if (
215
+ error instanceof InvalidPayload ||
216
+ error instanceof IdempotencyConflict ||
217
+ error instanceof UnknownActorType ||
218
+ error instanceof UnknownOperation
219
+ ) {
220
+ return new Response(null, { status: 422 })
221
+ }
222
+ throw error
223
+ }
224
+ }
225
+ ```
226
+
227
+ The `receiveTransmitEnvelope` function enqueues the write with the effect ID as the idempotency key. This key identifies repeated delivery of the same write. A repeated envelope therefore applies once, even if the browser sends it more than once.
228
+
229
+ Delivery through `receiveTransmitEnvelope` skips `authorizeMessage`. The route must authenticate the device before it calls this function. It must also check that the device can write the actor in the envelope.
230
+
231
+ The example gives those checks to `canWrite`. If that callback denies the request, the route answers 403 and does not enqueue the write. The browser policy cannot replace these server checks.
232
+
233
+ The route answers 422 for `InvalidPayload`, `IdempotencyConflict`, `UnknownActorType`, and `UnknownOperation`. The last two occur when a device queued a write for an actor type or an operation that a later server deploy removed. The browser converts that response to `NonRetryableError` and stops retries for that write. This response prevents repeated attempts for an envelope that cannot apply.
234
+
235
+ A Rails server can receive the same envelopes with `SolidObjects::Transmission.receive`. That method also skips message authorization. Authenticate the device before the call. Check its permission to write the actor.
236
+
237
+ ## Several tabs
238
+
239
+ Each tab starts its own worker. The workers share the database through `sharedSqliteWasm`. Writes from two tabs to one inspection apply in the local order.
240
+
241
+ The browser test records two findings in one tab and one finding in a second tab while offline. The server has no findings before the network returns. After the network returns, the server receives all three findings and applies each once, in order.
242
+
243
+ Run one effect worker for each local runtime to preserve the order of writes for each actor. [The transmit section of the public API](../api.md#solid-objectstransmit) states this requirement. This order belongs to each actor identity; it does not define one order across all inspections.
244
+
245
+ ## What this does not do
246
+
247
+ - It does not replicate server changes to the browser. Fetch the server state. Alternatively, subscribe with the WebSocket client in `solid-objects/browser`.
248
+ - It does not merge concurrent edits from different devices. The server applies writes in the order it receives them for each identity. The application defines the conflict rules. CRDT libraries such as [Yjs](https://yjs.dev) and [Automerge](https://automerge.org) support automatic merges of concurrent edits.
249
+ - Nothing runs while the browser is closed. Reminders and the outbox run only while a tab runs the worker. Queued writes wait in OPFS and send when a tab opens again.
250
+
251
+ ## Limits
252
+
253
+ - CI tests the browser runtime in Chromium only. Safari 16.4 and Firefox 111 added the OPFS API that persistent storage needs. Test each engine that you support.
254
+ - Persistent storage needs a secure context and a dedicated worker. An embedded WebView can lack OPFS even when the device browser supports it. Test the WebView itself.
255
+ - The browser can clear the storage of an origin. Call `navigator.storage.persist()` to ask the browser to keep it.
256
+ - All authorization callbacks deny by default, also in the browser. The example explicitly permits messages and queries for `Inspection`.
257
+ - Delivery is at least once. The server must stay idempotent: a repeated write must not cause another state change.
258
+
259
+ [Step 12 of the agent guide](../agents.md#12-use-the-browser-runtime) explains browser setup and policies. [Correctness and delivery semantics](../correctness.md) defines the guarantees and limits. [Virtual actors in TypeScript and Node.js](../virtual-actors.md) explains the actor model.
260
+
261
+ ## What the tests prove
262
+
263
+ The [browser tests](../../test/browser/offline-first.browser.ts) check these cases:
264
+
265
+ - Two tabs record three findings while offline. After the network returns, the server state contains each finding once, in the same order.
266
+ - A finding in the local actor state survives a page reload.
267
+ - Two findings in the outbox in page memory disappear after a page reload.
268
+
269
+ The [route tests](../../test/guide-offline-first.test.ts) check these cases:
270
+
271
+ - A request without device authorization receives 403 and adds no finding.
272
+ - An authorized request receives 200 and adds the expected finding.
273
+ - A repeated envelope receives 200 and leaves one finding.
274
+ - An envelope with an empty operation receives 422.
275
+ - An envelope for an actor type or an operation that the server removed receives 422.
276
+
277
+ These tests do not check every browser engine or every interruption during delivery. They also do not test `IdempotencyConflict` or the browser response to 422.
278
+
279
+ ## Sources
280
+
281
+ - MDN, [Background Synchronization API](https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API), checked October 9, 2026.
282
+ - MDN, [Web Locks API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API), checked October 9, 2026.
283
+ - [Yjs](https://yjs.dev), and [Automerge](https://automerge.org), checked October 9, 2026.