@prenta/realtime 0.2.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/CHANGELOG.md +49 -0
- package/LICENSE +21 -0
- package/README.md +470 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/persistence.d.ts +45 -0
- package/dist/persistence.d.ts.map +1 -0
- package/dist/persistence.js +120 -0
- package/dist/persistence.js.map +1 -0
- package/dist/protocol.d.ts +52 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +120 -0
- package/dist/protocol.js.map +1 -0
- package/dist/room.d.ts +93 -0
- package/dist/room.d.ts.map +1 -0
- package/dist/room.js +189 -0
- package/dist/room.js.map +1 -0
- package/package.json +60 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# @actuate-media/realtime
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 5eea995: Product rename: ActuateCMS is now **Prenta**. Every package moves from the
|
|
8
|
+
`@actuate-media/*` scope to `@prenta/*` with simplified names (`@prenta/core`,
|
|
9
|
+
`@prenta/admin`, `create-prenta`), and version numbers continue from where the
|
|
10
|
+
old scope left off.
|
|
11
|
+
|
|
12
|
+
This is a clean break — no backwards-compat aliases:
|
|
13
|
+
- **npm packages**: `@actuate-media/cms-core` → `@prenta/core`,
|
|
14
|
+
`@actuate-media/cms-admin` → `@prenta/admin`, all other packages keep their
|
|
15
|
+
suffix under `@prenta/*`. `create-actuate-cms` → `create-prenta`
|
|
16
|
+
(`npm create prenta`), `create-actuate-astro` → `create-prenta-astro`.
|
|
17
|
+
CLI bins: `actuate`/`actuate-cms` → `prenta`/`prenta-cms`; `actuate-mcp` →
|
|
18
|
+
`prenta-mcp`.
|
|
19
|
+
- **Database**: migration `0012_rename_to_prenta` renames all 36 `actuate_*`
|
|
20
|
+
tables to `prenta_*` in place (plus prefixed constraints, indexes, and
|
|
21
|
+
sequences). Run `prisma migrate deploy` when upgrading.
|
|
22
|
+
- **Runtime identifiers**: `getActuateConfig` → `getPrentaConfig`,
|
|
23
|
+
`handleActuateAPI` → `handlePrentaAPI`, `ActuateClient` → `PrentaClient`,
|
|
24
|
+
`ActuateDB` → `PrentaDB`, config file `actuate.config.ts` →
|
|
25
|
+
`prenta.config.ts`, CSS scopes `.actuate-admin`/`.actuate-canvas` →
|
|
26
|
+
`.prenta-admin`/`.prenta-canvas`, preview protocol `actuate-preview:*` →
|
|
27
|
+
`prenta-preview:*`, webhook headers `X-Actuate-*` → `X-Prenta-*`, session
|
|
28
|
+
cookie `actuate_session` → `prenta_session`, env vars `ACTUATE_*` →
|
|
29
|
+
`PRENTA_*`, purge route `/api/actuate/purge` → `/api/prenta/purge`.
|
|
30
|
+
- **Sessions and webhooks**: all sessions reset on upgrade (cookie + JWT issuer
|
|
31
|
+
changed); webhook consumers must re-verify signatures against the new
|
|
32
|
+
`X-Prenta-*` headers.
|
|
33
|
+
|
|
34
|
+
The old `@actuate-media/*` packages are deprecated on npm and will receive no
|
|
35
|
+
further releases.
|
|
36
|
+
|
|
37
|
+
## 0.1.2
|
|
38
|
+
|
|
39
|
+
### Patch Changes
|
|
40
|
+
|
|
41
|
+
- 041a228: Add the MIT `license` field to every published package (previously missing) and correct `repository.url` to `github.com/actuate-media/actuatecms` (13 packages carried the wrong org).
|
|
42
|
+
|
|
43
|
+
## 0.1.1
|
|
44
|
+
|
|
45
|
+
### Patch Changes
|
|
46
|
+
|
|
47
|
+
- 854152d: Developer experience improvements from external-consumer feedback:
|
|
48
|
+
- Every published package now ships its `CHANGELOG.md` in the npm tarball, and packages that were missing a `README.md` (cli, cms-admin, cms-core, import, platform-vercel, all plugins, sections-react) now have one — so release notes and usage docs are visible on npmjs.com and in `node_modules`.
|
|
49
|
+
- New client-safe form validation entry point: `@actuate-media/cms-core/forms/client` exports `validateFormFieldClient()`, `validateFormValuesClient()`, visibility/conditional helpers, and the exact `FORM_EMAIL_RE` / `FORM_PHONE_RE` regexes the server enforces — zero Node dependencies, so public-site forms can mirror server rules without reimplementing them. The server validator now imports the same primitives, so client and server can never drift.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Actuate Media
|
|
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/README.md
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
# @prenta/realtime
|
|
2
|
+
|
|
3
|
+
Transport-agnostic Yjs collaboration primitives that power Prenta CMS'
|
|
4
|
+
real-time editing surface (Phase 3 of the [roadmap](../../docs/roadmap-status.md)).
|
|
5
|
+
|
|
6
|
+
The package is intentionally narrow: it owns the **wire protocol**, the
|
|
7
|
+
**room state machine**, and the **persistence contract**. It knows nothing
|
|
8
|
+
about HTTP, WebSocket, or any specific server framework — those concerns
|
|
9
|
+
live in `@prenta/core` (the `/realtime/sync` endpoint) and the
|
|
10
|
+
admin TipTap collaboration extension.
|
|
11
|
+
|
|
12
|
+
## What you get
|
|
13
|
+
|
|
14
|
+
- **Protocol layer (`./protocol`).** Pure encode/decode helpers for the
|
|
15
|
+
binary envelope used by `y-websocket`. Read inbound frames with
|
|
16
|
+
`readMessage`; produce outbound ones with `encodeSyncStep1`,
|
|
17
|
+
`encodeSyncStep2`, `encodeUpdateMessage`, `encodeAwarenessUpdate`,
|
|
18
|
+
`encodeQueryAwareness`. The envelope is byte-compatible with the
|
|
19
|
+
upstream y-websocket provider, so standard browser clients (including
|
|
20
|
+
`@tiptap/extension-collaboration`'s default transport) work without any
|
|
21
|
+
custom wire shimming.
|
|
22
|
+
- **Room (`./room`).** `createRoom({ documentId, initialState })` returns
|
|
23
|
+
a `Room` that owns a `Y.Doc` and an `Awareness` instance and routes
|
|
24
|
+
bytes between attached `Connection`s. The transport layer creates
|
|
25
|
+
one `Connection` per peer (a thin wrapper around a WebSocket / fetch
|
|
26
|
+
stream / postMessage channel) and calls `addConnection`,
|
|
27
|
+
`handleMessage`, and `removeConnection`. The room handles the sync
|
|
28
|
+
handshake, broadcast fan-out, and awareness propagation.
|
|
29
|
+
- **Persistence (`./persistence`).** A narrow `DocumentPersistence`
|
|
30
|
+
interface (`load` / `save`) plus `bindPersistence(room, persistence)`,
|
|
31
|
+
which debounces writes off the room's `update` event. A reference
|
|
32
|
+
in-memory implementation (`createMemoryPersistence`) ships in the box
|
|
33
|
+
and is used by the test suite.
|
|
34
|
+
|
|
35
|
+
## Quick start
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import {
|
|
39
|
+
createRoom,
|
|
40
|
+
bindPersistence,
|
|
41
|
+
createMemoryPersistence,
|
|
42
|
+
type Connection,
|
|
43
|
+
} from '@prenta/realtime'
|
|
44
|
+
|
|
45
|
+
const persistence = createMemoryPersistence()
|
|
46
|
+
|
|
47
|
+
// Bootstrap a room with whatever state we have on disk.
|
|
48
|
+
const initialState = (await persistence.load('doc-1')) ?? undefined
|
|
49
|
+
const room = createRoom({ documentId: 'doc-1', initialState })
|
|
50
|
+
const { flush, unbind } = bindPersistence(room, persistence)
|
|
51
|
+
|
|
52
|
+
// In your WebSocket onConnection handler:
|
|
53
|
+
const conn: Connection = {
|
|
54
|
+
id: socketId,
|
|
55
|
+
send: (bytes) => socket.send(bytes),
|
|
56
|
+
close: () => socket.close(),
|
|
57
|
+
}
|
|
58
|
+
room.addConnection(conn)
|
|
59
|
+
socket.on('message', (bytes) => room.handleMessage(conn.id, bytes))
|
|
60
|
+
socket.on('close', () => room.removeConnection(conn.id))
|
|
61
|
+
|
|
62
|
+
// On graceful shutdown:
|
|
63
|
+
await flush()
|
|
64
|
+
unbind()
|
|
65
|
+
room.destroy()
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The room sends a `SyncStep1` immediately on `addConnection` and an
|
|
69
|
+
awareness snapshot if any peers are already present, so the client only
|
|
70
|
+
needs to reply with its own state — the standard y-websocket handshake.
|
|
71
|
+
|
|
72
|
+
## Persistence model
|
|
73
|
+
|
|
74
|
+
The companion Prisma model is named `DocumentCRDT` (see
|
|
75
|
+
`packages/cms-core/prisma/cms-schema.prisma`). The schema fragment lives
|
|
76
|
+
in cms-core so consumers wire it into a single migration. The shape:
|
|
77
|
+
|
|
78
|
+
| Field | Type | Purpose |
|
|
79
|
+
| ----------------- | -------- | ------------------------------------------------------ |
|
|
80
|
+
| `documentId` | String | PK — references `Document.id` at the app layer |
|
|
81
|
+
| `state` | Bytes | `Y.encodeStateAsUpdate(doc)` blob |
|
|
82
|
+
| `stateVector` | Bytes | `Y.encodeStateVector(doc)` — speeds up cold late joins |
|
|
83
|
+
| `version` | Int | Monotonic counter (optimistic locking) |
|
|
84
|
+
| `lastUpdatedAt` | DateTime | Wall-clock of most recent flush |
|
|
85
|
+
| `lastUpdatedById` | String? | Editor id if known |
|
|
86
|
+
| `createdAt` | DateTime | First-write timestamp |
|
|
87
|
+
|
|
88
|
+
`@prenta/realtime` is storage-agnostic — the cms-core layer
|
|
89
|
+
implements `DocumentPersistence` against Prisma, but you can plug
|
|
90
|
+
in S3, Redis, or anything else by implementing two methods.
|
|
91
|
+
|
|
92
|
+
## Wire-protocol compatibility
|
|
93
|
+
|
|
94
|
+
The envelope follows the standard y-websocket layout:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
[messageType: varUint][payload: bytes]
|
|
98
|
+
|
|
99
|
+
messageType 0 → MESSAGE_SYNC (y-protocols sync sub-message)
|
|
100
|
+
messageType 1 → MESSAGE_AWARENESS (varUint8Array awareness update)
|
|
101
|
+
messageType 3 → MESSAGE_QUERY_AWARENESS (no payload; reply with snapshot)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Keeping this stable means any client that already speaks y-websocket
|
|
105
|
+
(e.g. browsers using `@tiptap/extension-collaboration` with the default
|
|
106
|
+
provider) can connect to the Prenta realtime endpoint without custom
|
|
107
|
+
client-side code.
|
|
108
|
+
|
|
109
|
+
## Test coverage
|
|
110
|
+
|
|
111
|
+
42 unit tests across four files:
|
|
112
|
+
|
|
113
|
+
| File | Coverage |
|
|
114
|
+
| ------------------ | ----------------------------------------------------------------- |
|
|
115
|
+
| `protocol.test` | envelope shape, sync roundtrip, awareness, query, malformed input |
|
|
116
|
+
| `room.test` | handshake, two-client convergence, disconnect, awareness fan-out |
|
|
117
|
+
| `persistence.test` | debounce, flush, error handling, round trip with the memory impl |
|
|
118
|
+
| `index.test` | barrel exports, constant stability |
|
|
119
|
+
|
|
120
|
+
Run them with `pnpm --filter @prenta/realtime test`.
|
|
121
|
+
|
|
122
|
+
## Status
|
|
123
|
+
|
|
124
|
+
- **Slice 1 (this package, foundation)** — ✅ shipped.
|
|
125
|
+
- **Slice 2 (cms-core WebSocket gateway + Prisma adapter)** — ✅ shipped.
|
|
126
|
+
See `@prenta/core/realtime` for the consumer-facing
|
|
127
|
+
`createRealtimeGateway` and `createPrismaDocumentPersistence` helpers.
|
|
128
|
+
- **Slice 3 (admin TipTap collaboration extension)** — ✅ shipped.
|
|
129
|
+
See `@prenta/admin` — `createCollaborationProvider`,
|
|
130
|
+
`<PresenceChips />`, and the `collaboration` prop on `<TipTapEditor />`.
|
|
131
|
+
- **Slice 4 (`DocumentComment` model + REST endpoints)** — ✅ shipped.
|
|
132
|
+
See `@prenta/core/realtime` for the service helpers
|
|
133
|
+
(`createComment`, `listComments`, `resolveComment`, …) and the HTTP
|
|
134
|
+
endpoints under `/api/cms/documents/:id/comments` and
|
|
135
|
+
`/api/cms/comments/:id`.
|
|
136
|
+
- **Slice 5 (comments side panel + anchor binding in admin)** — ✅ shipped.
|
|
137
|
+
See `@prenta/admin` — the `comments` prop on `<TipTapEditor />`,
|
|
138
|
+
the `CommentSidePanel` component, the `CommentMark` TipTap mark, and
|
|
139
|
+
the anchor helpers in `lib/comment-anchor.ts`.
|
|
140
|
+
- **Slice 6 (offline drafts + notifications)** — ✅ shipped.
|
|
141
|
+
See `@prenta/admin` — `<OfflineStatus />`, the `offline`
|
|
142
|
+
flag on `createCollaborationProvider`, and `<NotificationBell />`.
|
|
143
|
+
Server side: `DocumentNotification` Prisma model + REST endpoints
|
|
144
|
+
under `/api/cms/notifications` in `@prenta/core`.
|
|
145
|
+
|
|
146
|
+
## Wiring the gateway (slice 2 cheat sheet)
|
|
147
|
+
|
|
148
|
+
The cms-core gateway is transport-agnostic — it takes a `WebSocketLike`
|
|
149
|
+
adapter so it works with `ws`, `uWebSockets.js`, Bun, Cloudflare Workers,
|
|
150
|
+
or anything else. A minimal `ws` integration looks like this:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
import { createServer } from 'node:http'
|
|
154
|
+
import { WebSocketServer } from 'ws'
|
|
155
|
+
import {
|
|
156
|
+
createRealtimeGateway,
|
|
157
|
+
createPrismaDocumentPersistence,
|
|
158
|
+
type WebSocketLike,
|
|
159
|
+
} from '@prenta/core/realtime'
|
|
160
|
+
|
|
161
|
+
const httpServer = createServer()
|
|
162
|
+
const wss = new WebSocketServer({ noServer: true })
|
|
163
|
+
|
|
164
|
+
const gateway = createRealtimeGateway({
|
|
165
|
+
persistence: createPrismaDocumentPersistence(prisma),
|
|
166
|
+
authenticate: async (req) => {
|
|
167
|
+
const session = await verifySessionFromHeaders(req.headers)
|
|
168
|
+
if (!session) return null
|
|
169
|
+
const url = new URL(`http://x${req.url}`)
|
|
170
|
+
return {
|
|
171
|
+
documentId: url.searchParams.get('documentId')!,
|
|
172
|
+
connectionId: req.headers['sec-websocket-key']!,
|
|
173
|
+
userId: session.userId,
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
httpServer.on('upgrade', (req, socket, head) => {
|
|
179
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
180
|
+
const adapter: WebSocketLike = {
|
|
181
|
+
send: (d) => ws.send(d),
|
|
182
|
+
close: (code, reason) => ws.close(code, reason),
|
|
183
|
+
on: (event, handler) => {
|
|
184
|
+
if (event === 'message')
|
|
185
|
+
ws.on('message', (d: Buffer) => (handler as (b: Uint8Array) => void)(new Uint8Array(d)))
|
|
186
|
+
else if (event === 'close') ws.on('close', () => (handler as () => void)())
|
|
187
|
+
else if (event === 'error') ws.on('error', (e: Error) => (handler as (e: Error) => void)(e))
|
|
188
|
+
},
|
|
189
|
+
}
|
|
190
|
+
void gateway.handleConnection(adapter, {
|
|
191
|
+
url: req.url ?? '/',
|
|
192
|
+
headers: req.headers as Record<string, string | undefined>,
|
|
193
|
+
})
|
|
194
|
+
})
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
process.on('SIGTERM', () => {
|
|
198
|
+
void gateway.shutdown()
|
|
199
|
+
})
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
The gateway handles per-document room creation, debounced persistence,
|
|
203
|
+
idle reaping, and graceful shutdown automatically.
|
|
204
|
+
|
|
205
|
+
## Wiring the editor (slice 3 cheat sheet)
|
|
206
|
+
|
|
207
|
+
The admin editor accepts an optional `collaboration` prop. When set, the
|
|
208
|
+
`TipTapEditor` swaps StarterKit's history for the Yjs-driven history,
|
|
209
|
+
mounts the collaboration + collaboration-cursor extensions, and renders
|
|
210
|
+
`<PresenceChips />` above the toolbar.
|
|
211
|
+
|
|
212
|
+
```tsx
|
|
213
|
+
import { TipTapEditor } from '@prenta/admin/components/TipTapEditor'
|
|
214
|
+
;<TipTapEditor
|
|
215
|
+
content={initialHtml}
|
|
216
|
+
onChange={() => {
|
|
217
|
+
/* still fires for autosave; gateway is source of truth */
|
|
218
|
+
}}
|
|
219
|
+
collaboration={{
|
|
220
|
+
documentId: doc.id,
|
|
221
|
+
url: 'wss://your.app/api/cms/realtime/sync',
|
|
222
|
+
user: { id: currentUser.id, name: currentUser.name, color: '#22c55e' },
|
|
223
|
+
// Optional: extra query params (e.g. auth tokens for cross-origin deploys).
|
|
224
|
+
params: { token: previewToken },
|
|
225
|
+
}}
|
|
226
|
+
/>
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Behind the scenes:
|
|
230
|
+
|
|
231
|
+
1. `createCollaborationProvider({ documentId, url, user })` builds a
|
|
232
|
+
`Y.Doc`, opens a `WebsocketProvider`, and seeds `Awareness.localState`
|
|
233
|
+
with the user info.
|
|
234
|
+
2. The editor wires `Collaboration.configure({ document })` and
|
|
235
|
+
`CollaborationCursor.configure({ provider, user })`, and disables
|
|
236
|
+
StarterKit's history (Yjs owns undo/redo when collaboration is active).
|
|
237
|
+
3. `PresenceChips` subscribes to the awareness instance and renders an
|
|
238
|
+
avatar strip with overflow + connection status.
|
|
239
|
+
|
|
240
|
+
The provider exposes `status` (`connecting | connected | disconnected`)
|
|
241
|
+
and lifecycle callbacks (`onStatusChange`, `onError`) so callers can
|
|
242
|
+
surface their own connection chrome if needed.
|
|
243
|
+
|
|
244
|
+
## Comments REST API (slice 4 cheat sheet)
|
|
245
|
+
|
|
246
|
+
Comments live in a separate REST surface (not the Yjs wire) so plugins,
|
|
247
|
+
mobile clients, and notification workers can consume them without
|
|
248
|
+
speaking the CRDT protocol. The Prisma model is `DocumentComment`
|
|
249
|
+
(threaded, anchored, soft-deletable); the service helpers in
|
|
250
|
+
`@prenta/core/realtime` own validation and permissions, and
|
|
251
|
+
the HTTP handlers in `cms-core` map those to status codes.
|
|
252
|
+
|
|
253
|
+
### Endpoints (under `/api/cms`)
|
|
254
|
+
|
|
255
|
+
| Method | Path | Purpose | Auth |
|
|
256
|
+
| ------ | --------------------------------- | ---------------------------------------- | ------------------- |
|
|
257
|
+
| POST | `/documents/:documentId/comments` | Create a top-level comment or a reply | write role |
|
|
258
|
+
| GET | `/documents/:documentId/comments` | List active comments (filters available) | any auth |
|
|
259
|
+
| PATCH | `/comments/:id` | Edit a comment body | author or admin |
|
|
260
|
+
| POST | `/comments/:id/resolve` | Mark a thread as resolved | write role / author |
|
|
261
|
+
| POST | `/comments/:id/reopen` | Re-open a resolved thread | write role / author |
|
|
262
|
+
| DELETE | `/comments/:id` | Soft-delete a comment | author or admin |
|
|
263
|
+
|
|
264
|
+
GET supports `?includeResolved=true` (anyone) and `?includeDeleted=true`
|
|
265
|
+
(admin only). Responses are always envelope `{ data: CommentDTO }` or
|
|
266
|
+
`{ data: CommentDTO[] }`; errors map cleanly: 400 (validation), 403
|
|
267
|
+
(forbidden), 404 (not found), 409 (conflict).
|
|
268
|
+
|
|
269
|
+
### Anchor format
|
|
270
|
+
|
|
271
|
+
The `anchor` field is opaque to the API. The client encodes a pair of
|
|
272
|
+
Yjs relative positions with `Y.encodeRelativePosition(...)` and Base64s
|
|
273
|
+
each side:
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import * as Y from 'yjs'
|
|
277
|
+
|
|
278
|
+
function makeAnchor(doc: Y.Doc, from: number, to: number) {
|
|
279
|
+
const type = doc.getXmlFragment('default') // or whichever ytype your editor binds to
|
|
280
|
+
const relFrom = Y.createRelativePositionFromTypeIndex(type, from)
|
|
281
|
+
const relTo = Y.createRelativePositionFromTypeIndex(type, to)
|
|
282
|
+
return {
|
|
283
|
+
from: Buffer.from(Y.encodeRelativePosition(relFrom)).toString('base64'),
|
|
284
|
+
to: Buffer.from(Y.encodeRelativePosition(relTo)).toString('base64'),
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Slice 5 reverses the operation in the comments side panel to paint
|
|
290
|
+
live highlights that survive concurrent edits — see the next section.
|
|
291
|
+
|
|
292
|
+
### Service layer (server-side)
|
|
293
|
+
|
|
294
|
+
Apps that need to manage comments outside the HTTP layer (e.g. a
|
|
295
|
+
background worker that emits notifications on resolve) can call the
|
|
296
|
+
service helpers directly:
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
import { createComment, resolveComment, type CommentsDB } from '@prenta/core/realtime'
|
|
300
|
+
|
|
301
|
+
const db: CommentsDB = prisma // PrismaClient satisfies the narrow type
|
|
302
|
+
const created = await createComment(db, {
|
|
303
|
+
documentId: 'doc-1',
|
|
304
|
+
userId: 'user-1',
|
|
305
|
+
body: 'Looks great!',
|
|
306
|
+
})
|
|
307
|
+
if (!created.ok) throw new Error(created.error.message)
|
|
308
|
+
|
|
309
|
+
await resolveComment(db, created.value.id, {
|
|
310
|
+
userId: 'editor-1',
|
|
311
|
+
canResolve: true,
|
|
312
|
+
})
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
The service is intentionally storage-agnostic — `CommentsDB` is the
|
|
316
|
+
exact subset of Prisma we use, so tests can substitute an in-memory
|
|
317
|
+
fake (see `comments.test.ts`).
|
|
318
|
+
|
|
319
|
+
## Comments side panel (slice 5 cheat sheet)
|
|
320
|
+
|
|
321
|
+
Slice 5 layers a typed REST client, anchor helpers, a TipTap mark, and
|
|
322
|
+
a side-panel React component on top of slice 4 so editors can comment
|
|
323
|
+
on selections directly inside the admin.
|
|
324
|
+
|
|
325
|
+
```tsx
|
|
326
|
+
import { TipTapEditor } from '@prenta/admin/components/TipTapEditor'
|
|
327
|
+
;<TipTapEditor
|
|
328
|
+
content={initialHtml}
|
|
329
|
+
onChange={onAutoSave}
|
|
330
|
+
collaboration={{
|
|
331
|
+
documentId: doc.id,
|
|
332
|
+
url: 'wss://your.app/api/cms/realtime/sync',
|
|
333
|
+
user: { id: currentUser.id, name: currentUser.name, color: '#22c55e' },
|
|
334
|
+
}}
|
|
335
|
+
comments={{
|
|
336
|
+
documentId: doc.id,
|
|
337
|
+
currentUserId: currentUser.id,
|
|
338
|
+
isAdmin: currentUser.role === 'ADMIN',
|
|
339
|
+
onError: (msg) => toast.error(msg),
|
|
340
|
+
}}
|
|
341
|
+
/>
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
The editor reacts to the `comments` prop by:
|
|
345
|
+
|
|
346
|
+
1. Loading the `CommentMark` extension so saved comment ranges are
|
|
347
|
+
highlighted in the document (yellow band on hover, dotted underline
|
|
348
|
+
when resolved, outlined when the panel selects them).
|
|
349
|
+
2. Mounting `<CommentSidePanel />` next to the editor pane. The panel
|
|
350
|
+
talks to the slice-4 REST API through `lib/comments-client.ts` and
|
|
351
|
+
shows threads, replies, edit/resolve/delete affordances, and an
|
|
352
|
+
includes-resolved toggle.
|
|
353
|
+
3. Encoding the active editor selection into a CRDT-relative anchor
|
|
354
|
+
when "Comment" is submitted, so the highlight survives concurrent
|
|
355
|
+
edits. Multi-paragraph selections fall back to a doc-level comment
|
|
356
|
+
(anchor `null`).
|
|
357
|
+
|
|
358
|
+
### Composing anchors manually
|
|
359
|
+
|
|
360
|
+
`lib/comment-anchor.ts` is the single place that interprets the wire
|
|
361
|
+
format. Consumers building their own UI can use it directly:
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
import * as Y from 'yjs'
|
|
365
|
+
import { encodeAnchor, decodeAnchor } from '@prenta/admin/lib/comment-anchor'
|
|
366
|
+
|
|
367
|
+
const yText = paragraph.firstChild as Y.XmlText
|
|
368
|
+
const anchor = encodeAnchor({ doc, yType: yText, from: 6, to: 11 })
|
|
369
|
+
// → POST /documents/:id/comments { anchor }
|
|
370
|
+
|
|
371
|
+
// Later, after sync:
|
|
372
|
+
const resolved = decodeAnchor({ doc, anchor })
|
|
373
|
+
// → { yType, from, to } or null when the anchored text was deleted.
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
### Driving the panel from a custom shell
|
|
377
|
+
|
|
378
|
+
`<CommentSidePanel />` is exported standalone — the editor wires it
|
|
379
|
+
through the `comments` prop for convenience, but a different host shell
|
|
380
|
+
(e.g. an inbox-style review queue) can render the same component:
|
|
381
|
+
|
|
382
|
+
```tsx
|
|
383
|
+
import { CommentSidePanel } from '@prenta/admin/components/CommentSidePanel'
|
|
384
|
+
;<CommentSidePanel
|
|
385
|
+
documentId={doc.id}
|
|
386
|
+
currentUserId={user.id}
|
|
387
|
+
isAdmin={user.role === 'ADMIN'}
|
|
388
|
+
onComposeAnchor={() => null /* doc-level only */}
|
|
389
|
+
onError={notify}
|
|
390
|
+
/>
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
All actions (create, reply, edit, resolve / reopen, delete) flow
|
|
394
|
+
through the same `cmsApi` client that powers the rest of the admin, so
|
|
395
|
+
CSRF tokens, locale headers, and credential handling are inherited
|
|
396
|
+
without extra wiring.
|
|
397
|
+
|
|
398
|
+
## Offline drafts + notifications (slice 6 cheat sheet)
|
|
399
|
+
|
|
400
|
+
Slice 6 closes Phase 3 with two ergonomics features that ride on top of
|
|
401
|
+
slices 3-5: per-browser offline drafts via IndexedDB, and a top-bar
|
|
402
|
+
notification bell that reacts to comment events.
|
|
403
|
+
|
|
404
|
+
### Offline drafts
|
|
405
|
+
|
|
406
|
+
Opt-in via the new `offline` flag on `createCollaborationProvider` (or
|
|
407
|
+
the `collaboration.offline` shape on `<TipTapEditor />`):
|
|
408
|
+
|
|
409
|
+
```ts
|
|
410
|
+
import { createCollaborationProvider } from '@prenta/admin/lib/collaboration-provider'
|
|
411
|
+
|
|
412
|
+
const collab = createCollaborationProvider({
|
|
413
|
+
documentId: doc.id,
|
|
414
|
+
url: 'wss://your.app/api/cms/realtime/sync',
|
|
415
|
+
user: { id: currentUser.id, name: currentUser.name, color: '#22c55e' },
|
|
416
|
+
offline: true,
|
|
417
|
+
onOfflineStatus: (status) => {
|
|
418
|
+
// 'unsupported' | 'loading' | 'ready' | 'error' | 'pending'
|
|
419
|
+
},
|
|
420
|
+
})
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
The provider lazy-loads `y-indexeddb` (so the dependency stays out of
|
|
424
|
+
the bundle when offline drafts are disabled), seeds the local doc from
|
|
425
|
+
the IndexedDB snapshot before the socket opens, and writes every Yjs
|
|
426
|
+
update through to disk. On reconnect the y-websocket transport flushes
|
|
427
|
+
the pending operations and the in-memory doc stays authoritative.
|
|
428
|
+
|
|
429
|
+
`<OfflineStatus connection={status} offline={offlineStatus} />` renders
|
|
430
|
+
the merged state as a single pill — "Saved & synced", "Saved
|
|
431
|
+
locally — reconnecting…", or "Local drafts failed". The editor mounts
|
|
432
|
+
it next to the presence chips automatically when `collaboration` is
|
|
433
|
+
set.
|
|
434
|
+
|
|
435
|
+
### Notification bell
|
|
436
|
+
|
|
437
|
+
Server side, a new `DocumentNotification` Prisma model captures
|
|
438
|
+
per-user events (`comment_reply`, `comment_resolved`, `comment_mention`).
|
|
439
|
+
The comments lifecycle hooks fan out into notifications:
|
|
440
|
+
|
|
441
|
+
- Replying to a comment notifies the **root author** unless the
|
|
442
|
+
replier authored the root.
|
|
443
|
+
- Resolving a comment notifies the **root author** unless the resolver
|
|
444
|
+
authored the root.
|
|
445
|
+
- `@mentions` (currently parsed from comment bodies as `@user-id`) emit
|
|
446
|
+
a `comment_mention` row.
|
|
447
|
+
|
|
448
|
+
The REST surface (under `/api/cms`):
|
|
449
|
+
|
|
450
|
+
| Method | Path | Purpose | Auth |
|
|
451
|
+
| ------ | ----------------------------- | -------------------------- | -------- |
|
|
452
|
+
| GET | `/notifications` | List the caller's rows | any auth |
|
|
453
|
+
| GET | `/notifications/unread-count` | Cheap badge counter | any auth |
|
|
454
|
+
| POST | `/notifications/:id/read` | Mark one notification read | owner |
|
|
455
|
+
| POST | `/notifications/read-all` | Mark every unread row read | any auth |
|
|
456
|
+
|
|
457
|
+
Client side, drop `<NotificationBell />` into the admin top bar:
|
|
458
|
+
|
|
459
|
+
```tsx
|
|
460
|
+
import { NotificationBell } from '@prenta/admin'
|
|
461
|
+
;<NotificationBell
|
|
462
|
+
onSelect={(notification) => navigateToDocument(notification.documentId)}
|
|
463
|
+
onError={(msg) => toast.error(msg)}
|
|
464
|
+
/>
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
The bell polls `/notifications/unread-count` every 30s by default
|
|
468
|
+
(`pollIntervalMs={0}` disables polling) and re-fetches the full list
|
|
469
|
+
when the dropdown opens. Clicks are optimistically marked read with
|
|
470
|
+
automatic rollback on server failures.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public API for `@prenta/realtime`.
|
|
3
|
+
*
|
|
4
|
+
* Three layers, each independently usable:
|
|
5
|
+
*
|
|
6
|
+
* - **Protocol** (`./protocol`) — pure encode/decode of the wire envelope
|
|
7
|
+
* (binary-compatible with `y-websocket`).
|
|
8
|
+
* - **Room** (`./room`) — transport-agnostic Yjs collaboration session: owns
|
|
9
|
+
* a `Y.Doc` and an `Awareness`, routes inbound bytes, broadcasts outbound.
|
|
10
|
+
* - **Persistence** (`./persistence`) — narrow storage adapter contract plus
|
|
11
|
+
* a `bindPersistence` helper that debounces writes off a `Room`.
|
|
12
|
+
*
|
|
13
|
+
* Cms-core wires these into the `/realtime/sync` WebSocket endpoint; the
|
|
14
|
+
* admin TipTap collaboration extension talks the standard y-websocket
|
|
15
|
+
* protocol so it works against this server out of the box.
|
|
16
|
+
*/
|
|
17
|
+
export { Awareness, encodeAwarenessUpdate, encodeQueryAwareness, encodeSyncStep1, encodeSyncStep2, encodeUpdateMessage, MESSAGE_AWARENESS, MESSAGE_QUERY_AWARENESS, MESSAGE_SYNC, readMessage, type MessageType, type ReadResult, } from './protocol.js';
|
|
18
|
+
export { createRoom, removeAwarenessClients, ROOM_DESTROY_ORIGIN, ROOM_FORCE_LEAVE_ORIGIN, ROOM_INIT_ORIGIN, type Connection, type Room, type RoomOptions, } from './room.js';
|
|
19
|
+
export { bindPersistence, createMemoryPersistence, type DocumentPersistence, type PersistenceBindOptions, type TimerImpl, } from './persistence.js';
|
|
20
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EACL,SAAS,EACT,qBAAqB,EACrB,oBAAoB,EACpB,eAAe,EACf,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,EACvB,YAAY,EACZ,WAAW,EACX,KAAK,WAAW,EAChB,KAAK,UAAU,GAChB,MAAM,eAAe,CAAA;AAEtB,OAAO,EACL,UAAU,EACV,sBAAsB,EACtB,mBAAmB,EACnB,uBAAuB,EACvB,gBAAgB,EAChB,KAAK,UAAU,EACf,KAAK,IAAI,EACT,KAAK,WAAW,GACjB,MAAM,WAAW,CAAA;AAElB,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,KAAK,SAAS,GACf,MAAM,kBAAkB,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public API for `@prenta/realtime`.
|
|
3
|
+
*
|
|
4
|
+
* Three layers, each independently usable:
|
|
5
|
+
*
|
|
6
|
+
* - **Protocol** (`./protocol`) — pure encode/decode of the wire envelope
|
|
7
|
+
* (binary-compatible with `y-websocket`).
|
|
8
|
+
* - **Room** (`./room`) — transport-agnostic Yjs collaboration session: owns
|
|
9
|
+
* a `Y.Doc` and an `Awareness`, routes inbound bytes, broadcasts outbound.
|
|
10
|
+
* - **Persistence** (`./persistence`) — narrow storage adapter contract plus
|
|
11
|
+
* a `bindPersistence` helper that debounces writes off a `Room`.
|
|
12
|
+
*
|
|
13
|
+
* Cms-core wires these into the `/realtime/sync` WebSocket endpoint; the
|
|
14
|
+
* admin TipTap collaboration extension talks the standard y-websocket
|
|
15
|
+
* protocol so it works against this server out of the box.
|
|
16
|
+
*/
|
|
17
|
+
export { Awareness, encodeAwarenessUpdate, encodeQueryAwareness, encodeSyncStep1, encodeSyncStep2, encodeUpdateMessage, MESSAGE_AWARENESS, MESSAGE_QUERY_AWARENESS, MESSAGE_SYNC, readMessage, } from './protocol.js';
|
|
18
|
+
export { createRoom, removeAwarenessClients, ROOM_DESTROY_ORIGIN, ROOM_FORCE_LEAVE_ORIGIN, ROOM_INIT_ORIGIN, } from './room.js';
|
|
19
|
+
export { bindPersistence, createMemoryPersistence, } from './persistence.js';
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EACL,SAAS,EACT,qBAAqB,EACrB,oBAAoB,EACpB,eAAe,EACf,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,EACvB,YAAY,EACZ,WAAW,GAGZ,MAAM,eAAe,CAAA;AAEtB,OAAO,EACL,UAAU,EACV,sBAAsB,EACtB,mBAAmB,EACnB,uBAAuB,EACvB,gBAAgB,GAIjB,MAAM,WAAW,CAAA;AAElB,OAAO,EACL,eAAe,EACf,uBAAuB,GAIxB,MAAM,kBAAkB,CAAA"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Room } from './room.js';
|
|
2
|
+
/** Storage adapter for room state. */
|
|
3
|
+
export interface DocumentPersistence {
|
|
4
|
+
/**
|
|
5
|
+
* Return the encoded Yjs state for `documentId`, or `null` if none yet.
|
|
6
|
+
* The bytes are produced by `Y.encodeStateAsUpdate(doc)`.
|
|
7
|
+
*/
|
|
8
|
+
load(documentId: string): Promise<Uint8Array | null>;
|
|
9
|
+
/** Replace the encoded state for `documentId`. */
|
|
10
|
+
save(documentId: string, state: Uint8Array): Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
export interface PersistenceBindOptions {
|
|
13
|
+
/** Coalesce writes that arrive within this window (ms). Default: 1000. */
|
|
14
|
+
debounceMs?: number;
|
|
15
|
+
/** Maximum time to wait before flushing (ms). Prevents starvation. Default: 5000. */
|
|
16
|
+
maxIdleMs?: number;
|
|
17
|
+
/** Called when `persistence.save` rejects. Defaults to a console.error. */
|
|
18
|
+
onError?: (err: unknown) => void;
|
|
19
|
+
/** Provide a custom timer (for tests). Defaults to `setTimeout` / `clearTimeout`. */
|
|
20
|
+
timer?: TimerImpl;
|
|
21
|
+
}
|
|
22
|
+
export interface TimerImpl {
|
|
23
|
+
setTimeout(handler: () => void, ms: number): unknown;
|
|
24
|
+
clearTimeout(handle: unknown): void;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Bind a `DocumentPersistence` to a `Room`. Returns a `flush` function that
|
|
28
|
+
* writes any pending state immediately (e.g. on graceful shutdown). The
|
|
29
|
+
* binding listens for Yjs `update` events on the room's doc and debounces
|
|
30
|
+
* writes to avoid hot loops during typing.
|
|
31
|
+
*
|
|
32
|
+
* The caller is responsible for tearing the binding down — pair `bindPersistence`
|
|
33
|
+
* with a `room.destroy()` and a final `await flush()`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function bindPersistence(room: Room, persistence: DocumentPersistence, opts?: PersistenceBindOptions): {
|
|
36
|
+
flush: () => Promise<void>;
|
|
37
|
+
unbind: () => void;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Reference implementation backed by an in-memory `Map`. Useful for tests
|
|
41
|
+
* and for transports that don't need durable persistence. Stores a copy of
|
|
42
|
+
* the bytes (callers may mutate the original buffer after save).
|
|
43
|
+
*/
|
|
44
|
+
export declare function createMemoryPersistence(initial?: Record<string, Uint8Array>): DocumentPersistence;
|
|
45
|
+
//# sourceMappingURL=persistence.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"persistence.d.ts","sourceRoot":"","sources":["../src/persistence.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAErC,sCAAsC;AACtC,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAA;IACpD,kDAAkD;IAClD,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC3D;AAED,MAAM,WAAW,sBAAsB;IACrC,0EAA0E;IAC1E,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,qFAAqF;IACrF,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,2EAA2E;IAC3E,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAA;IAChC,qFAAqF;IACrF,KAAK,CAAC,EAAE,SAAS,CAAA;CAClB;AAED,MAAM,WAAW,SAAS;IACxB,UAAU,CAAC,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAA;IACpD,YAAY,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI,CAAA;CACpC;AAOD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,IAAI,EACV,WAAW,EAAE,mBAAmB,EAChC,IAAI,GAAE,sBAA2B,GAChC;IAAE,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,MAAM,EAAE,MAAM,IAAI,CAAA;CAAE,CAiEpD;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,mBAAmB,CAgBjG"}
|