@liveink/server 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/PROTOCOL.md +331 -0
- package/README.md +104 -2
- package/dist/chunks/chunk-5WGYVCZI.js +466 -0
- package/dist/chunks/chunk-5WGYVCZI.js.map +7 -0
- package/dist/cli.js +97 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +7 -0
- package/dist/types/cli.d.ts +2 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/server.d.ts +61 -0
- package/dist/types/storage.d.ts +29 -0
- package/package.json +70 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daniel Di Giovanni
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/PROTOCOL.md
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
# liveink wire protocol (v1)
|
|
2
|
+
|
|
3
|
+
How `<ink-canvas>` clients (`@liveink/canvas`) and a sync server (`@liveink/server`, or your own)
|
|
4
|
+
talk to each other.
|
|
5
|
+
|
|
6
|
+
This document is enough to write a compatible server (or client) in another language.
|
|
7
|
+
The document model is a [Yjs](https://github.com/yjs/yjs) CRDT; any Yjs-compatible
|
|
8
|
+
library can be used on the server (`yjs` in JS, `yrs`/`y-crdt` in Rust, `pycrdt`/`ypy` in Python,
|
|
9
|
+
`y-octo`, …). The server does **not** need to understand drawings: it merges Yjs updates,
|
|
10
|
+
relays presence, and stores bytes.
|
|
11
|
+
|
|
12
|
+
## 1. Transport
|
|
13
|
+
|
|
14
|
+
* One WebSocket per client per room: `ws://<host>:<port>/ws` (`wss://` behind TLS).
|
|
15
|
+
* **Binary frames only.** Text frames are answered with a non-fatal `ERROR text-frame` and ignored.
|
|
16
|
+
* Each WebSocket message is exactly one *frame*:
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
+---------+---------------------------+
|
|
20
|
+
| type u8 | payload (0..N bytes) |
|
|
21
|
+
+---------+---------------------------+
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
* JSON payloads are UTF-8 JSON **objects** (not arrays/scalars), max 64 KiB.
|
|
25
|
+
* Max frame size 16 MiB (server closes the socket with code 1009 above that).
|
|
26
|
+
* The component accepts any `InkTransport` (an ordered, reliable, binary, reconnecting pipe), so a
|
|
27
|
+
host can carry the very same frames over something other than WebSocket.
|
|
28
|
+
|
|
29
|
+
## 2. Frame types
|
|
30
|
+
|
|
31
|
+
| Hex | Name | Direction | Payload |
|
|
32
|
+
|------|---------------|-----------|---------|
|
|
33
|
+
| 0x00 | `HELLO` | C → S | JSON `{ "v": 1, "room": string, "user"?: { "id"?: string, "name"?: string, "color"?: string } }` |
|
|
34
|
+
| 0x01 | `WELCOME` | S → C | JSON `{ "v": 1, "room": string, "serverTime": number }` |
|
|
35
|
+
| 0x02 | `PING` | C → S | any bytes (≤ 64 echoed) |
|
|
36
|
+
| 0x03 | `PONG` | S → C | same bytes as the PING |
|
|
37
|
+
| 0x10 | `SYNC_STEP1` | C ↔ S | Yjs **state vector** (`Y.encodeStateVector(doc)`) |
|
|
38
|
+
| 0x11 | `SYNC_STEP2` | C ↔ S | Yjs **update** with everything the other side lacks (`Y.encodeStateAsUpdate(doc, theirStateVector)`) |
|
|
39
|
+
| 0x12 | `UPDATE` | C ↔ S | Incremental Yjs **update** (v1 encoding, as emitted by `doc.on('update')`) |
|
|
40
|
+
| 0x20 | `AWARENESS` | C ↔ S | y-protocols awareness update (`encodeAwarenessUpdate`, see §5) |
|
|
41
|
+
| 0x30 | `EPHEMERAL` | C ↔ S | JSON object, relayed verbatim to the *other* members of the room; never stored (see §6) |
|
|
42
|
+
| 0x7F | `ERROR` | S → C | JSON `{ "code": string, "message": string, "fatal": boolean }` |
|
|
43
|
+
|
|
44
|
+
Unknown frame types received by a **client** must be ignored (forward compatibility).
|
|
45
|
+
Unknown types received by the **server** produce a non-fatal `ERROR unknown-type`.
|
|
46
|
+
|
|
47
|
+
All Yjs payloads use the **v1** update encoding (`encodeStateAsUpdate`, not `…V2`).
|
|
48
|
+
|
|
49
|
+
## 3. Connection / join / resync flow
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
Client Server
|
|
53
|
+
| -- WS connect /ws ------------------------> |
|
|
54
|
+
| -- HELLO {v:1, room, user} ---------------> | validate; load room (async) — frames that
|
|
55
|
+
| -- SYNC_STEP1 (client state vector) ------> | arrive meanwhile are queued, in order
|
|
56
|
+
| -- AWARENESS (own state) -----------------> |
|
|
57
|
+
| <------------------------------ WELCOME --- |
|
|
58
|
+
| <------- SYNC_STEP1 (server state vector) - |
|
|
59
|
+
| <--- AWARENESS (all known peers' states) -- | (only if any)
|
|
60
|
+
| <-- SYNC_STEP2 (what the client lacks) ---- | reply to the client's STEP1
|
|
61
|
+
| -- SYNC_STEP2 (what the server lacks) ----> | reply to the server's STEP1 ← offline edits
|
|
62
|
+
| |
|
|
63
|
+
| <=========== UPDATE / AWARENESS / EPHEMERAL in both directions ==========> |
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Rules:
|
|
67
|
+
|
|
68
|
+
1. `HELLO` **must** be the first frame. Anything else first → fatal `ERROR not-joined`.
|
|
69
|
+
(`PING` is allowed at any time.)
|
|
70
|
+
2. A connection belongs to exactly one room for its lifetime; a second `HELLO` → non-fatal
|
|
71
|
+
`ERROR already-joined`. To switch rooms open a new connection.
|
|
72
|
+
3. Either side answers every `SYNC_STEP1` with a `SYNC_STEP2`. The client sends `SYNC_STEP1`
|
|
73
|
+
immediately after `HELLO`, the server sends its own after `WELCOME`. Because Yjs updates are
|
|
74
|
+
idempotent and commutative, this two-way exchange is all that is needed after *any*
|
|
75
|
+
(re)connect: edits made while offline are contained in the client's `SYNC_STEP2`.
|
|
76
|
+
4. The client considers itself **synced** after applying the server's `SYNC_STEP2`.
|
|
77
|
+
5. Server applies client `SYNC_STEP2`/`UPDATE` to the room document and broadcasts the
|
|
78
|
+
resulting update as `UPDATE` to all *other* connections of the room (never echoed to the sender).
|
|
79
|
+
6. Clients send every local Yjs update as `UPDATE` while connected. Updates produced while
|
|
80
|
+
disconnected are simply not sent; the next resync carries them.
|
|
81
|
+
7. Ordering: the server processes the frames of one connection strictly in order, and
|
|
82
|
+
relays to each receiver in the order it processed them. Clients rely on this only for
|
|
83
|
+
cosmetic purposes (an `EPHEMERAL live-end` arriving after the `UPDATE` that commits the same stroke).
|
|
84
|
+
|
|
85
|
+
### Reconnect (client side, reference implementation)
|
|
86
|
+
|
|
87
|
+
* Exponential backoff with jitter: 400 ms × 1.8ⁿ, capped at 10 s, ±25 % jitter; reset on success.
|
|
88
|
+
* Immediate retry on `online` and when the page becomes visible again.
|
|
89
|
+
* Heartbeat: `PING` every 10 s; if no `PONG` within ~8 s the socket is considered half-open
|
|
90
|
+
(typical after a tablet sleeps) and is replaced.
|
|
91
|
+
* On every reconnect the full flow in §3 is repeated (HELLO, STEP1, AWARENESS).
|
|
92
|
+
* The server additionally sends WebSocket-level pings every 30 s and terminates dead sockets.
|
|
93
|
+
|
|
94
|
+
## 4. Document schema (inside the Yjs doc)
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
doc.getMap("objects") : Y.Map< id: string, Y.Map<field, value> >
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Every value of `objects` is a nested `Y.Map` whose fields are the object's properties
|
|
101
|
+
(so concurrent edits of *different* fields of one object merge; the same field is last-writer-wins).
|
|
102
|
+
|
|
103
|
+
| field | type | objects | meaning |
|
|
104
|
+
|----------|----------|---------|---------|
|
|
105
|
+
| `id` | string | all | equals the key in `objects` |
|
|
106
|
+
| `type` | string | all | `stroke` · `line` · `rect` · `ellipse` · `text` · `fill` · `inkshape` |
|
|
107
|
+
| `author` | string | all | author/user id |
|
|
108
|
+
| `color` | string | all | CSS color |
|
|
109
|
+
| `z` | number | all | paint order (ascending; ties broken by `id` string compare) |
|
|
110
|
+
| `width` | number | stroke, line, rect, ellipse, inkshape | stroke width in logical units (inkshape: the width of the ink it was cut from; informational, see §4.3) |
|
|
111
|
+
| `fill` | string | rect, ellipse (optional) | Interior fill colour (CSS). Absent, `""` or `"none"` = unfilled. Set by the paint bucket. |
|
|
112
|
+
| `rings` | number[][] | fill, inkshape | Region rings, each flat `[x0, y0, x1, y1, …]` (≥ 3 points, implicitly closed), logical units, rounded to 0.01. Painted with the **even-odd** rule. |
|
|
113
|
+
| `points` | number[] | stroke | flat `[x0, y0, x1, y1, …]` in logical units (a single point = dot) |
|
|
114
|
+
| `x1,y1,x2,y2` | number | line, rect, ellipse | drag start / end corner in logical units |
|
|
115
|
+
| `x, y` | number | text | top-left of the first line |
|
|
116
|
+
| `text` | string | text | `\n`-separated lines |
|
|
117
|
+
| `fontSize` | number | text | logical units; line height = 1.25 × fontSize, baseline at 0.82 × fontSize |
|
|
118
|
+
|
|
119
|
+
Coordinates are logical page units (default page 1600 × 1000), independent of device size.
|
|
120
|
+
|
|
121
|
+
**Fill objects.** `{ id, type: "fill", author, color, z, rings }`. A fill is a static vector
|
|
122
|
+
region produced by the paint bucket: the free area around the tap, bounded by ink, grown a little
|
|
123
|
+
under the bounding ink so no halo shows. Moving or deleting the ink later does not change it.
|
|
124
|
+
Rendering order on every client:
|
|
125
|
+
|
|
126
|
+
1. the background
|
|
127
|
+
2. all fill-layer items, in ascending `z` / id order. These are `fill` objects (even-odd) and
|
|
128
|
+
the interiors of rect/ellipse objects that have `fill` set. A shape's interior uses its
|
|
129
|
+
centre-line geometry.
|
|
130
|
+
3. all ink, in ascending `z` / id order: strokes, shape outlines, `inkshape`s and text.
|
|
131
|
+
|
|
132
|
+
Fills are therefore always beneath ink, and newer fills are on top of older ones. Limits enforced
|
|
133
|
+
by clients: at most 20 000 rings and 600 000 coordinates per fill; rings with fewer than 3 points
|
|
134
|
+
are dropped. A recolour is a single-field update (`color`, or `fill` for shapes), so concurrent
|
|
135
|
+
recolours resolve last-writer-wins per field.
|
|
136
|
+
Clients ignore objects that fail validation (wrong types etc.), so a buggy peer cannot crash others.
|
|
137
|
+
Deletion = removing the key from `objects`. "Clear" = removing all keys in one transaction.
|
|
138
|
+
Undo/redo is purely client-side (Y.UndoManager restricted to the client's own transaction origin)
|
|
139
|
+
and is transmitted as normal updates.
|
|
140
|
+
|
|
141
|
+
The JSON export format (`toJSON()`) is `{ format: "ink-canvas", version: 1, width, height, background, objects: [...] }`
|
|
142
|
+
with the same fields, objects sorted by paint order.
|
|
143
|
+
|
|
144
|
+
### 4.1 Page settings
|
|
145
|
+
|
|
146
|
+
```
|
|
147
|
+
doc.getMap("page") : Y.Map
|
|
148
|
+
"background" : string // CSS colour of the page, 1–64 chars; absent = "#ffffff"
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
The background is document-level state, not an object: it is never erased or selected. It is set
|
|
152
|
+
in a client transaction with the client's own origin, so it is undone per user like any edit.
|
|
153
|
+
`toJSON()` writes it as the top-level `background` field; `loadJSON()` sets it from that field
|
|
154
|
+
(a file without it resets it to the default) in the same transaction that replaces the objects.
|
|
155
|
+
|
|
156
|
+
### 4.2 Pixel erase = ordinary edits
|
|
157
|
+
|
|
158
|
+
A pixel-erase gesture is committed by the erasing client as ordinary edits, grouped into one undo
|
|
159
|
+
step on that client; there is no erase object in the document. The reference client applies a
|
|
160
|
+
large erase as several small transactions (so its main thread never blocks), and peers receive them
|
|
161
|
+
as several `UPDATE`s; see §6. Let E be the swept area: the gesture's path
|
|
162
|
+
(the same points that were sent in `erase` messages, §6) ⊕ a disc of radius r (round caps and
|
|
163
|
+
joins). Then:
|
|
164
|
+
|
|
165
|
+
* a `stroke`, `line`, `rect` or `ellipse` whose ink meets E is **removed**, and each connected
|
|
166
|
+
piece of `ink − E` is **added** as a new `inkshape` (new id, same `color`, `z`, `author`, and
|
|
167
|
+
`width`). The ink is the shape's rendered centre-line (for a stroke the midpoint-quadratic
|
|
168
|
+
curve, §4.3) offset by `width/2` with round caps and joins. So the stored result is exactly what
|
|
169
|
+
the erasing client and its peers previewed;
|
|
170
|
+
* an `inkshape` that E meets gets `ink − E`: the largest piece **updates** its `rings` in place
|
|
171
|
+
(same id); further pieces are **added** as new `inkshape`s; nothing left = **removed**;
|
|
172
|
+
* a filled rect/ellipse that is cut also yields a new `fill` object (colour = the shape's `fill`,
|
|
173
|
+
same `z`) with E removed; if only its interior was touched, the shape keeps its id
|
|
174
|
+
and gets `fill: ""` (= unfilled) instead of being removed;
|
|
175
|
+
* a cut `fill` gets its `rings` field **updated in place** (or the object is removed if empty);
|
|
176
|
+
* a touched `text` is removed.
|
|
177
|
+
|
|
178
|
+
Peers therefore need nothing special to render the result, and undo is the normal Yjs undo of
|
|
179
|
+
the erasing client's step.
|
|
180
|
+
|
|
181
|
+
### 4.3 `inkshape` objects
|
|
182
|
+
|
|
183
|
+
`{ id, type: "inkshape", author, color, z, width, rings }`: ink that the pixel eraser has cut,
|
|
184
|
+
stored as its exact outline. One object is one connected piece: its outer ring(s) and the holes
|
|
185
|
+
inside them (islands inside a hole are separate objects). Rings never cross each other or
|
|
186
|
+
themselves (they come out of a polygon clipper), so the even-odd and non-zero rules paint the
|
|
187
|
+
same area; clients paint with **even-odd**, like `fill`. An `inkshape` is **ink**, not a fill:
|
|
188
|
+
|
|
189
|
+
* it renders in the ink pass (step 3 above), filled with `color` (no stroke);
|
|
190
|
+
* it is a boundary for the paint bucket (its rings are its ink outline) and a tap on it is a tap
|
|
191
|
+
on ink;
|
|
192
|
+
* it is selected, moved (all `rings` coordinates translated), deleted and object-erased like any
|
|
193
|
+
ink; hit-testing is point-in-rings (even-odd) or within the tolerance of a ring edge;
|
|
194
|
+
* SVG export: `<path d="M…L…Z…" fill="<color>" fill-rule="evenodd"/>` in the ink part;
|
|
195
|
+
* `width` is the width of the stroke/shape it came from. It does not change the geometry (the
|
|
196
|
+
shape is already an area, so it cannot be re-stroked thicker or thinner); the bucket uses it as
|
|
197
|
+
the stroke width for its tuck rule. Missing → 2.
|
|
198
|
+
|
|
199
|
+
Geometry used by this client (other clients only need to render the rings): centre-lines are
|
|
200
|
+
flattened to ≤ 0.03 units (strokes: `p0`, then a quadratic from the previous junction through
|
|
201
|
+
control point `p[i]` to the midpoint of `p[i]`,`p[i+1]`, …, a straight segment to the last point;
|
|
202
|
+
one point = a disc), arcs to ≤ 0.02 units, the boolean operation runs on a 1/32-unit integer
|
|
203
|
+
grid, and every ring is simplified with Ramer–Douglas–Peucker at 0.1 units before rounding to 0.01.
|
|
204
|
+
Limits as for `fill` (20 000 rings, 600 000 coordinates).
|
|
205
|
+
|
|
206
|
+
## 5. Awareness (presence)
|
|
207
|
+
|
|
208
|
+
Standard [y-protocols awareness](https://github.com/yjs/y-protocols) binary encoding:
|
|
209
|
+
|
|
210
|
+
```
|
|
211
|
+
varUint count
|
|
212
|
+
repeat count:
|
|
213
|
+
varUint clientID (the Yjs doc clientID of that tab)
|
|
214
|
+
varUint clock (monotonic per clientID)
|
|
215
|
+
varString stateJSON (JSON text, or "null" = client left)
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
(`varUint` / `varString` = lib0 encoding: LEB128-style unsigned varint; string = varUint byte length + UTF-8.)
|
|
219
|
+
|
|
220
|
+
State used by this component:
|
|
221
|
+
|
|
222
|
+
```json
|
|
223
|
+
{ "user": { "id": "abc", "name": "Calm Otter", "color": "#30a46c" },
|
|
224
|
+
"cursor": { "x": 812.4, "y": 233.1, "ptype": "pen", "down": false, "tool": "pen" } }
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
`cursor` is `null` when the pointer left the canvas. Cursor updates are throttled to 20 Hz.
|
|
228
|
+
Clients re-send their state every ~15 s (awareness renewal); states not renewed for 30 s are dropped.
|
|
229
|
+
|
|
230
|
+
Server duties:
|
|
231
|
+
|
|
232
|
+
* Keep an awareness instance per room. Apply incoming updates, remember which clientIDs each
|
|
233
|
+
connection announced, broadcast each applied update to the room's other connections.
|
|
234
|
+
* On `HELLO` send the full current awareness of the room (if non-empty).
|
|
235
|
+
* When a connection closes, mark its clientIDs as removed (state `null`, clock+1) and broadcast that.
|
|
236
|
+
|
|
237
|
+
A server that does not want to decode awareness may instead relay `AWARENESS` frames verbatim to
|
|
238
|
+
the other connections and cache the last frame per connection for newcomers; it then has to
|
|
239
|
+
synthesize a "removed" update on disconnect, so decoding is recommended.
|
|
240
|
+
|
|
241
|
+
## 6. Ephemeral messages (live strokes)
|
|
242
|
+
|
|
243
|
+
`EPHEMERAL` payloads are JSON objects relayed verbatim (the server only checks it is a JSON object
|
|
244
|
+
≤ 64 KiB). Defined kinds (`k`):
|
|
245
|
+
|
|
246
|
+
```jsonc
|
|
247
|
+
// in-progress stroke or shape, ~30 Hz while drawing
|
|
248
|
+
{ "k": "live", "c": 123456789, // sender's awareness clientID
|
|
249
|
+
"id": "q3k…", // id the object will have once committed
|
|
250
|
+
"tool": "pen" | "line" | "rect" | "ellipse",
|
|
251
|
+
"color": "#1f2328", "width": 4,
|
|
252
|
+
"pts": [x, y, x, y, …], // pen: points appended since last message; shapes: [x1,y1,x2,y2]
|
|
253
|
+
"from": 120 } // pen: index in the flat array where `pts` starts
|
|
254
|
+
// stroke finished (committed or cancelled)
|
|
255
|
+
{ "k": "live-end", "c": 123456789, "id": "q3k…" }
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
```jsonc
|
|
259
|
+
// in-progress pixel-eraser gesture, ~30 Hz, and at least every 1 s while it lasts
|
|
260
|
+
{ "k": "erase", "c": 123456789, "id": "q3k…", // gesture id (not an object id)
|
|
261
|
+
"r": 10, // eraser radius, logical units (0 < r ≤ 500)
|
|
262
|
+
"pts": [x, y, x, y, …], // centre-line points appended since last message
|
|
263
|
+
"from": 120 } // index in the flat array where `pts` starts
|
|
264
|
+
// the gesture ends with { "k": "live-end", "c": …, "id": "q3k…" }, sent right AFTER the UPDATE(s)
|
|
265
|
+
// that commit the cut (or after nothing, if nothing was erased / the gesture was cancelled)
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
The reference client computes the cut off its main thread after pen-up and applies it as a series
|
|
269
|
+
of small `UPDATE`s (one undo step for the sender; to peers they are ordinary updates). So there can
|
|
270
|
+
be a delay between the gesture's last `erase` message and `live-end`, and several `UPDATE`s in
|
|
271
|
+
between, each holding part of the cut. Receivers keep the mask until `live-end`; the reference
|
|
272
|
+
client also holds its own redraw until then (the mask already shows the result).
|
|
273
|
+
|
|
274
|
+
Receivers of `erase` mask the swept path (width 2r, round caps/joins) on their rendering of the
|
|
275
|
+
document: the ink is cleared and fills show the background colour. They drop the mask on
|
|
276
|
+
`live-end` (by then the committing UPDATE has been applied, because the server relays in order),
|
|
277
|
+
when the sender's awareness disappears, or after 5 s without messages (a cut normally lands well within
|
|
278
|
+
that; on a very large wipe on a slow device the mask may drop a moment early).
|
|
279
|
+
|
|
280
|
+
Receivers draw live strokes on their live layer, drop one when an object with the same `id`
|
|
281
|
+
appears in the document or `live-end` arrives, when the sender's awareness disappears, or after
|
|
282
|
+
5 s without updates. Unknown `k` values must be ignored.
|
|
283
|
+
|
|
284
|
+
## 7. Errors
|
|
285
|
+
|
|
286
|
+
| code | fatal | when |
|
|
287
|
+
|------|-------|------|
|
|
288
|
+
| `not-joined` | yes | first frame was not `HELLO` |
|
|
289
|
+
| `bad-hello` | yes | HELLO payload is not a JSON object |
|
|
290
|
+
| `version` | yes | `v` ≠ 1 |
|
|
291
|
+
| `bad-room` | yes | room is not a 1–128 char string without control chars |
|
|
292
|
+
| `join-failed` | yes | storage failure while opening the room |
|
|
293
|
+
| `queue-overflow` | yes | > 1000 frames sent before the join completed |
|
|
294
|
+
| `rate-limit` | first: no, later: yes | > 600 frames/s (frames over the limit are dropped; > 3× → close) |
|
|
295
|
+
| `already-joined` | no | second HELLO |
|
|
296
|
+
| `bad-frame` | no | empty frame |
|
|
297
|
+
| `text-frame` | no | text WebSocket frame |
|
|
298
|
+
| `bad-update` | no | Yjs update could not be applied |
|
|
299
|
+
| `bad-awareness` | no | awareness update could not be decoded |
|
|
300
|
+
| `bad-ephemeral` | no | EPHEMERAL payload not a JSON object ≤ 64 KiB |
|
|
301
|
+
| `unknown-type` | no | unknown frame type |
|
|
302
|
+
| `internal` | no | unexpected server exception while handling a frame |
|
|
303
|
+
|
|
304
|
+
After a fatal error the server closes the socket with code 1008; the reference client stops
|
|
305
|
+
reconnecting and reports `disconnected`. Clients must treat any other close as transient and reconnect.
|
|
306
|
+
|
|
307
|
+
## 8. Persistence (reference server)
|
|
308
|
+
|
|
309
|
+
* One `Y.Doc` per active room, loaded via `RoomStorage.loadRoom(room)` on first join.
|
|
310
|
+
* Saved as a full snapshot (`Y.encodeStateAsUpdate(doc)`) via `saveRoom(room, bytes)` 500 ms after
|
|
311
|
+
the last change (at most 5 s after the first unsaved change), when the last client leaves, and on shutdown.
|
|
312
|
+
* Rooms are unloaded 30 s after the last client left.
|
|
313
|
+
* `FileStorage` writes `./data/<slug>-<sha256(room)[0..16]>.ydoc` atomically (temp file + rename);
|
|
314
|
+
`MemoryStorage` keeps bytes in a Map (`STORAGE=memory npm start`).
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
interface RoomStorage {
|
|
318
|
+
loadRoom(room: string): Promise<Uint8Array | null>;
|
|
319
|
+
saveRoom(room: string, state: Uint8Array): Promise<void>;
|
|
320
|
+
deleteRoom?(room: string): Promise<void>;
|
|
321
|
+
}
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
Because the stored snapshot includes Yjs tombstones/state vectors, a client that was offline for
|
|
325
|
+
days can still merge its edits correctly when it reconnects.
|
|
326
|
+
|
|
327
|
+
## 9. Other HTTP endpoints (same port)
|
|
328
|
+
|
|
329
|
+
* `GET /healthz` → `{ ok, rooms, protocol }`
|
|
330
|
+
* `GET /api/info` → `{ addresses: [LAN IPv4…], port, protocol }` (used by the demo to show a typeable LAN link)
|
|
331
|
+
* everything else: static files of the demo (`dist/public`).
|
package/README.md
CHANGED
|
@@ -1,3 +1,105 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @liveink/server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sync server for [`@liveink/canvas`](https://www.npmjs.com/package/@liveink/canvas) (`<ink-canvas>`).
|
|
4
|
+
Every device that opens the same **room** sees the same drawing live:
|
|
5
|
+
|
|
6
|
+
- strokes appear while they are being drawn;
|
|
7
|
+
- edits merge without conflicts (Yjs CRDT);
|
|
8
|
+
- rooms are saved and reload on rejoin.
|
|
9
|
+
|
|
10
|
+
You can run it as a command, or mount it on your existing Node HTTP server.
|
|
11
|
+
|
|
12
|
+
## Run it
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npx @liveink/server --port 8080
|
|
16
|
+
# ws://localhost:8080/ws ← pass this to ink.connect()
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
--port <n> HTTP + WebSocket port (default 8080, env PORT)
|
|
21
|
+
--host <addr> bind address (default 0.0.0.0, env HOST)
|
|
22
|
+
--data-dir <dir> where rooms are saved (default ./liveink-data, env DATA_DIR)
|
|
23
|
+
--memory keep rooms in memory only (env STORAGE=memory)
|
|
24
|
+
--static <dir> also serve this folder over HTTP, e.g. your page (env STATIC_DIR)
|
|
25
|
+
--https also serve HTTPS/WSS; self-signed unless --cert/--key (env HTTPS=1)
|
|
26
|
+
--https-port <n> default 8443 (env HTTPS_PORT)
|
|
27
|
+
--cert, --key PEM files (env HTTPS_CERT, HTTPS_KEY)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
`GET /healthz` returns `{ ok, rooms, protocol }`.
|
|
31
|
+
|
|
32
|
+
## Use it as a library
|
|
33
|
+
|
|
34
|
+
Standalone:
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
import { createInkServer, FileStorage } from '@liveink/server';
|
|
38
|
+
|
|
39
|
+
const srv = await createInkServer({ port: 8080, storage: new FileStorage('./rooms') });
|
|
40
|
+
// … later
|
|
41
|
+
await srv.close(); // saves rooms
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Attached to the HTTP server your app already has (Express, Fastify, plain `http`):
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
import http from 'node:http';
|
|
48
|
+
import express from 'express';
|
|
49
|
+
import { createInkServer } from '@liveink/server';
|
|
50
|
+
|
|
51
|
+
const app = express();
|
|
52
|
+
const server = http.createServer(app);
|
|
53
|
+
await createInkServer({ server, path: '/ink' }); // handles only WebSocket upgrades on /ink
|
|
54
|
+
server.listen(3000);
|
|
55
|
+
// client: ink.connect('wss://your-site.example/ink', { room })
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
When attached, every other request and upgrade path stays with your app, and `close()` leaves
|
|
59
|
+
your server running.
|
|
60
|
+
|
|
61
|
+
### Options
|
|
62
|
+
|
|
63
|
+
| Option | Default | |
|
|
64
|
+
|---|---|---|
|
|
65
|
+
| `server` | (none) | Existing `http.Server` / `https.Server` to attach to. |
|
|
66
|
+
| `path` | `/ws` | WebSocket path. |
|
|
67
|
+
| `port`, `host` | `8080`, `0.0.0.0` | Standalone mode only. |
|
|
68
|
+
| `storage` | `MemoryStorage` | Where rooms persist (see below). |
|
|
69
|
+
| `staticDir` | `null` | Serve a folder over HTTP (standalone mode). |
|
|
70
|
+
| `info` | `false` | Serve `GET /api/info` (LAN addresses + port, for share links in demos). |
|
|
71
|
+
| `https` | (none) | `{ key, cert, port }`: also serve HTTPS/WSS (standalone mode). |
|
|
72
|
+
| `saveDebounceMs`, `saveMaxWaitMs` | `500`, `5000` | When a changed room is saved. |
|
|
73
|
+
| `roomIdleMs` | `30000` | Unload an empty room after this long. |
|
|
74
|
+
| `log` | `console.log` | |
|
|
75
|
+
|
|
76
|
+
### Storage
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
interface RoomStorage {
|
|
80
|
+
loadRoom(room: string): Promise<Uint8Array | null>; // the room's Yjs state, or null if new
|
|
81
|
+
saveRoom(room: string, state: Uint8Array): Promise<void>;
|
|
82
|
+
deleteRoom?(room: string): Promise<void>; // optional
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`FileStorage(dir)` writes one file per room (atomically); `MemoryStorage` keeps rooms in
|
|
87
|
+
memory. Implement `RoomStorage` to use Redis, S3, a database, and so on.
|
|
88
|
+
|
|
89
|
+
## Access and limits
|
|
90
|
+
|
|
91
|
+
Rooms are **open**: anyone who knows a room name can join it, and there is no authentication.
|
|
92
|
+
Use unguessable room names, or put the server behind your own auth (for example, attach it to
|
|
93
|
+
your app's server and check the session in front of the upgrade). The server validates every
|
|
94
|
+
message, enforces frame-size and rate limits, and drops misbehaving connections without
|
|
95
|
+
affecting the room.
|
|
96
|
+
|
|
97
|
+
## Protocol
|
|
98
|
+
|
|
99
|
+
The wire protocol is documented in [PROTOCOL.md](PROTOCOL.md) (also at
|
|
100
|
+
[docs/protocol.md](https://github.com/Danpythonman/liveink/blob/main/docs/protocol.md)), well enough to
|
|
101
|
+
write a compatible server in another language.
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
MIT
|