spacewave 0.0.0 → 0.57.7
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/AGENTS.md +82 -0
- package/API.md +364 -0
- package/CHANGELOG.md +11 -0
- package/LICENSE +191 -0
- package/README.md +349 -0
- package/dist/THIRD_PARTY_NOTICES.txt +4497 -0
- package/dist/build.json +6 -0
- package/dist/chunks/errors-BHnASqFk.mjs +2 -0
- package/dist/chunks/node.pb-ChF26ESv.mjs +2 -0
- package/dist/chunks/rolldown-runtime-Csi-cuKc.mjs +1 -0
- package/dist/engine-worker.mjs +112 -0
- package/dist/index.mjs +1 -0
- package/dist/react.mjs +1 -0
- package/dist/server.mjs +10 -0
- package/dist/types/core/sync/config.d.ts +55 -0
- package/dist/types/packages/spacewave/index.d.ts +7 -0
- package/dist/types/packages/spacewave/react.d.ts +1 -0
- package/dist/types/packages/spacewave/server.d.ts +4 -0
- package/dist/types/sdk/sync/access.d.ts +15 -0
- package/dist/types/sdk/sync/client.d.ts +37 -0
- package/dist/types/sdk/sync/errors.d.ts +12 -0
- package/dist/types/sdk/sync/json.d.ts +30 -0
- package/dist/types/sdk/sync/operation.d.ts +23 -0
- package/dist/types/sdk/sync/schema.d.ts +51 -0
- package/dist/types/web/sync/index.d.ts +4 -0
- package/dist/types/web/sync/react.d.ts +11 -0
- package/examples/task-board/package.json +25 -0
- package/examples/task-board/react.html +17 -0
- package/examples/task-board/react.tsx +235 -0
- package/examples/task-board/schema.ts +21 -0
- package/examples/task-board/server.ts +133 -0
- package/examples/task-board/style.css +154 -0
- package/examples/task-board/tsconfig.json +15 -0
- package/examples/task-board/vanilla.html +17 -0
- package/examples/task-board/vanilla.ts +190 -0
- package/package.json +54 -16
package/AGENTS.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Building with Spacewave
|
|
2
|
+
|
|
3
|
+
Use this guide when adding the `spacewave` npm package to an application. Start with the [README](README.md) for setup and the [API reference](API.md) for signatures and error codes. The [task board](examples/task-board) is a complete integration with vanilla TypeScript and React clients sharing one server.
|
|
4
|
+
|
|
5
|
+
## Package and runtime
|
|
6
|
+
|
|
7
|
+
Install with `npm install spacewave`, or use `spacewave@next` for a prerelease. Use ESM and Node.js `>=24.15.0 <25` for the server. The package contains its compiled engine; consuming it requires no Go compiler or installation scripts.
|
|
8
|
+
|
|
9
|
+
| Import | Use |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| `spacewave` | `defineSchema`, `connect`, `SyncError`, and public types |
|
|
12
|
+
| `spacewave/server` | `createServer` and server configuration types; Node only |
|
|
13
|
+
| `spacewave/react` | Optional `createSyncContext(schema)` bindings for React `>=19.2.0 <20` |
|
|
14
|
+
|
|
15
|
+
Use these public entry points. Package internals and generated engine files are implementation details.
|
|
16
|
+
|
|
17
|
+
For server type checking, install `@types/node` 24.x and include `"node"` in `compilerOptions.types`. React applications also need their matching React types. Check the application against the installed package so repository aliases cannot hide missing dependencies or exports.
|
|
18
|
+
|
|
19
|
+
## Shared schema
|
|
20
|
+
|
|
21
|
+
Keep one browser-safe schema module containing the application ID, version, collection validators, and declared mutation inputs and outputs. Import it from clients and the server. Keep token verification, authorization, and mutation handlers in server modules.
|
|
22
|
+
|
|
23
|
+
Use a Standard Schema v1 validator, such as Zod. Collection writes take validator inputs; reads return stored validator outputs. Store strict JSON: null, booleans, finite numbers, strings, arrays, and plain objects. A missing record is `undefined`; a stored `null` is a value.
|
|
24
|
+
|
|
25
|
+
Treat the schema ID and version as the persisted application's compatibility contract. To change an existing dataset's schema, supply an explicit migration from its stored version. `createServer` completes that maintenance transaction before admitting clients. See [Migration](API.md#migration).
|
|
26
|
+
|
|
27
|
+
## Server and access
|
|
28
|
+
|
|
29
|
+
Create one server per dataset directory. `createServer({ directory, schema, authenticate, authorize, mutations })` opens durable storage and returns after startup and maintenance finish.
|
|
30
|
+
|
|
31
|
+
- Return a stable `subject` and `scope` from the application's real token verifier. The scope selects the caller's dataset. Supply `expiresAt` or a revocation `signal` when available.
|
|
32
|
+
- Grant collection actions through `authorize({ principal, scope, collection, action })`. Read and write permissions are separate, and subscription deliveries recheck read permission. A prefix is a query selector, not an authorization boundary; this RC has no row-level authorization.
|
|
33
|
+
- Use `server.as(principal)` for server-side work that follows the same policy. Reserve `server.admin(scope)` for deliberate privileged operations; it bypasses collection authorization.
|
|
34
|
+
- Use `server.listen()` for a listener Spacewave owns, or `server.attach(http)` to add sync to an existing HTTP server. Set `allowedOrigins` for the frontend and use `wss://` with HTTPS. Pass tokens through `getAccessToken`, keeping them out of URLs.
|
|
35
|
+
- Call `await server.close()` during shutdown. It closes its attachments, application, and storage. When using `attach(http)`, close the supplied HTTP server separately.
|
|
36
|
+
|
|
37
|
+
The example's `local-demo` verifier is only for local development. Replace it before serving other users.
|
|
38
|
+
|
|
39
|
+
## Client and React lifetime
|
|
40
|
+
|
|
41
|
+
Await `connect({ url, schema, getAccessToken })` before using the database. Admission includes authentication and schema compatibility checks. `getAccessToken(signal)` runs for each connection attempt; obtain the current token there. The client manages reconnection.
|
|
42
|
+
|
|
43
|
+
Keep a database for the application's intended connection lifetime. Use `collection(name).subscribe()` or `.watch()` for changing state, and render freshness alongside the data:
|
|
44
|
+
|
|
45
|
+
| Status | Meaning |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| `loading` | Waiting for the first snapshot |
|
|
48
|
+
| `current` | Latest received snapshot on a live connection |
|
|
49
|
+
| `stale` | Last received snapshot while reconnecting |
|
|
50
|
+
| `error` | Subscription ended with a failure |
|
|
51
|
+
|
|
52
|
+
Snapshots contain all matching `{ key, value }` records, ordered by key. They replace the previous snapshot. A query supports only `{ prefix?: string }`; it has no SQL, pagination, row filters, or deltas.
|
|
53
|
+
|
|
54
|
+
Forward cancellation signals to operations. Release subscriptions when views leave and close the database with `await db.close()` when its application lifetime ends.
|
|
55
|
+
|
|
56
|
+
For React, call `createSyncContext(schema)` once at module scope. Its `SyncProvider` receives an existing database; `useCollection` manages the component's subscription and `useDatabase` exposes the database for writes. The application closes the database. Keep top-level calls to `connect()` in client startup modules; importing a package entry alone is safe during server rendering.
|
|
57
|
+
|
|
58
|
+
## Writes, transactions, and recovery
|
|
59
|
+
|
|
60
|
+
Use collection `put` and `delete` for single-record changes. For an operation spanning records, declare a named mutation and implement its handler with `context.collection(name)` so its reads and writes share one transaction. The server validates mutation inputs and outputs.
|
|
61
|
+
|
|
62
|
+
Keep external side effects out of mutation handlers. Transaction rollback and acceptance receipts cover collection data and the returned result; they cannot roll back an email, payment, or unrelated HTTP request.
|
|
63
|
+
|
|
64
|
+
Each write has a request ID. When recovery matters, choose the ID before dispatch and keep the exact input available. Handle `SyncError` by its stable `code`:
|
|
65
|
+
|
|
66
|
+
- On `UNCERTAIN`, acceptance is unknown. Offer a retry of the same operation with the same request ID and exact input. An accepted duplicate returns the original result, including after a server restart.
|
|
67
|
+
- On `CONFLICT`, the request ID was reused with different input. Correct the caller's request handling.
|
|
68
|
+
- On `UNAVAILABLE`, the server or storage cannot currently serve the operation. Preserve the user's intent and let the application decide when to retry.
|
|
69
|
+
|
|
70
|
+
Receipts remain for the dataset lifetime. The client has no durable offline replica, offline write queue, or optimistic updates. Render accepted server snapshots and keep any pending form input separate from them. See [Uncertain writes](API.md#uncertain-writes) for a concrete retry example.
|
|
71
|
+
|
|
72
|
+
## Verify the integration
|
|
73
|
+
|
|
74
|
+
Run the application against the installed artifact and check the behavior the change affects:
|
|
75
|
+
|
|
76
|
+
- Type-check shared schema, server code, and client code with strict TypeScript.
|
|
77
|
+
- Connect two clients in the same scope and a server writer. Confirm accepted changes reach both clients, then close and reopen the server to verify persistence.
|
|
78
|
+
- Exercise rejected tokens, denied operations, and separate scopes. Confirm each caller sees only its authorized dataset.
|
|
79
|
+
- Interrupt and restore the connection. Check stale state, recovery, and reuse of the original request ID for an uncertain write.
|
|
80
|
+
- Unmount subscribed views and close clients and servers. Confirm subscriptions and processes finish.
|
|
81
|
+
|
|
82
|
+
Keep queries sized for the view: defaults cap them at 10,000 records and 8 MiB per snapshot, with 256 KiB per record. Changes produce complete snapshots, so record count alone does not describe the workload. Measure scan and delivery time, memory, and storage growth with representative data before raising limits. See the [README's current scope](README.md#current-scope).
|
package/API.md
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
# Spacewave API reference
|
|
2
|
+
|
|
3
|
+
Spacewave provides typed live collections backed by durable storage. An
|
|
4
|
+
application declares a schema of collections and mutations. Clients hold one
|
|
5
|
+
WebSocket connection and read full snapshots that update live. A Node server
|
|
6
|
+
owns storage, authentication, and per-operation authorization.
|
|
7
|
+
|
|
8
|
+
Package entries:
|
|
9
|
+
|
|
10
|
+
- `spacewave`: schema, client, and error API for browsers and Node.
|
|
11
|
+
- `spacewave/server`: `createServer` for Node applications.
|
|
12
|
+
- `spacewave/react`: optional React bindings.
|
|
13
|
+
|
|
14
|
+
The server requires Node 24.15 or later, below 25. The React bindings require
|
|
15
|
+
React 19.2 or later, below 20.
|
|
16
|
+
|
|
17
|
+
## Schema
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { defineSchema } from 'spacewave'
|
|
21
|
+
import { z } from 'zod'
|
|
22
|
+
|
|
23
|
+
const todo = z.object({ title: z.string().min(1).max(120), done: z.boolean() })
|
|
24
|
+
|
|
25
|
+
export const schema = defineSchema({
|
|
26
|
+
id: 'task-board',
|
|
27
|
+
version: 1,
|
|
28
|
+
collections: { todos: todo },
|
|
29
|
+
mutations: {
|
|
30
|
+
completeTodo: {
|
|
31
|
+
input: z.object({ id: z.string().min(1) }),
|
|
32
|
+
output: todo,
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
})
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`defineSchema(schema)` checks that `id` is nonempty and `version` is a safe
|
|
39
|
+
integer from 1 to 4294967295, then returns the schema with its inferred types.
|
|
40
|
+
Collection and mutation values are Standard Schema v1 validators; zod is one
|
|
41
|
+
compatible library. `Input<V>` and `Output<V>` infer a validator's input and
|
|
42
|
+
output types.
|
|
43
|
+
|
|
44
|
+
Every stored value is JSON. A write must be JSON-compatible: null, booleans,
|
|
45
|
+
finite numbers, strings, arrays, and plain objects. `undefined`, `bigint`,
|
|
46
|
+
symbols, functions, non-finite numbers, cycles, and class instances are
|
|
47
|
+
rejected. Object keys are stored in a canonical sorted form, so the same value
|
|
48
|
+
always produces the same bytes.
|
|
49
|
+
|
|
50
|
+
The server validates each write against the validator and stores the
|
|
51
|
+
validator's output form. Reads and watch snapshots return that stored form, so
|
|
52
|
+
client types use `Output<V>`.
|
|
53
|
+
|
|
54
|
+
## Client
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { connect } from 'spacewave'
|
|
58
|
+
|
|
59
|
+
const db = await connect({
|
|
60
|
+
url: 'ws://localhost:8787/sync',
|
|
61
|
+
schema,
|
|
62
|
+
getAccessToken: () => 'local-demo',
|
|
63
|
+
})
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`connect(options)` returns `Promise<Database<S>>`. It resolves after
|
|
67
|
+
authentication, the wire and schema version check, and root admission. On
|
|
68
|
+
failure it closes the connection and throws `SyncError`.
|
|
69
|
+
|
|
70
|
+
`ConnectOptions<S>`:
|
|
71
|
+
|
|
72
|
+
| Field | Contract |
|
|
73
|
+
| --- | --- |
|
|
74
|
+
| `url` | WebSocket URL without credentials, query, or fragment. |
|
|
75
|
+
| `schema` | The application schema. |
|
|
76
|
+
| `getAccessToken(signal)` | Returns the token or a promise of it. Called for each connection attempt. |
|
|
77
|
+
| `signal?` | Aborting closes the client. |
|
|
78
|
+
| `requestTimeoutMs?` | Per-request timeout. Default 15000. |
|
|
79
|
+
|
|
80
|
+
`Database<S>`:
|
|
81
|
+
|
|
82
|
+
| Member | Contract |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| `connection` | `ConnectionStatus`: `current` state plus `subscribe(listener)`, which returns a disposer. |
|
|
85
|
+
| `collection(name)` | Typed access for one schema collection name. |
|
|
86
|
+
| `mutate(name, input, options?)` | Runs a declared mutation and returns its declared output type. |
|
|
87
|
+
| `close()` | Idempotent. Also available through `await using` (`AsyncDisposable`). |
|
|
88
|
+
|
|
89
|
+
`ConnectionState` is `{ status: 'ready' | 'reconnecting' | 'closed', error? }`.
|
|
90
|
+
A new client is `reconnecting` until admission completes, and `closed` after
|
|
91
|
+
`close()`.
|
|
92
|
+
|
|
93
|
+
One collection exposes:
|
|
94
|
+
|
|
95
|
+
| Member | Contract |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `get(key, options?)` | `Promise<Output \| undefined>`. |
|
|
98
|
+
| `scan(query?, options?)` | One full snapshot of the prefix, ordered by key. |
|
|
99
|
+
| `put(key, value, options?)` | Writes one record. `value` is the validator's input type. |
|
|
100
|
+
| `delete(key, options?)` | Removes one record. |
|
|
101
|
+
| `watch(query?, options?)` | `AsyncIterable<SubscriptionState<Output>>`. |
|
|
102
|
+
| `subscribe(query, observer, options?)` | Pushes states to `observer.next`; `observer.error?` sees failures. Returns an unsubscribe function. |
|
|
103
|
+
|
|
104
|
+
`CallOptions` is `{ signal?, requestId? }`. Forward `AbortSignal` into every
|
|
105
|
+
call; cancellation propagates to the server.
|
|
106
|
+
|
|
107
|
+
A record key is nonempty UTF-8 within 1024 bytes.
|
|
108
|
+
|
|
109
|
+
### Subscriptions
|
|
110
|
+
|
|
111
|
+
`SubscriptionState<T>` is `{ status, data, error? }` where `data` is a readonly
|
|
112
|
+
array of `{ key, value }` entries:
|
|
113
|
+
|
|
114
|
+
| Status | Meaning |
|
|
115
|
+
| --- | --- |
|
|
116
|
+
| `loading` | No snapshot has arrived yet. |
|
|
117
|
+
| `current` | The connection is live and `data` is its latest received server snapshot. |
|
|
118
|
+
| `stale` | The connection was lost; `data` is the last known snapshot. |
|
|
119
|
+
| `error` | The subscription ended; `error` says why. |
|
|
120
|
+
|
|
121
|
+
`Query` is `{ prefix?: string }`. An empty prefix covers the whole collection.
|
|
122
|
+
|
|
123
|
+
Each state carries the full snapshot of every record matching the prefix,
|
|
124
|
+
ordered by key. There are no per-row deltas and no per-row filters. The client
|
|
125
|
+
reconnects on its own: a lost connection publishes `stale` and the stream
|
|
126
|
+
resumes with `current` once the server admits the client again. An
|
|
127
|
+
unrecoverable failure publishes `error` and ends the stream.
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
const unsubscribe = db.collection('todos').subscribe({}, {
|
|
131
|
+
next: (state) => console.log(state.status, state.data.length),
|
|
132
|
+
})
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Uncertain writes
|
|
136
|
+
|
|
137
|
+
Every write carries a request ID. The client generates one when a call omits
|
|
138
|
+
`requestId`; the server accepts 1 to 128 characters.
|
|
139
|
+
|
|
140
|
+
The client retries a write once when a call fails with a recoverable
|
|
141
|
+
connection error, using the same request ID. If acceptance still cannot be
|
|
142
|
+
confirmed, the call throws `SyncError('UNCERTAIN', ..., requestId)`. The write may or may not have
|
|
143
|
+
been accepted. Retry the exact same call with the same request ID and input:
|
|
144
|
+
the server recognizes the duplicate and returns the original result. Reusing a
|
|
145
|
+
request ID with different input throws `CONFLICT`.
|
|
146
|
+
|
|
147
|
+
Receipts of accepted writes persist in each scope's dataset for the dataset
|
|
148
|
+
lifetime, so a retry stays idempotent across restarts.
|
|
149
|
+
|
|
150
|
+
The client keeps no offline queue and applies no optimistic writes. If the server is unreachable, operations fail with `UNAVAILABLE`; a write that may have been sent can fail with `UNCERTAIN`. The application decides when to retry. Rendered state comes from server snapshots.
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
import { SyncError } from 'spacewave'
|
|
154
|
+
|
|
155
|
+
const requestId = crypto.randomUUID()
|
|
156
|
+
try {
|
|
157
|
+
await db.collection('todos').put(id, todo, { requestId })
|
|
158
|
+
} catch (error) {
|
|
159
|
+
if (error instanceof SyncError && error.code === 'UNCERTAIN') {
|
|
160
|
+
// Same request ID, same input.
|
|
161
|
+
await db.collection('todos').put(id, todo, { requestId })
|
|
162
|
+
} else {
|
|
163
|
+
throw error
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Errors
|
|
169
|
+
|
|
170
|
+
`SyncError` extends `Error` with a stable `code` and, for writes, the
|
|
171
|
+
`requestId`.
|
|
172
|
+
|
|
173
|
+
| Code | Meaning |
|
|
174
|
+
| --- | --- |
|
|
175
|
+
| `VALIDATION` | Input, key, or configuration is invalid. |
|
|
176
|
+
| `AUTHENTICATION` | The token or principal was rejected, expired, or retired. |
|
|
177
|
+
| `DENIED` | `authorize` returned false. |
|
|
178
|
+
| `MISSING_COLLECTION` | The collection is not declared in the schema. |
|
|
179
|
+
| `SCHEMA_MISMATCH` | Application ID, schema version, or wire version differs. |
|
|
180
|
+
| `QUERY_LIMIT` | A record, snapshot, or scan limit was exceeded. |
|
|
181
|
+
| `CONFLICT` | A request ID was reused with different input. |
|
|
182
|
+
| `UNAVAILABLE` | The connection or storage is temporarily unavailable. |
|
|
183
|
+
| `UNCERTAIN` | A write's acceptance could not be confirmed. Retry the same request ID and input. |
|
|
184
|
+
| `STORAGE` | Durable storage failed. |
|
|
185
|
+
| `CLOSED` | The client or server is closed. |
|
|
186
|
+
|
|
187
|
+
## React
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
import { createSyncContext } from 'spacewave/react'
|
|
191
|
+
|
|
192
|
+
const { SyncProvider, useDatabase, useCollection } = createSyncContext(schema)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`createSyncContext(schema)` binds collection names and validator output types
|
|
196
|
+
at compile time. The schema argument carries no runtime state.
|
|
197
|
+
|
|
198
|
+
| Binding | Contract |
|
|
199
|
+
| --- | --- |
|
|
200
|
+
| `SyncProvider({ db, children })` | Supplies an already-connected `Database<S>`. It never opens, retries, or closes the db; the application owns that lifetime. |
|
|
201
|
+
| `useDatabase()` | Returns the typed `Database<S>`. Throws when no provider is above in the tree. |
|
|
202
|
+
| `useCollection(name, query?)` | Returns `SubscriptionState<Output>` for the collection. |
|
|
203
|
+
|
|
204
|
+
The subscription restarts only when the db, the collection name, or the query
|
|
205
|
+
prefix changes, so an inline query object does not resubscribe on every render.
|
|
206
|
+
While a subscription loads or restarts, the state is `loading`; the previous
|
|
207
|
+
query's data is not shown as current. Unmounting a component aborts its watch
|
|
208
|
+
signal. Closing the db remains the application's job, for example on
|
|
209
|
+
`pagehide`.
|
|
210
|
+
|
|
211
|
+
```tsx
|
|
212
|
+
function TodoList() {
|
|
213
|
+
const todos = useCollection('todos')
|
|
214
|
+
if (todos.status === 'loading') return <p>Loading tasks…</p>
|
|
215
|
+
if (todos.status === 'error') return <p>{todos.error?.message}</p>
|
|
216
|
+
return (
|
|
217
|
+
<ul>
|
|
218
|
+
{todos.data.map((entry) => (
|
|
219
|
+
<li key={entry.key}>{entry.value.title}</li>
|
|
220
|
+
))}
|
|
221
|
+
</ul>
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
createRoot(document.getElementById('app')!).render(
|
|
226
|
+
<SyncProvider db={db}>
|
|
227
|
+
<TodoList />
|
|
228
|
+
</SyncProvider>,
|
|
229
|
+
)
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
## Server
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
import { createServer } from 'spacewave/server'
|
|
236
|
+
|
|
237
|
+
const server = await createServer({
|
|
238
|
+
directory: './data',
|
|
239
|
+
schema,
|
|
240
|
+
authenticate: async (token) => {
|
|
241
|
+
if (token !== 'local-demo') throw new Error('unknown token')
|
|
242
|
+
return { subject: 'demo', scope: 'demo' }
|
|
243
|
+
},
|
|
244
|
+
authorize: ({ collection }) => collection === 'todos',
|
|
245
|
+
mutations: {
|
|
246
|
+
completeTodo: async (context, input) => {
|
|
247
|
+
const todo = await context.collection('todos').get(input.id)
|
|
248
|
+
if (!todo) throw new Error('unknown task')
|
|
249
|
+
const updated = { ...todo, done: true }
|
|
250
|
+
await context.collection('todos').put(input.id, updated)
|
|
251
|
+
return updated
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
})
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
`createServer(options)` returns `Promise<SyncServer<S, P>>`. It opens the
|
|
258
|
+
dataset, checks the stored application ID and version, runs any migration, and
|
|
259
|
+
only then returns a server that can admit callers. Failures throw `SyncError`.
|
|
260
|
+
|
|
261
|
+
`ServerOptions<S, P>`:
|
|
262
|
+
|
|
263
|
+
| Field | Contract |
|
|
264
|
+
| --- | --- |
|
|
265
|
+
| `directory` | Dataset directory. This is the public storage option. |
|
|
266
|
+
| `schema` | The application schema. |
|
|
267
|
+
| `authenticate(token, signal)` | Returns `Promise<Principal>`. Called once per connection after the wire and schema version check. Throwing rejects the connection; each connection gets one attempt. |
|
|
268
|
+
| `authorize(access)` | Returns `boolean \| Promise<boolean>`. Called for every operation and again for every watch delivery. |
|
|
269
|
+
| `mutations` | One handler per declared mutation. |
|
|
270
|
+
| `limits?` | `maxRecords` (default 10000), `maxSnapshotBytes` (default 8 MiB), `maxRecordBytes` (default 256 KiB). Exceeding a bound fails that query or write with `QUERY_LIMIT`. |
|
|
271
|
+
| `migration?` | Runs before any caller is admitted when the stored schema version differs. |
|
|
272
|
+
|
|
273
|
+
Storage uses built-in SQLite in a dedicated worker. A directory permits one open server writer at a time.
|
|
274
|
+
|
|
275
|
+
`Principal` is `{ subject, scope, expiresAt?, signal? }`. `subject` and `scope`
|
|
276
|
+
must be nonempty, with `subject` within 256 UTF-8 bytes. `expiresAt` is a Unix
|
|
277
|
+
millisecond time; the connection retires at that time. Aborting `signal`
|
|
278
|
+
retires the connection.
|
|
279
|
+
|
|
280
|
+
`authorize` receives `{ principal, scope, collection, action }` where `action`
|
|
281
|
+
is `'read'` or `'write'`. Returning false rejects the operation with `DENIED`.
|
|
282
|
+
Authorization is per collection and action; queries cover a whole collection
|
|
283
|
+
or a prefix. There are no per-row grants or filters.
|
|
284
|
+
|
|
285
|
+
A mutation handler receives `(context, input)` and returns the mutation
|
|
286
|
+
output's input type. `context` provides `collection(name)` with `get`, `scan`,
|
|
287
|
+
`put`, and `delete` inside the same transaction, plus `principal`, `scope`,
|
|
288
|
+
and `signal`. The server validates the handler's input and returned output
|
|
289
|
+
against the schema and stores the output form.
|
|
290
|
+
|
|
291
|
+
### Migration
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
migration: {
|
|
295
|
+
from: 1,
|
|
296
|
+
async run({ scopes, scope }) {
|
|
297
|
+
for (const name of await scopes()) {
|
|
298
|
+
const todos = scope(name).collection('todos')
|
|
299
|
+
for (const entry of await todos.scan()) {
|
|
300
|
+
await todos.put(entry.key, { title: entry.value.title, done: false })
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
}
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
`Migration<S>` is `{ from, run(context) }`. `run` receives `scopes()` listing
|
|
308
|
+
the stored scopes, `scope(name)` returning a transaction for that scope, and
|
|
309
|
+
`signal`. The migration runs inside one maintenance transaction before any
|
|
310
|
+
caller is admitted. If the stored version differs and no matching migration is
|
|
311
|
+
supplied, or the dataset belongs to a different application ID, `createServer`
|
|
312
|
+
fails with `SCHEMA_MISMATCH`.
|
|
313
|
+
|
|
314
|
+
### Hosting and lifetime
|
|
315
|
+
|
|
316
|
+
| Member | Contract |
|
|
317
|
+
| --- | --- |
|
|
318
|
+
| `listen(options?)` | Opens its own HTTP server. `ListenerOptions` adds `port?` (default 8787) and `host?` (default 127.0.0.1). Returns `Listener` with a `ws://` `url` and `close()`. |
|
|
319
|
+
| `attach(http, options?)` | Handles the upgrade event of a supplied HTTP server. Other routes and upgrade paths stay yours. Returns `Attachment` with `close()`. |
|
|
320
|
+
| `as(principal)` | `DatabaseAccess<S>` for direct server-side access as that principal. Every operation still passes `authorize`. |
|
|
321
|
+
| `admin(scope)` | Privileged access as subject `admin`, with only the base principal fields. Handlers that require application-specific principal fields should use `as(principal)`. Collection authorization is bypassed; validation still applies. |
|
|
322
|
+
| `close()` | Closes every attachment the server created, then the application, then storage the server opened. Idempotent. Also available through `await using`. |
|
|
323
|
+
|
|
324
|
+
`AttachmentOptions` for both forms:
|
|
325
|
+
|
|
326
|
+
| Field | Contract |
|
|
327
|
+
| --- | --- |
|
|
328
|
+
| `path?` | Upgrade path. Default `/sync`. |
|
|
329
|
+
| `allowedOrigins?` | Exact Origin values to accept. |
|
|
330
|
+
| `maxRequestBytes?` | Maximum WebSocket message size. Default 1 MiB. |
|
|
331
|
+
|
|
332
|
+
Origin handling: a request without an Origin header, such as a non-browser
|
|
333
|
+
client, is accepted. With `allowedOrigins` set, the Origin must be one of the
|
|
334
|
+
listed values. Otherwise the Origin must match the request's own Host header
|
|
335
|
+
with an `http` or `https` scheme. Upgrades with a query string are refused.
|
|
336
|
+
|
|
337
|
+
```ts
|
|
338
|
+
import { createServer as createHTTPServer } from 'node:http'
|
|
339
|
+
|
|
340
|
+
const listener = await server.listen({ port: 8787 })
|
|
341
|
+
console.log(listener.url)
|
|
342
|
+
|
|
343
|
+
const http = createHTTPServer((request, response) => response.end())
|
|
344
|
+
server.attach(http, { path: '/sync', allowedOrigins: ['https://example.com'] })
|
|
345
|
+
http.listen(3000)
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
## Limits and performance
|
|
349
|
+
|
|
350
|
+
Queries return complete, ordered snapshots of a collection or prefix. Defaults bound a query to 10,000 records and 8 MiB of encoded keys and values, and a record to 256 KiB. Exceeding a bound produces `QUERY_LIMIT`. These are safety bounds, not throughput guarantees.
|
|
351
|
+
|
|
352
|
+
A qualification workload on Node 24.21.0 and macOS arm64 used 1,000 numeric records, three subscribers, and ten writes. Identical queries shared one producer.
|
|
353
|
+
|
|
354
|
+
| Measurement | Observed sample |
|
|
355
|
+
| --- | --- |
|
|
356
|
+
| Write acceptance, p50 / p95 | 234 / 242 ms |
|
|
357
|
+
| Delivery to all subscribers, p50 / p95 | 947 / 1,041 ms |
|
|
358
|
+
| Initial bulk seeding | 13.57 seconds |
|
|
359
|
+
| RSS when ready / after the workload | 336 MB / 1.10 GB |
|
|
360
|
+
| Encoded snapshot | 28.9 KB |
|
|
361
|
+
|
|
362
|
+
Each changed revision still requires a complete scan. RSS includes the compiled runtime and is not a retained-heap measurement. These observations describe one workload; measure representative scan and delivery time, memory, and storage growth before raising limits. Acceptance receipts and World history accumulate for the dataset lifetime.
|
|
363
|
+
|
|
364
|
+
A qualified release artifact's `qualification.json` records its own sample, source revision, package sizes, and checksum. See the [README](README.md) for supported runtimes and current release scope.
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Release notes
|
|
2
|
+
|
|
3
|
+
## 0.1.0-rc.1
|
|
4
|
+
|
|
5
|
+
The first typed sync release candidate provides shared Standard Schema contracts, live ordered collections, named atomic server mutations, scoped authentication and authorization, durable SQLite storage, retained acceptance receipts, reconnect recovery, and optional React bindings.
|
|
6
|
+
|
|
7
|
+
The package ships ESM client, server, and React exports with public TypeScript declarations and a compiled engine worker. Node 24.15–24.x is required for the server. Complete vanilla TypeScript and React task boards use the same contract and storage.
|
|
8
|
+
|
|
9
|
+
Subscriptions share a bounded producer for identical scope, collection, and prefix queries. Each subscriber retains its own authorization checks and cancellation lifetime. Query limits fail the affected subscription while independent queries continue.
|
|
10
|
+
|
|
11
|
+
This RC supports online authoritative operation. Offline replicas, optimistic writes, receipt pruning, and SQL query APIs are outside this release. The schema version is an application compatibility contract; changing it requires an explicit maintenance migration. Receipts and World history increase storage over the dataset lifetime. See the README for measured workload limits.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright (c) 2018-2026 Aperture Robotics, LLC.
|
|
179
|
+
Copyright (c) 2018-2026 Christian Stewart <christian@cjs.zip>
|
|
180
|
+
|
|
181
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
+
you may not use this file except in compliance with the License.
|
|
183
|
+
You may obtain a copy of the License at
|
|
184
|
+
|
|
185
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
+
|
|
187
|
+
Unless required by applicable law or agreed to in writing, software
|
|
188
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
+
See the License for the specific language governing permissions and
|
|
191
|
+
limitations under the License.
|