@somewhere-cloud/cli 0.38.155 → 0.38.156
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 +4 -1
- package/dist/commands/docs.js +1 -1
- package/dist/lib/bundle.js +276 -188
- package/dist/lib/bundle.js.map +3 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -3
- package/dist/docs/adopt.md +0 -39
- package/dist/docs/analytics.md +0 -161
- package/dist/docs/api-reference.md +0 -339
- package/dist/docs/api-surface.md +0 -2067
- package/dist/docs/app-mcp.md +0 -162
- package/dist/docs/architecture-patterns.md +0 -334
- package/dist/docs/auth-client.md +0 -531
- package/dist/docs/billing.md +0 -76
- package/dist/docs/browser.md +0 -639
- package/dist/docs/calendar.md +0 -298
- package/dist/docs/changes.md +0 -323
- package/dist/docs/cli.md +0 -407
- package/dist/docs/common-mistakes.md +0 -199
- package/dist/docs/connect-agent.md +0 -72
- package/dist/docs/cors.md +0 -114
- package/dist/docs/cron.md +0 -167
- package/dist/docs/database-engine.md +0 -167
- package/dist/docs/declared-data.md +0 -1656
- package/dist/docs/declared-files.md +0 -475
- package/dist/docs/deploy-intelligence.md +0 -188
- package/dist/docs/deploy.md +0 -733
- package/dist/docs/design-system.md +0 -273
- package/dist/docs/dev-environments.md +0 -496
- package/dist/docs/domain-ownership.md +0 -31
- package/dist/docs/domains.md +0 -370
- package/dist/docs/feedback.md +0 -88
- package/dist/docs/file-tools.md +0 -116
- package/dist/docs/functions.md +0 -489
- package/dist/docs/getting-started.md +0 -238
- package/dist/docs/github.md +0 -95
- package/dist/docs/google-calendar.md +0 -212
- package/dist/docs/groups.md +0 -836
- package/dist/docs/guarantees.md +0 -58
- package/dist/docs/handled-for-you.md +0 -224
- package/dist/docs/inspect.md +0 -171
- package/dist/docs/limits.md +0 -68
- package/dist/docs/live-data.md +0 -197
- package/dist/docs/live.md +0 -92
- package/dist/docs/local-dev.md +0 -30
- package/dist/docs/migration-supabase.md +0 -58
- package/dist/docs/payments.md +0 -1102
- package/dist/docs/portability.md +0 -194
- package/dist/docs/postgres.md +0 -301
- package/dist/docs/pricing-comparison.md +0 -42
- package/dist/docs/pricing.md +0 -39
- package/dist/docs/project-groups.md +0 -107
- package/dist/docs/projects.md +0 -380
- package/dist/docs/recipe-ai-agent.md +0 -112
- package/dist/docs/recipe-ai-features.md +0 -227
- package/dist/docs/recipe-ai-receipts.md +0 -783
- package/dist/docs/recipe-background-jobs.md +0 -369
- package/dist/docs/recipe-booking.md +0 -348
- package/dist/docs/recipe-csv-import.md +0 -390
- package/dist/docs/recipe-ecommerce.md +0 -127
- package/dist/docs/recipe-email.md +0 -282
- package/dist/docs/recipe-escalation.md +0 -133
- package/dist/docs/recipe-file-uploads.md +0 -159
- package/dist/docs/recipe-import-app.md +0 -110
- package/dist/docs/recipe-login.md +0 -457
- package/dist/docs/recipe-multi-chat.md +0 -198
- package/dist/docs/recipe-paid-api.md +0 -161
- package/dist/docs/recipe-pdfs.md +0 -205
- package/dist/docs/recipe-push-notifications.md +0 -107
- package/dist/docs/recipe-seo.md +0 -200
- package/dist/docs/recipe-signed-in-app.md +0 -330
- package/dist/docs/render.md +0 -99
- package/dist/docs/rooms.md +0 -554
- package/dist/docs/sdk.md +0 -287
- package/dist/docs/sdks.md +0 -24
- package/dist/docs/search.md +0 -199
- package/dist/docs/security-model.md +0 -168
- package/dist/docs/setup.md +0 -212
- package/dist/docs/smoke.md +0 -102
- package/dist/docs/speed.md +0 -298
- package/dist/docs/sql-compatibility.md +0 -96
- package/dist/docs/sw.agent.md +0 -248
- package/dist/docs/sw.ai.md +0 -1291
- package/dist/docs/sw.auth.md +0 -1811
- package/dist/docs/sw.billing.md +0 -171
- package/dist/docs/sw.db.md +0 -2128
- package/dist/docs/sw.email.md +0 -661
- package/dist/docs/sw.endpoint.md +0 -187
- package/dist/docs/sw.env.md +0 -303
- package/dist/docs/sw.fetch.md +0 -115
- package/dist/docs/sw.fs.md +0 -424
- package/dist/docs/sw.groups.md +0 -836
- package/dist/docs/sw.image.md +0 -69
- package/dist/docs/sw.jobs.md +0 -520
- package/dist/docs/sw.logs.md +0 -61
- package/dist/docs/sw.mail.md +0 -106
- package/dist/docs/sw.notifications.md +0 -78
- package/dist/docs/sw.push.md +0 -161
- package/dist/docs/sw.rateLimit.md +0 -67
- package/dist/docs/sw.web.md +0 -128
- package/dist/docs/tasks.md +0 -269
- package/dist/docs/test.md +0 -220
- package/dist/docs/tool-reference-account.md +0 -7
- package/dist/docs/tool-reference-ai.md +0 -121
- package/dist/docs/tool-reference-analytics.md +0 -37
- package/dist/docs/tool-reference-api.md +0 -19
- package/dist/docs/tool-reference-artifacts.md +0 -35
- package/dist/docs/tool-reference-auth.md +0 -163
- package/dist/docs/tool-reference-browser.md +0 -114
- package/dist/docs/tool-reference-code.md +0 -26
- package/dist/docs/tool-reference-connect.md +0 -21
- package/dist/docs/tool-reference-cron.md +0 -48
- package/dist/docs/tool-reference-db.md +0 -282
- package/dist/docs/tool-reference-domains.md +0 -107
- package/dist/docs/tool-reference-email.md +0 -55
- package/dist/docs/tool-reference-env.md +0 -19
- package/dist/docs/tool-reference-feedback.md +0 -56
- package/dist/docs/tool-reference-fs.md +0 -265
- package/dist/docs/tool-reference-github.md +0 -57
- package/dist/docs/tool-reference-groups.md +0 -85
- package/dist/docs/tool-reference-help.md +0 -29
- package/dist/docs/tool-reference-jobs.md +0 -39
- package/dist/docs/tool-reference-live.md +0 -48
- package/dist/docs/tool-reference-logs.md +0 -16
- package/dist/docs/tool-reference-payments.md +0 -44
- package/dist/docs/tool-reference-project.md +0 -706
- package/dist/docs/tool-reference-push.md +0 -78
- package/dist/docs/tool-reference-rate-limit.md +0 -18
- package/dist/docs/tool-reference-search.md +0 -68
- package/dist/docs/tool-reference-security.md +0 -42
- package/dist/docs/tool-reference-smoke.md +0 -17
- package/dist/docs/tool-reference-stock-photos.md +0 -20
- package/dist/docs/tool-reference-tasks.md +0 -73
- package/dist/docs/tool-reference-telegram.md +0 -32
- package/dist/docs/tool-reference-usage.md +0 -9
- package/dist/docs/tool-reference-web.md +0 -71
- package/dist/docs/tool-reference-webhooks.md +0 -9
- package/dist/docs/troubleshooting.md +0 -411
- package/dist/docs/typed-functions.md +0 -94
- package/dist/docs/verify-before-deploy.md +0 -67
- package/dist/docs/vs-supabase.md +0 -75
- package/dist/docs/vs-vercel.md +0 -103
package/dist/docs/rooms.md
DELETED
|
@@ -1,554 +0,0 @@
|
|
|
1
|
-
# Rooms — shared state, presence and messages on one row
|
|
2
|
-
|
|
3
|
-
## Quick start
|
|
4
|
-
|
|
5
|
-
A room is a live place attached to one database row. Everyone who may read
|
|
6
|
-
the row may join it. The room holds one shared state object, the list of who
|
|
7
|
-
is here, and quick throwaway messages, all on one connection. The room owns
|
|
8
|
-
the state: every change goes to the room, which orders it, applies it and
|
|
9
|
-
tells everyone. When the room is empty, the row is the truth.
|
|
10
|
-
|
|
11
|
-
Declare `rooms` on a table that has a single `id()` key:
|
|
12
|
-
|
|
13
|
-
```ts
|
|
14
|
-
// in db/schema.ts: a shared board
|
|
15
|
-
import { schema, table, id, text, json, shared } from 'somewhere/db'
|
|
16
|
-
|
|
17
|
-
export default schema({
|
|
18
|
-
boards: table(
|
|
19
|
-
{ id: id(), title: text({ default: '' }), state: json({ nullable: true }) },
|
|
20
|
-
{
|
|
21
|
-
scope: shared(),
|
|
22
|
-
client: { read: ['id', 'title'], create: ['title'] },
|
|
23
|
-
rooms: { save: 'state' },
|
|
24
|
-
},
|
|
25
|
-
),
|
|
26
|
-
})
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
Join from the browser with the module the platform serves on your app's own
|
|
30
|
-
origin. In TypeScript or a bundled page, import the same module as
|
|
31
|
-
`'somewhere:rooms'`, which carries its types (`joinRoom`, `watchLive`):
|
|
32
|
-
|
|
33
|
-
```js
|
|
34
|
-
// browser
|
|
35
|
-
import { joinRoom } from '/__sw/rooms/client.js'
|
|
36
|
-
|
|
37
|
-
const room = await joinRoom('boards', boardId)
|
|
38
|
-
render(room.state)
|
|
39
|
-
|
|
40
|
-
const stopState = room.on('state', (state) => render(state))
|
|
41
|
-
room.on('people', (people) => showAvatars(people))
|
|
42
|
-
room.on('message', (data, from) => moveCursor(from, data.cursor))
|
|
43
|
-
|
|
44
|
-
await room.set({ title: 'Launch plan' }) // shows at once; the room confirms it
|
|
45
|
-
room.send({ cursor: [3, 4] }) // to everyone else; not stored
|
|
46
|
-
room.me.set({ name: 'Ana' }) // shown beside this tab in room.people
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
`room.set` needs the person to be allowed to update the row. `on()` returns
|
|
50
|
-
a function that unsubscribes. Call `room.leave()` when the page stops showing
|
|
51
|
-
the room.
|
|
52
|
-
|
|
53
|
-
A room is one row. To keep a list of rows fresh on screen, declare a live
|
|
54
|
-
list with `sw.rooms.live` and follow it with `watchLive` from the same
|
|
55
|
-
module (see "Live lists" below). Rooms work on the live app only; previews
|
|
56
|
-
and drafts refuse them with `ROOMS_DRAFT_UNAVAILABLE`.
|
|
57
|
-
|
|
58
|
-
More sections: `rooms` → `declare-a-room`, `the-browser-room`,
|
|
59
|
-
`a-referee-decides-every-change`, `server-code`,
|
|
60
|
-
`who-can-join-and-what-they-see`, `example-a-two-player-game`, `live-lists`,
|
|
61
|
-
`limits`, `recovery`.
|
|
62
|
-
|
|
63
|
-
## Declare a room
|
|
64
|
-
|
|
65
|
-
Set `rooms: { save: 'state', referee: '/api/game-room' }` in the table options
|
|
66
|
-
in `db/schema.ts`. Both properties are optional.
|
|
67
|
-
|
|
68
|
-
- `save` names a `json` column on the same row. The room writes the state
|
|
69
|
-
there at most every 10 seconds while it changes, and again when everyone
|
|
70
|
-
leaves. The next join starts from that column (or `{}` when it is empty).
|
|
71
|
-
After a row exists, ordinary writes to that column are refused with
|
|
72
|
-
`ROOM_COLUMN_RESERVED`: only the room writes it.
|
|
73
|
-
- Without `save`, state is temporary. It is gone about 60 seconds after the
|
|
74
|
-
last person leaves.
|
|
75
|
-
- `referee` is the path of one of your app's own functions. It decides every
|
|
76
|
-
change. Without it, people change state with `room.set`.
|
|
77
|
-
|
|
78
|
-
There is no room directory. A room is one row, so listing rooms is listing
|
|
79
|
-
rows. When you redeploy with a changed `rooms` declaration, open rooms save
|
|
80
|
-
and close, and browsers rejoin on their own.
|
|
81
|
-
|
|
82
|
-
## The browser room
|
|
83
|
-
|
|
84
|
-
```js
|
|
85
|
-
import { joinRoom } from '/__sw/rooms/client.js'
|
|
86
|
-
|
|
87
|
-
const room = await joinRoom('games', gameId)
|
|
88
|
-
room.state // the current shared state, a plain object
|
|
89
|
-
room.version // a number; +1 for each accepted change
|
|
90
|
-
room.people // [{ id, user, me, info }]
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
In `room.people`, `id` is the connection id, `user` is the signed-in user id
|
|
94
|
-
or visitor id (`null` for someone with no session), `me` is `true` for this tab, and `info` is what that
|
|
95
|
-
connection set with `room.me.set(info)` (at most 1 KB). One person with two
|
|
96
|
-
tabs appears twice, with the same `user`.
|
|
97
|
-
|
|
98
|
-
Events:
|
|
99
|
-
|
|
100
|
-
```js
|
|
101
|
-
room.on('state', (state, change) => {}) // after every accepted change, and after each (re)join;
|
|
102
|
-
// change.by is the connection id that made it, or 'server'
|
|
103
|
-
room.on('people', (people) => {})
|
|
104
|
-
room.on('message', (data, from) => {})
|
|
105
|
-
room.on('timer_failed', () => {}) // the referee's timer failed 3 times
|
|
106
|
-
room.on('status', (status) => {}) // 'open' | 'reconnecting' | 'closed'
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
Changing state:
|
|
110
|
-
|
|
111
|
-
- `await room.set(patch)` is for rooms **without** a referee. It merges the
|
|
112
|
-
top-level keys of `patch` into the state; `null` deletes a key. It is
|
|
113
|
-
applied at once in this tab, and the room's answer confirms or corrects it.
|
|
114
|
-
- `await room.act(action)` is for rooms **with** a referee. It is not applied
|
|
115
|
-
locally. It resolves with the new state once the referee accepts. A
|
|
116
|
-
refusal rejects with `err.code` `REFEREE_REJECTED` and `err.reason`, the
|
|
117
|
-
plain reason your referee gave.
|
|
118
|
-
- `room.send(data)` sends a throwaway message to everyone else. It is not
|
|
119
|
-
stored and never changes the state.
|
|
120
|
-
|
|
121
|
-
The connection reconnects with backoff by itself. On every rejoin the room
|
|
122
|
-
sends the full state and people list; missed messages are not replayed. The
|
|
123
|
-
module renews the person's access every 4 minutes.
|
|
124
|
-
|
|
125
|
-
If the connection drops while an `act` is unanswered, the act rejects with
|
|
126
|
-
`ROOM_OUTCOME_UNKNOWN`, and `err.state` holds the fresh state. The action may
|
|
127
|
-
or may not have been applied. It is never sent again for you: look at
|
|
128
|
-
`err.state` and decide.
|
|
129
|
-
|
|
130
|
-
## A referee decides every change
|
|
131
|
-
|
|
132
|
-
A referee is an ordinary function at the declared path. It reads one event
|
|
133
|
-
and answers with one decision:
|
|
134
|
-
|
|
135
|
-
```ts
|
|
136
|
-
// the function at the declared referee path: a counter that only goes up
|
|
137
|
-
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
138
|
-
const ev = await sw.rooms.event(req)
|
|
139
|
-
// ev: { type: 'join' | 'leave' | 'action' | 'timer', state, version, action?,
|
|
140
|
-
// who, row: { table, id } }
|
|
141
|
-
if (ev.type !== 'action') return Response.json({})
|
|
142
|
-
const count = typeof ev.state.count === 'number' ? ev.state.count : 0
|
|
143
|
-
return Response.json({ state: { count: count + 1 } })
|
|
144
|
-
}
|
|
145
|
-
```
|
|
146
|
-
|
|
147
|
-
`who` says who caused the event:
|
|
148
|
-
|
|
149
|
-
| `who` | Caller |
|
|
150
|
-
|---|---|
|
|
151
|
-
| `{ user: '<user id>' }` | a signed-in user |
|
|
152
|
-
| `{ visitor: 'v_…' }` | an anonymous visitor; a stable id for that visitor in this app, not their session |
|
|
153
|
-
| `{ anonymous: true }` | someone with no session (a public-read row) |
|
|
154
|
-
| `'server'` | `sw.rooms.server.*` |
|
|
155
|
-
|
|
156
|
-
The `user` field in `room.people` is the same string as `who.user` or
|
|
157
|
-
`who.visitor` (`null` when anonymous), so the referee and the browser can
|
|
158
|
-
match seats.
|
|
159
|
-
|
|
160
|
-
`sw.rooms.event(req)` is the only way to read the event. It throws
|
|
161
|
-
`ROOM_EVENT_INVALID` unless the room really sent this event just now, so
|
|
162
|
-
nobody can call the path directly and forge a decision.
|
|
163
|
-
|
|
164
|
-
The decision is a JSON object; every field is optional:
|
|
165
|
-
|
|
166
|
-
| Field | Meaning |
|
|
167
|
-
|---|---|
|
|
168
|
-
| `state` | the whole new state |
|
|
169
|
-
| `reject` | a plain reason; the change is refused and the person sees it as `err.reason` |
|
|
170
|
-
| `timer` | seconds from now, 1 second to 7 days; `null` clears it; leave it out to keep the current timer |
|
|
171
|
-
| `send` | up to 10 messages, delivered to everyone like `room.send` |
|
|
172
|
-
|
|
173
|
-
How events arrive:
|
|
174
|
-
|
|
175
|
-
- Events are handled strictly one at a time per room. Two moves never race.
|
|
176
|
-
- `join` comes on a person's first connection; `leave` on their last. A
|
|
177
|
-
rejected `join` does not stop the person joining: they are simply not
|
|
178
|
-
seated as far as your state is concerned.
|
|
179
|
-
- `action` carries what `room.act` or `sw.rooms.act` sent.
|
|
180
|
-
- `timer` fires when the room's one timer runs out. A pending timer keeps
|
|
181
|
-
the room and its state alive with nobody present: it fires and the
|
|
182
|
-
referee runs even when everyone has gone.
|
|
183
|
-
- If the referee throws, answers with a non-2xx status or a bad shape, or
|
|
184
|
-
takes longer than 3 seconds, the change is refused with
|
|
185
|
-
`REFEREE_UNAVAILABLE` and the state is unchanged. A failed timer event is
|
|
186
|
-
retried 3 times; then everyone gets `timer_failed`.
|
|
187
|
-
|
|
188
|
-
A referee must only decide. It must not send email, take payments or write
|
|
189
|
-
elsewhere, and it must not call back into its own room: when a call times
|
|
190
|
-
out, its effects are not undone. Do outside work from your own functions
|
|
191
|
-
after the state changes.
|
|
192
|
-
|
|
193
|
-
## Server code
|
|
194
|
-
|
|
195
|
-
Inside a function that is handling a browser request, `sw.rooms` acts as the
|
|
196
|
-
person who made the request, with that person's permissions:
|
|
197
|
-
|
|
198
|
-
If the room uses a referee, pass an action that the referee accepts. For
|
|
199
|
-
the game below, the player whose turn it is can play an empty cell.
|
|
200
|
-
|
|
201
|
-
```ts
|
|
202
|
-
await sw.rooms.act('games', gameId, { cell: 0 })
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
For a room without a referee, set state directly. The caller needs permission
|
|
206
|
-
to update the row.
|
|
207
|
-
|
|
208
|
-
```ts
|
|
209
|
-
await sw.rooms.set('boards', boardId, { title: 'Final' })
|
|
210
|
-
```
|
|
211
|
-
|
|
212
|
-
Send a message or read the room state with either configuration.
|
|
213
|
-
|
|
214
|
-
```ts
|
|
215
|
-
await sw.rooms.send('boards', boardId, { toast: 'Saved' })
|
|
216
|
-
const { state, version, people } = await sw.rooms.get('boards', boardId)
|
|
217
|
-
```
|
|
218
|
-
|
|
219
|
-
Jobs and schedules have no browser caller, so plain `sw.rooms.*` there is
|
|
220
|
-
refused with `ROOM_NO_CALLER`. Use `sw.rooms.server.act`, `.set`, `.send`
|
|
221
|
-
and `.get` instead. They act as the platform (`who: 'server'`) on any row of
|
|
222
|
-
a table that declares rooms. That is explicit platform authority: never pass
|
|
223
|
-
a browser's input to `sw.rooms.server.*` without checking it yourself.
|
|
224
|
-
|
|
225
|
-
For agents, the `rooms_get` tool (`project_id`, `table`, `id`) returns the
|
|
226
|
-
state, the version and who is here.
|
|
227
|
-
|
|
228
|
-
## Who can join and what they see
|
|
229
|
-
|
|
230
|
-
- Joining needs permission to read the row, by the row's own read rule, for
|
|
231
|
-
a signed-in user or an anonymous visitor session. A row the person may not
|
|
232
|
-
read is refused with `ROOM_NOT_ALLOWED`.
|
|
233
|
-
- `room.set` needs permission to update the row. `room.act` needs only to
|
|
234
|
-
have joined; the referee decides.
|
|
235
|
-
- **Everyone who can join sees the whole state, the people list and every
|
|
236
|
-
message.** A room must not hold anything some participants may not see.
|
|
237
|
-
Keep secrets in the database behind your functions.
|
|
238
|
-
- Removing someone's access takes effect within 5 minutes.
|
|
239
|
-
- A room's stored state is erased within 10 minutes of its row or project
|
|
240
|
-
being deleted.
|
|
241
|
-
|
|
242
|
-
## Example: a two-player game
|
|
243
|
-
|
|
244
|
-
Tic-tac-toe with seats, move checks and a 30-second turn clock. A player who
|
|
245
|
-
lets the clock run out loses.
|
|
246
|
-
|
|
247
|
-
```ts
|
|
248
|
-
// db/schema.ts
|
|
249
|
-
import { schema, table, id, text, json, shared } from 'somewhere/db'
|
|
250
|
-
|
|
251
|
-
export default schema({
|
|
252
|
-
games: table(
|
|
253
|
-
{ id: id(), title: text({ default: '' }), state: json({ nullable: true }) },
|
|
254
|
-
{
|
|
255
|
-
scope: shared(),
|
|
256
|
-
client: { read: ['id', 'title'], create: ['title'] },
|
|
257
|
-
rooms: { save: 'state', referee: '/api/game-room' },
|
|
258
|
-
},
|
|
259
|
-
),
|
|
260
|
-
})
|
|
261
|
-
```
|
|
262
|
-
|
|
263
|
-
```ts
|
|
264
|
-
// api/game-room.ts — the referee
|
|
265
|
-
type Mark = 'x' | 'o'
|
|
266
|
-
type Game = { board: (Mark | null)[]; x: string | null; o: string | null; turn: Mark; winner: Mark | 'draw' | null }
|
|
267
|
-
|
|
268
|
-
const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
|
|
269
|
-
const TURN_SECONDS = 30
|
|
270
|
-
const NEW_GAME: Game = { board: Array(9).fill(null), x: null, o: null, turn: 'x', winner: null }
|
|
271
|
-
|
|
272
|
-
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
273
|
-
const ev = await sw.rooms.event(req)
|
|
274
|
-
const s = (Array.isArray(ev.state.board) ? ev.state : NEW_GAME) as Game
|
|
275
|
-
const me = ev.who === 'server' ? null
|
|
276
|
-
: 'user' in ev.who ? ev.who.user
|
|
277
|
-
: 'visitor' in ev.who ? ev.who.visitor
|
|
278
|
-
: null
|
|
279
|
-
|
|
280
|
-
if (ev.type === 'join') {
|
|
281
|
-
if (!me || s.x === me || s.o === me || s.winner) return Response.json({})
|
|
282
|
-
if (!s.x) return Response.json({ state: { ...s, x: me } })
|
|
283
|
-
if (!s.o) return Response.json({ state: { ...s, o: me }, timer: TURN_SECONDS })
|
|
284
|
-
return Response.json({}) // everyone else watches
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
if (ev.type === 'timer') {
|
|
288
|
-
if (s.winner || !s.o) return Response.json({ timer: null })
|
|
289
|
-
const winner: Mark = s.turn === 'x' ? 'o' : 'x'
|
|
290
|
-
return Response.json({ state: { ...s, winner }, timer: null, send: [{ note: 'Time ran out.' }] })
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
if (ev.type === 'action') {
|
|
294
|
-
const cell = (ev.action as { cell?: unknown } | undefined)?.cell
|
|
295
|
-
if (s.winner) return Response.json({ reject: 'The game is over.' })
|
|
296
|
-
if (!s.o) return Response.json({ reject: 'Wait for a second player.' })
|
|
297
|
-
if (!me || s[s.turn] !== me) return Response.json({ reject: 'It is not your turn.' })
|
|
298
|
-
if (typeof cell !== 'number' || !Number.isInteger(cell) || cell < 0 || cell > 8 || s.board[cell]) {
|
|
299
|
-
return Response.json({ reject: 'Pick an empty square.' })
|
|
300
|
-
}
|
|
301
|
-
const board = s.board.slice()
|
|
302
|
-
board[cell] = s.turn
|
|
303
|
-
const won = LINES.some((line) => line.every((i) => board[i] === s.turn))
|
|
304
|
-
const winner = won ? s.turn : board.every(Boolean) ? 'draw' : null
|
|
305
|
-
const turn: Mark = s.turn === 'x' ? 'o' : 'x'
|
|
306
|
-
return Response.json({ state: { ...s, board, turn, winner }, timer: winner ? null : TURN_SECONDS })
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
return Response.json({}) // leave: the seat stays
|
|
310
|
-
}
|
|
311
|
-
```
|
|
312
|
-
|
|
313
|
-
Create a game row from the page with the generated client,
|
|
314
|
-
`data.games.create({ title: 'Tic-tac-toe' })` (`docs({ topic: 'declared-data' })`),
|
|
315
|
-
and open the game page with `?game=<id>`:
|
|
316
|
-
|
|
317
|
-
```js
|
|
318
|
-
// browser — game page
|
|
319
|
-
import { joinRoom } from '/__sw/rooms/client.js'
|
|
320
|
-
|
|
321
|
-
const gameId = new URL(location.href).searchParams.get('game')
|
|
322
|
-
const room = await joinRoom('games', gameId)
|
|
323
|
-
const status = document.querySelector('#status')
|
|
324
|
-
const squares = document.querySelectorAll('[data-cell]')
|
|
325
|
-
|
|
326
|
-
function draw(state) {
|
|
327
|
-
squares.forEach((square) => {
|
|
328
|
-
square.textContent = state.board?.[Number(square.dataset.cell)] ?? ''
|
|
329
|
-
})
|
|
330
|
-
const mine = room.people.find((person) => person.me)?.user
|
|
331
|
-
const seat = mine && mine === state.x ? 'You are x. ' : mine && mine === state.o ? 'You are o. ' : ''
|
|
332
|
-
status.textContent = seat + (state.winner ? 'Result: ' + state.winner
|
|
333
|
-
: state.o ? state.turn + ' to move' : 'Waiting for a second player')
|
|
334
|
-
}
|
|
335
|
-
draw(room.state)
|
|
336
|
-
room.on('state', draw)
|
|
337
|
-
room.on('message', (msg) => { if (msg.note) status.textContent = msg.note })
|
|
338
|
-
room.on('timer_failed', () => { status.textContent = 'The turn clock stopped. Reload to continue.' })
|
|
339
|
-
|
|
340
|
-
squares.forEach((square) => {
|
|
341
|
-
square.addEventListener('click', async () => {
|
|
342
|
-
try {
|
|
343
|
-
await room.act({ cell: Number(square.dataset.cell) })
|
|
344
|
-
} catch (err) {
|
|
345
|
-
if (err.code === 'REFEREE_REJECTED') status.textContent = err.reason
|
|
346
|
-
else if (err.code === 'ROOM_OUTCOME_UNKNOWN') draw(err.state)
|
|
347
|
-
else throw err
|
|
348
|
-
}
|
|
349
|
-
})
|
|
350
|
-
})
|
|
351
|
-
```
|
|
352
|
-
|
|
353
|
-
The first two signed-in people to join are seated;
|
|
354
|
-
everyone else watches. Everyone can leave and come back: the board is saved
|
|
355
|
-
in the row.
|
|
356
|
-
|
|
357
|
-
## Live lists
|
|
358
|
-
|
|
359
|
-
A live list keeps a list of rows fresh in every open tab: new rows, edited
|
|
360
|
-
rows, rows entering or leaving the filter, a changed order, and rows a person
|
|
361
|
-
gains or loses access to. The rows always come from your own function, so
|
|
362
|
-
every access rule applies to each refresh. The connection carries only
|
|
363
|
-
"refresh now" notices; no row, SQL, table name, filter or owner travels on it.
|
|
364
|
-
|
|
365
|
-
Declare the list in a function with `sw.rooms.live(name, read)`. This one
|
|
366
|
-
reads an `owner()` notes table (its schema is in `docs({ topic: 'live' })`),
|
|
367
|
-
so each person sees only their own notes:
|
|
368
|
-
|
|
369
|
-
```ts
|
|
370
|
-
// api/open-notes.ts — the declaration and the read stay server-side
|
|
371
|
-
export default async function (_req: Request, sw: SomewhereRuntimeContext) {
|
|
372
|
-
return Response.json(await sw.rooms.live('notes.open', sw.db.from('notes', {
|
|
373
|
-
where: { done: false },
|
|
374
|
-
columns: ['id', 'title', 'done', 'created_at'],
|
|
375
|
-
order: [['created_at', 'desc'], ['id', 'asc']],
|
|
376
|
-
limit: 20,
|
|
377
|
-
})))
|
|
378
|
-
}
|
|
379
|
-
```
|
|
380
|
-
|
|
381
|
-
Follow it in the browser with `watchLive(load, render, onError?)`:
|
|
382
|
-
|
|
383
|
-
```js
|
|
384
|
-
// browser: load re-calls your function, never the database
|
|
385
|
-
import { watchLive } from '/__sw/rooms/client.js'
|
|
386
|
-
|
|
387
|
-
const list = document.querySelector('#open-notes')
|
|
388
|
-
if (!list) throw new Error('Add a list element with id open-notes to the page.')
|
|
389
|
-
|
|
390
|
-
const stop = watchLive(
|
|
391
|
-
async () => {
|
|
392
|
-
const response = await fetch('/api/open-notes', { credentials: 'include' })
|
|
393
|
-
if (!response.ok) throw new Error('Could not load your notes (' + response.status + ').')
|
|
394
|
-
return response.json()
|
|
395
|
-
},
|
|
396
|
-
(rows) => list.replaceChildren(...rows.map((note) => {
|
|
397
|
-
const item = document.createElement('li')
|
|
398
|
-
item.textContent = note.title
|
|
399
|
-
return item
|
|
400
|
-
})),
|
|
401
|
-
(err, { retrying }) => showBanner(retrying ? 'Reconnecting…' : 'Live updates paused: ' + err.message),
|
|
402
|
-
)
|
|
403
|
-
// Call stop() when the page stops showing the list.
|
|
404
|
-
```
|
|
405
|
-
|
|
406
|
-
`render(rows, result)` gets the function result's `data` array and the whole
|
|
407
|
-
parsed response. `onError(err, { attempt, retrying })` is optional; without
|
|
408
|
-
it, problems are written to the console with `console.error`.
|
|
409
|
-
|
|
410
|
-
What the declaration accepts:
|
|
411
|
-
|
|
412
|
-
- One direct `sw.db.from(...)` call on a declared table. Values may be
|
|
413
|
-
dynamic; the shape (table, columns, filter columns, order, limit) must be
|
|
414
|
-
written out, because deploy pins it to the release.
|
|
415
|
-
- `limit` is a positive integer literal and `order` is required, ending with
|
|
416
|
-
the table's key column(s). `offset` and `asServer` are not allowed.
|
|
417
|
-
Explicit `columns` must include the key and order columns.
|
|
418
|
-
- Tables with `owner()` (including `owner({ visitors: true })`), `shared()`,
|
|
419
|
-
`member()` and `group()` rules, app-role rules, and parent chains ending in
|
|
420
|
-
a group or an app role. A `member()` or `group()` list names one group by
|
|
421
|
-
equality, for example `where: { team_id: teamId }`. `serverOnly()` tables
|
|
422
|
-
are refused. Deploy refuses any other shape and says why.
|
|
423
|
-
- The name is unique within one release.
|
|
424
|
-
|
|
425
|
-
The function's result keeps `data`, `count` and the rest, and adds `live`:
|
|
426
|
-
|
|
427
|
-
{
|
|
428
|
-
data: [{ id: 1, title: 'Ship', done: 0, created_at: '2026-09-25T06:14:07.694Z' }],
|
|
429
|
-
live: { state: 'ready', name: 'notes.open', release_id: '…', fingerprint: '…',
|
|
430
|
-
subscribe_url: 'wss://your-app.somewhere.site/__sw/live/subscribe?…', expires_at: 1780000000000 },
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
`subscribe_url` holds a signed one-minute ticket bound to the person whose
|
|
434
|
-
session ran the read. Do not log it. In a preview, `live.state` is
|
|
435
|
-
`'unavailable'`: the rows still load, nothing follows them.
|
|
436
|
-
|
|
437
|
-
How it stays fresh:
|
|
438
|
-
|
|
439
|
-
- Structured inserts and removals notify live lists that depend on the
|
|
440
|
-
written table. Updates notify lists that depend on the written columns.
|
|
441
|
-
This applies to `sw.db`, `sw.db.server`, and the generated browser client.
|
|
442
|
-
- A `shared()` list notifies all subscribers. An `owner()` list notifies
|
|
443
|
-
subscribers for the owners identified before and after the write, including
|
|
444
|
-
writes by another user or server code. When the write can identify only
|
|
445
|
-
the signed-in writer, it can notify that writer's list. Other owners'
|
|
446
|
-
lists catch up on refresh.
|
|
447
|
-
- A group list notifies the groups identified by the write. A role list
|
|
448
|
-
notifies its role channel. When a membership change removes access, the
|
|
449
|
-
affected connections close before the write returns.
|
|
450
|
-
- With a separate managed database, `sw.db.tx` and `sw.db.server.tx` use each
|
|
451
|
-
step's write evidence to notify the same lists. On an older project that
|
|
452
|
-
keeps declared tables and raw SQL tables in one database, transactions
|
|
453
|
-
lack row-owner and group information. They can notify shared lists and
|
|
454
|
-
the acting user's owner lists. Other owners and groups catch up on refresh.
|
|
455
|
-
- The connection is opened with a refresh, so a change made between the
|
|
456
|
-
first load and the connection is shown.
|
|
457
|
-
- If the connection drops, `watchLive` reconnects through a fresh `load`,
|
|
458
|
-
which checks the person's access again. It also refreshes when the tab
|
|
459
|
-
becomes visible, when the network comes back, and every 60 seconds as a
|
|
460
|
-
safety net for a lost notice. Normal updates never wait for it.
|
|
461
|
-
- A failed `load` or `render` is reported and retried after 0.5, 1, 2, 4, 8
|
|
462
|
-
and 15 seconds, then reported as stopped until the next reconnect, focus or
|
|
463
|
-
safety refresh.
|
|
464
|
-
- A new deploy or a rollback closes the connection; `watchLive` reloads and
|
|
465
|
-
follows the new release.
|
|
466
|
-
- Each live-list connection lasts up to 5 minutes, then `watchLive` reconnects
|
|
467
|
-
through a fresh `load`. Each open live list counts toward the account's
|
|
468
|
-
people connected at once (see Limits); when that is full, `watchLive` reports
|
|
469
|
-
`ROOM_ACCOUNT_FULL` and stops until the tab becomes visible again or the
|
|
470
|
-
network comes back.
|
|
471
|
-
If admission is temporarily unavailable it reports
|
|
472
|
-
`ROOM_ADMISSION_UNAVAILABLE` and retries with a growing delay.
|
|
473
|
-
|
|
474
|
-
A write's result can carry `live_delivery`:
|
|
475
|
-
|
|
476
|
-
- `{ delivery: 'queued' }` or `{ delivery: 'invalidated' }`: notices are
|
|
477
|
-
queued for delivery or have already been sent. Queued notices go out just
|
|
478
|
-
after the write returns and are retried up to three times.
|
|
479
|
-
- `{ delivery: 'resync_required', reason }`: the platform could not confirm
|
|
480
|
-
every notice (for example, a write whose rows did not name all their
|
|
481
|
-
owners). Open lists catch up on their next refresh, and the failure is in
|
|
482
|
-
your app's logs.
|
|
483
|
-
|
|
484
|
-
Neither value means the write failed. Never retry a committed write because
|
|
485
|
-
of `live_delivery`.
|
|
486
|
-
|
|
487
|
-
Raw SQL writes through `sw.db.query`, `sw.db.batch`, or their `sw.db.server`
|
|
488
|
-
versions do not notify live lists. The
|
|
489
|
-
platform logs a `[SW_LIVE]` warning when one writes a live list's table; use
|
|
490
|
-
the structured write instead.
|
|
491
|
-
|
|
492
|
-
`sw.db.live` was the earlier name of this declaration. A deploy that still
|
|
493
|
-
calls it is refused with the rename to make.
|
|
494
|
-
|
|
495
|
-
## Usage
|
|
496
|
-
|
|
497
|
-
Rooms are measured in connected people-hours: the time each signed-in person
|
|
498
|
-
or visitor is connected to a room. Several tabs of the same person in one room
|
|
499
|
-
count once; the same person in two rooms counts in each. The project owner sees
|
|
500
|
-
`rooms.people_hours` (with a daily breakdown) in `GET /v1/usage`. The figure is
|
|
501
|
-
approximate: a room reports when it is already active, so a quiet room's
|
|
502
|
-
latest minutes can appear only after its next ticket renewal or when people leave.
|
|
503
|
-
|
|
504
|
-
## Limits
|
|
505
|
-
|
|
506
|
-
Refusals are typed and name the limit.
|
|
507
|
-
|
|
508
|
-
| Limit | Value |
|
|
509
|
-
|---|---|
|
|
510
|
-
| People in one room | 100 connections (`ROOM_FULL`) |
|
|
511
|
-
| People connected at once, across every room and live list in the account | Free: 200 (`ROOM_ACCOUNT_FULL`). Each signed-in app user or visitor counts once across all tabs and rooms of one project; the same identity in a different project counts separately. A connection with no identity, such as a shared live list, counts once per connection. Paid plans do not currently enforce an account-wide limit; that is not a promise of unlimited connections |
|
|
512
|
-
| State | 256 KB |
|
|
513
|
-
| One message | 4 KB |
|
|
514
|
-
| Presence info (`room.me.set`) | 1 KB |
|
|
515
|
-
| Inbound per connection | Sized for about 60 frames per second (frames beyond 75 in one second are refused) and 64 KB per second in total; of those, at most 20 `set`/`act` per second. Ticket renewals have their own budget, so heavy messaging never blocks them |
|
|
516
|
-
| Accepted changes per room | 10 per second |
|
|
517
|
-
| Referee events waiting per room | 50 (`ROOM_BUSY`) |
|
|
518
|
-
| Messages in one decision's `send` | 10 |
|
|
519
|
-
| Referee answer time | 3 seconds |
|
|
520
|
-
| Timer | 1 second to 7 days, one per room |
|
|
521
|
-
|
|
522
|
-
A limit other than the people count is refused with `ROOM_LIMIT`, which says
|
|
523
|
-
which limit.
|
|
524
|
-
|
|
525
|
-
## Recovery
|
|
526
|
-
|
|
527
|
-
| Code | Meaning and what to do |
|
|
528
|
-
|---|---|
|
|
529
|
-
| `ROOM_NOT_ALLOWED` | The person may not read this row (or may not update it, for `set`). Check the table's access rules and the signed-in user. |
|
|
530
|
-
| `ROOM_FULL` | 100 connections are already in the room. |
|
|
531
|
-
| `ROOM_ACCOUNT_FULL` | The account already has as many people connected at once as its plan allows, across all its rooms and live lists. Nobody is disconnected to make space. The client stops retrying; offer a deliberate retry later. |
|
|
532
|
-
| `ROOM_ADMISSION_UNAVAILABLE` | The connection could not be admitted right now. Nothing changed; try again shortly. |
|
|
533
|
-
| `ROOM_LIMIT` | A size or rate limit was hit; the message names it. Send less or less often. |
|
|
534
|
-
| `ROOM_BUSY` | 50 referee events are already waiting. Try again shortly. |
|
|
535
|
-
| `ROOM_HAS_REFEREE` | `set` was used on a room with a referee. Use `act`. |
|
|
536
|
-
| `ROOM_NO_REFEREE` | `act` was used on a room without a referee. Use `set`, or declare `referee`. |
|
|
537
|
-
| `REFEREE_REJECTED` | Your referee refused; show `err.reason`. |
|
|
538
|
-
| `REFEREE_UNAVAILABLE` | The referee threw, answered badly or took over 3 seconds. Nothing changed. Read the function's logs. |
|
|
539
|
-
| `ROOM_OUTCOME_UNKNOWN` | The connection dropped before an `act` was answered. Use `err.state` to decide whether to act again. |
|
|
540
|
-
| `ROOM_EVENT_INVALID` | `sw.rooms.event` got a request the room did not send. Only the room may call the referee. |
|
|
541
|
-
| `ROOM_NO_CALLER` | Plain `sw.rooms.*` ran with no browser caller. Use `sw.rooms.server.*`. |
|
|
542
|
-
| `ROOM_COLUMN_RESERVED` | A write tried to change the `save` column. Only the room writes it. |
|
|
543
|
-
| `ROOMS_DRAFT_UNAVAILABLE` | Rooms do not run in previews or drafts. Test on the live app. |
|
|
544
|
-
|
|
545
|
-
### Referee decisions and visitor sessions
|
|
546
|
-
|
|
547
|
-
A decision with a `reject` key is a rejection, including `reject: ''`. Its `state`
|
|
548
|
-
is ignored, but its `timer` and `send` still apply. This lets a refused action
|
|
549
|
-
correct a clock or send an explanation without changing state.
|
|
550
|
-
|
|
551
|
-
Anonymous participants must have a platform visitor session. The ticket door
|
|
552
|
-
resolves that session; it refuses entry when visitor identity is unavailable.
|
|
553
|
-
There are no sessionless room tickets. Referee failure alerts are aggregated
|
|
554
|
-
per project for one hour, across action, membership and timer failures.
|