@alecsibilia/ui-kit 0.0.0-stage → 0.1.0-alpha.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 +7 -0
- package/LICENSE +201 -0
- package/README.md +233 -2
- package/bin/ui-kit.js +12 -0
- package/dist/alchemy/app.d.ts +34 -0
- package/dist/alchemy/app.js +88 -0
- package/dist/alchemy/index.d.ts +11 -0
- package/dist/alchemy/index.js +11 -0
- package/dist/alchemy/live-rooms.d.ts +21 -0
- package/dist/alchemy/live-rooms.js +31 -0
- package/dist/alchemy/migrations.d.ts +28 -0
- package/dist/alchemy/migrations.js +56 -0
- package/dist/alchemy/stage.d.ts +20 -0
- package/dist/alchemy/stage.js +20 -0
- package/dist/alchemy/wrangler-config.d.ts +76 -0
- package/dist/alchemy/wrangler-config.js +82 -0
- package/dist/build/app-modules.d.ts +11 -0
- package/dist/build/app-modules.js +40 -0
- package/dist/build/check.d.ts +4 -0
- package/dist/build/check.js +170 -0
- package/dist/build/cli.d.ts +1 -0
- package/dist/build/cli.js +79 -0
- package/dist/build/feature.d.ts +8 -0
- package/dist/build/feature.js +24 -0
- package/dist/build/index.d.ts +13 -0
- package/dist/build/index.js +13 -0
- package/dist/build/measure-cpu.d.ts +2 -0
- package/dist/build/measure-cpu.js +196 -0
- package/dist/build/prerender.d.ts +5 -0
- package/dist/build/prerender.js +109 -0
- package/dist/build/preview.d.ts +7 -0
- package/dist/build/preview.js +41 -0
- package/dist/build/seo-files.d.ts +27 -0
- package/dist/build/seo-files.js +24 -0
- package/dist/client/head-swap.d.ts +45 -0
- package/dist/client/head-swap.js +183 -0
- package/dist/client/hydration-pass.d.ts +56 -0
- package/dist/client/hydration-pass.js +186 -0
- package/dist/client/hydration-reset.d.ts +82 -0
- package/dist/client/hydration-reset.js +154 -0
- package/dist/client/index.d.ts +37 -0
- package/dist/client/index.js +65 -0
- package/dist/client/nav-client.d.ts +35 -0
- package/dist/client/nav-client.js +371 -0
- package/dist/live/collab/doc-provider.d.ts +74 -0
- package/dist/live/collab/doc-provider.js +412 -0
- package/dist/live/collab/index.d.ts +51 -0
- package/dist/live/collab/index.jsx +142 -0
- package/dist/live/collab-status.d.ts +25 -0
- package/dist/live/collab-status.js +17 -0
- package/dist/live/cursors/cursor-engine.d.ts +57 -0
- package/dist/live/cursors/cursor-engine.js +243 -0
- package/dist/live/cursors/index.d.ts +46 -0
- package/dist/live/cursors/index.jsx +110 -0
- package/dist/live/declaration.d.ts +113 -0
- package/dist/live/declaration.js +94 -0
- package/dist/live/index.d.ts +8 -0
- package/dist/live/index.js +8 -0
- package/dist/live/protocol.d.ts +224 -0
- package/dist/live/protocol.js +272 -0
- package/dist/live/server/doc-store.d.ts +68 -0
- package/dist/live/server/doc-store.js +187 -0
- package/dist/live/server/index.d.ts +60 -0
- package/dist/live/server/index.js +77 -0
- package/dist/live/server/room-presence.d.ts +24 -0
- package/dist/live/server/room-presence.js +123 -0
- package/dist/live/server/room-sockets.d.ts +65 -0
- package/dist/live/server/room-sockets.js +97 -0
- package/dist/live/server/room.d.ts +20 -0
- package/dist/live/server/room.js +348 -0
- package/dist/live/server/route.d.ts +56 -0
- package/dist/live/server/route.js +159 -0
- package/dist/live/server/types.d.ts +163 -0
- package/dist/live/server/types.js +2 -0
- package/dist/logic/agent-actions.d.ts +133 -0
- package/dist/logic/agent-actions.js +150 -0
- package/dist/logic/command-types.d.ts +53 -0
- package/dist/logic/command-types.js +0 -0
- package/dist/logic/dev.d.ts +9 -0
- package/dist/logic/dev.js +10 -0
- package/dist/logic/draft-rebase.d.ts +59 -0
- package/dist/logic/draft-rebase.js +71 -0
- package/dist/logic/form-state.d.ts +105 -0
- package/dist/logic/form-state.js +93 -0
- package/dist/logic/head.d.ts +145 -0
- package/dist/logic/head.js +140 -0
- package/dist/logic/index.d.ts +27 -0
- package/dist/logic/index.js +25 -0
- package/dist/logic/island-def.d.ts +89 -0
- package/dist/logic/island-def.js +59 -0
- package/dist/logic/kit-commands.d.ts +104 -0
- package/dist/logic/kit-commands.js +72 -0
- package/dist/logic/kit-errors.d.ts +25 -0
- package/dist/logic/kit-errors.js +6 -0
- package/dist/logic/listen.d.ts +99 -0
- package/dist/logic/listen.js +92 -0
- package/dist/logic/mutation-def.d.ts +65 -0
- package/dist/logic/mutation-def.js +43 -0
- package/dist/logic/navigation-data.d.ts +50 -0
- package/dist/logic/navigation-data.js +55 -0
- package/dist/logic/navigation-policy.d.ts +74 -0
- package/dist/logic/navigation-policy.js +127 -0
- package/dist/logic/page-model-def.d.ts +108 -0
- package/dist/logic/page-model-def.js +31 -0
- package/dist/logic/path.d.ts +31 -0
- package/dist/logic/path.js +48 -0
- package/dist/logic/query-def.d.ts +56 -0
- package/dist/logic/query-def.js +37 -0
- package/dist/logic/query-key.d.ts +24 -0
- package/dist/logic/query-key.js +35 -0
- package/dist/logic/query-types.d.ts +28 -0
- package/dist/logic/query-types.js +2 -0
- package/dist/logic/resources.d.ts +163 -0
- package/dist/logic/resources.js +62 -0
- package/dist/logic/result.d.ts +30 -0
- package/dist/logic/result.js +23 -0
- package/dist/logic/route-model.d.ts +139 -0
- package/dist/logic/route-model.js +207 -0
- package/dist/logic/route-params.d.ts +80 -0
- package/dist/logic/route-params.js +114 -0
- package/dist/logic/route-table.d.ts +308 -0
- package/dist/logic/route-table.js +206 -0
- package/dist/logic/seo.d.ts +61 -0
- package/dist/logic/seo.js +101 -0
- package/dist/logic/site.d.ts +12 -0
- package/dist/logic/site.js +0 -0
- package/dist/logic/subscriptions.d.ts +177 -0
- package/dist/logic/subscriptions.js +152 -0
- package/dist/render/index.d.ts +32 -0
- package/dist/render/index.js +52 -0
- package/dist/runtime/island-wake.d.ts +38 -0
- package/dist/runtime/island-wake.js +147 -0
- package/dist/runtime/query-scope.d.ts +224 -0
- package/dist/runtime/query-scope.js +222 -0
- package/dist/runtime/room-hub.d.ts +107 -0
- package/dist/runtime/room-hub.js +307 -0
- package/dist/runtime/subscription-runner.d.ts +71 -0
- package/dist/runtime/subscription-runner.js +240 -0
- package/dist/server/bindings.d.ts +41 -0
- package/dist/server/bindings.js +74 -0
- package/dist/server/browser.d.ts +9 -0
- package/dist/server/browser.js +9 -0
- package/dist/server/edge-cache.d.ts +28 -0
- package/dist/server/edge-cache.js +35 -0
- package/dist/server/errors.d.ts +45 -0
- package/dist/server/errors.js +36 -0
- package/dist/server/form-actions-setup.d.ts +1 -0
- package/dist/server/form-actions-setup.js +15 -0
- package/dist/server/form-actions.d.ts +121 -0
- package/dist/server/form-actions.js +211 -0
- package/dist/server/index.d.ts +36 -0
- package/dist/server/index.js +35 -0
- package/dist/server/inputs.d.ts +45 -0
- package/dist/server/inputs.js +77 -0
- package/dist/server/rate-limit.d.ts +29 -0
- package/dist/server/rate-limit.js +32 -0
- package/dist/server/read-cache.d.ts +74 -0
- package/dist/server/read-cache.js +58 -0
- package/dist/server/request-info.d.ts +17 -0
- package/dist/server/request-info.js +11 -0
- package/dist/server/request.d.ts +52 -0
- package/dist/server/request.js +73 -0
- package/dist/server/response-cookies.d.ts +23 -0
- package/dist/server/response-cookies.js +24 -0
- package/dist/server/run-effect.d.ts +42 -0
- package/dist/server/run-effect.js +92 -0
- package/dist/server/run.d.ts +63 -0
- package/dist/server/run.js +66 -0
- package/dist/server/session.d.ts +125 -0
- package/dist/server/session.js +247 -0
- package/dist/test/fake-bindings.d.ts +32 -0
- package/dist/test/fake-bindings.js +108 -0
- package/dist/test/fake-room.d.ts +66 -0
- package/dist/test/fake-room.js +216 -0
- package/dist/test/index.d.ts +19 -0
- package/dist/test/index.js +44 -0
- package/dist/test/probe.d.ts +11 -0
- package/dist/test/probe.js +11 -0
- package/dist/test/solid-jsx.d.ts +23 -0
- package/dist/test/solid-jsx.js +28 -0
- package/dist/test/solid-preload.d.ts +1 -0
- package/dist/test/solid-preload.js +29 -0
- package/dist/ui/code-editor/index.d.ts +21 -0
- package/dist/ui/code-editor/index.jsx +286 -0
- package/dist/ui/collab-text/index.d.ts +29 -0
- package/dist/ui/collab-text/index.jsx +96 -0
- package/dist/ui/components/controls.d.ts +69 -0
- package/dist/ui/components/controls.jsx +81 -0
- package/dist/ui/components/feedback.d.ts +26 -0
- package/dist/ui/components/feedback.jsx +80 -0
- package/dist/ui/components/layout.d.ts +74 -0
- package/dist/ui/components/layout.jsx +146 -0
- package/dist/ui/components/lists.d.ts +69 -0
- package/dist/ui/components/lists.jsx +133 -0
- package/dist/ui/components/navigation.d.ts +73 -0
- package/dist/ui/components/navigation.jsx +112 -0
- package/dist/ui/components/text.d.ts +34 -0
- package/dist/ui/components/text.jsx +163 -0
- package/dist/ui/index.d.ts +7 -0
- package/dist/ui/index.js +7 -0
- package/dist/ui/jsx-runtime.d.ts +19 -0
- package/dist/ui/jsx-runtime.js +0 -0
- package/dist/ui/list-keys.d.ts +31 -0
- package/dist/ui/list-keys.js +45 -0
- package/dist/ui/styles/base.css +38 -0
- package/dist/ui/styles/components.css +608 -0
- package/dist/ui/styles/tokens.css +27 -0
- package/dist/ui/styles/transitions.css +23 -0
- package/dist/ui/styles/workbench.css +428 -0
- package/dist/ui/styles.css +9 -0
- package/dist/view/agent-actions-view.d.ts +30 -0
- package/dist/view/agent-actions-view.js +27 -0
- package/dist/view/agent-surface.d.ts +42 -0
- package/dist/view/agent-surface.js +123 -0
- package/dist/view/app-scope.d.ts +51 -0
- package/dist/view/app-scope.js +75 -0
- package/dist/view/boundary.d.ts +18 -0
- package/dist/view/boundary.jsx +26 -0
- package/dist/view/command-runner.d.ts +16 -0
- package/dist/view/command-runner.js +245 -0
- package/dist/view/form.d.ts +82 -0
- package/dist/view/form.jsx +109 -0
- package/dist/view/head-view.d.ts +31 -0
- package/dist/view/head-view.js +46 -0
- package/dist/view/index.d.ts +41 -0
- package/dist/view/index.js +40 -0
- package/dist/view/island-root.d.ts +30 -0
- package/dist/view/island-root.js +36 -0
- package/dist/view/island.d.ts +102 -0
- package/dist/view/island.jsx +154 -0
- package/dist/view/match.d.ts +41 -0
- package/dist/view/match.js +111 -0
- package/dist/view/model.d.ts +92 -0
- package/dist/view/model.js +162 -0
- package/dist/view/navigation-head.d.ts +29 -0
- package/dist/view/navigation-head.jsx +38 -0
- package/dist/view/page-model.d.ts +46 -0
- package/dist/view/page-model.js +146 -0
- package/dist/view/query-effects.d.ts +87 -0
- package/dist/view/query-effects.js +147 -0
- package/dist/view/query-ok.d.ts +45 -0
- package/dist/view/query-ok.js +96 -0
- package/dist/view/query.d.ts +115 -0
- package/dist/view/query.jsx +179 -0
- package/dist/view/result-view.d.ts +14 -0
- package/dist/view/result-view.jsx +15 -0
- package/dist/view/route-pages.d.ts +43 -0
- package/dist/view/route-pages.js +59 -0
- package/dist/view/router.d.ts +44 -0
- package/dist/view/router.js +123 -0
- package/dist/vite/dev-middleware.d.ts +12 -0
- package/dist/vite/dev-middleware.js +39 -0
- package/dist/vite/dev-objects.d.ts +25 -0
- package/dist/vite/dev-objects.js +127 -0
- package/dist/vite/dev-platform.d.ts +19 -0
- package/dist/vite/dev-platform.js +77 -0
- package/dist/vite/dev-seo-files.d.ts +11 -0
- package/dist/vite/dev-seo-files.js +40 -0
- package/dist/vite/index.d.ts +53 -0
- package/dist/vite/index.js +148 -0
- package/dist/vite/local-config.d.ts +34 -0
- package/dist/vite/local-config.js +72 -0
- package/dist/vite/worker-build.d.ts +24 -0
- package/dist/vite/worker-build.js +84 -0
- package/dist/worker/create-worker.d.ts +52 -0
- package/dist/worker/create-worker.js +90 -0
- package/dist/worker/index.d.ts +12 -0
- package/dist/worker/index.js +12 -0
- package/dist/worker/page-routes.d.ts +88 -0
- package/dist/worker/page-routes.js +100 -0
- package/dist/worker/page-status.d.ts +41 -0
- package/dist/worker/page-status.js +23 -0
- package/dist/worker/request-prelude.d.ts +69 -0
- package/dist/worker/request-prelude.js +107 -0
- package/dist/worker/security.d.ts +76 -0
- package/dist/worker/security.js +137 -0
- package/dist/worker/server-app.d.ts +54 -0
- package/dist/worker/server-app.js +76 -0
- package/guards/browser-only.js +5 -0
- package/guards/node-only.js +6 -0
- package/guards/server-only.js +5 -0
- package/migrations/0001-sessions.sql +22 -0
- package/package.json +233 -5
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collaborative docs inside a room: Yjs documents kept in the room's own
|
|
3
|
+
* SQLite (an append-only update log per doc, compacted into one snapshot
|
|
4
|
+
* row), plus the y-websocket message helpers the room speaks.
|
|
5
|
+
*
|
|
6
|
+
* Tables are created on the first doc use, so a presence-only room writes
|
|
7
|
+
* nothing to storage at all.
|
|
8
|
+
*/
|
|
9
|
+
import * as decoding from 'lib0/decoding';
|
|
10
|
+
import * as encoding from 'lib0/encoding';
|
|
11
|
+
import * as authProtocol from 'y-protocols/auth';
|
|
12
|
+
import * as syncProtocol from 'y-protocols/sync';
|
|
13
|
+
import * as Y from 'yjs';
|
|
14
|
+
/** y-websocket message types. */
|
|
15
|
+
export const MESSAGE = {
|
|
16
|
+
SYNC: 0,
|
|
17
|
+
AWARENESS: 1,
|
|
18
|
+
AUTH: 2,
|
|
19
|
+
QUERY_AWARENESS: 3,
|
|
20
|
+
};
|
|
21
|
+
/** Compact a doc's log past this many rows. */
|
|
22
|
+
export const COMPACT_AFTER_ROWS = 200;
|
|
23
|
+
/** Default cap on a doc's stored bytes. */
|
|
24
|
+
export const DEFAULT_DOC_MAX_BYTES = 256 * 1024;
|
|
25
|
+
export function ensureTables(state) {
|
|
26
|
+
const sql = state.storage.sql;
|
|
27
|
+
sql.exec('CREATE TABLE IF NOT EXISTS live_doc_updates (seq INTEGER PRIMARY KEY AUTOINCREMENT, doc TEXT NOT NULL, data BLOB NOT NULL)');
|
|
28
|
+
sql.exec('CREATE INDEX IF NOT EXISTS live_doc_updates_doc ON live_doc_updates (doc, seq)');
|
|
29
|
+
sql.exec('CREATE TABLE IF NOT EXISTS live_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
|
|
30
|
+
}
|
|
31
|
+
function bytesOf(value) {
|
|
32
|
+
if (value instanceof Uint8Array)
|
|
33
|
+
return value;
|
|
34
|
+
return new Uint8Array(value);
|
|
35
|
+
}
|
|
36
|
+
/** Reads a doc's log into a fresh Y.Doc (no seed). */
|
|
37
|
+
export function readDoc(state, doc) {
|
|
38
|
+
const rows = state.storage.sql
|
|
39
|
+
.exec('SELECT data FROM live_doc_updates WHERE doc = ? ORDER BY seq', doc)
|
|
40
|
+
.toArray();
|
|
41
|
+
const ydoc = new Y.Doc();
|
|
42
|
+
let bytes = 0;
|
|
43
|
+
if (rows.length > 0) {
|
|
44
|
+
Y.transact(ydoc, () => {
|
|
45
|
+
for (const row of rows) {
|
|
46
|
+
const data = bytesOf(row.data);
|
|
47
|
+
bytes += data.byteLength;
|
|
48
|
+
Y.applyUpdate(ydoc, data);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return { ydoc, bytes, rows: rows.length };
|
|
53
|
+
}
|
|
54
|
+
/** Appends one update row. */
|
|
55
|
+
export function appendUpdate(state, loaded, doc, update) {
|
|
56
|
+
state.storage.sql.exec('INSERT INTO live_doc_updates (doc, data) VALUES (?, ?)', doc, update);
|
|
57
|
+
loaded.bytes += update.byteLength;
|
|
58
|
+
loaded.rows += 1;
|
|
59
|
+
}
|
|
60
|
+
/** Replaces a doc's log with one snapshot row when it has grown past {@link COMPACT_AFTER_ROWS}. */
|
|
61
|
+
export function maybeCompact(state, loaded, doc) {
|
|
62
|
+
if (loaded.rows <= COMPACT_AFTER_ROWS)
|
|
63
|
+
return;
|
|
64
|
+
const snapshot = Y.encodeStateAsUpdate(loaded.ydoc);
|
|
65
|
+
state.storage.transactionSync(() => {
|
|
66
|
+
state.storage.sql.exec('DELETE FROM live_doc_updates WHERE doc = ?', doc);
|
|
67
|
+
state.storage.sql.exec('INSERT INTO live_doc_updates (doc, data) VALUES (?, ?)', doc, snapshot);
|
|
68
|
+
});
|
|
69
|
+
loaded.bytes = snapshot.byteLength;
|
|
70
|
+
loaded.rows = 1;
|
|
71
|
+
}
|
|
72
|
+
export function readMeta(state, key) {
|
|
73
|
+
const rows = state.storage.sql
|
|
74
|
+
.exec('SELECT value FROM live_meta WHERE key = ?', key)
|
|
75
|
+
.toArray();
|
|
76
|
+
const value = rows[0]?.value;
|
|
77
|
+
return typeof value === 'string' ? value : undefined;
|
|
78
|
+
}
|
|
79
|
+
export function writeMeta(state, key, value) {
|
|
80
|
+
state.storage.sql.exec('INSERT INTO live_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value', key, value);
|
|
81
|
+
}
|
|
82
|
+
export function deleteMeta(state, key) {
|
|
83
|
+
state.storage.sql.exec('DELETE FROM live_meta WHERE key = ?', key);
|
|
84
|
+
}
|
|
85
|
+
/** Meta rows whose key starts with `prefix`. */
|
|
86
|
+
export function metaWithPrefix(state, prefix) {
|
|
87
|
+
return state.storage.sql
|
|
88
|
+
.exec('SELECT key, value FROM live_meta WHERE key >= ? AND key < ?', prefix, `${prefix}`)
|
|
89
|
+
.toArray()
|
|
90
|
+
.map((row) => ({ key: String(row.key), value: String(row.value) }));
|
|
91
|
+
}
|
|
92
|
+
/** The server's sync step 1 (the client answers with what the server lacks). */
|
|
93
|
+
export function syncStep1Frame(ydoc) {
|
|
94
|
+
const encoder = encoding.createEncoder();
|
|
95
|
+
encoding.writeVarUint(encoder, MESSAGE.SYNC);
|
|
96
|
+
syncProtocol.writeSyncStep1(encoder, ydoc);
|
|
97
|
+
return encoding.toUint8Array(encoder);
|
|
98
|
+
}
|
|
99
|
+
/** An update broadcast to the doc's other sockets. */
|
|
100
|
+
export function updateFrame(update) {
|
|
101
|
+
const encoder = encoding.createEncoder();
|
|
102
|
+
encoding.writeVarUint(encoder, MESSAGE.SYNC);
|
|
103
|
+
syncProtocol.writeUpdate(encoder, update);
|
|
104
|
+
return encoding.toUint8Array(encoder);
|
|
105
|
+
}
|
|
106
|
+
/** y-protocols' "permission denied" auth message (y-websocket logs it). */
|
|
107
|
+
export function permissionDeniedFrame(reason) {
|
|
108
|
+
const encoder = encoding.createEncoder();
|
|
109
|
+
encoding.writeVarUint(encoder, MESSAGE.AUTH);
|
|
110
|
+
authProtocol.writePermissionDenied(encoder, reason);
|
|
111
|
+
return encoding.toUint8Array(encoder);
|
|
112
|
+
}
|
|
113
|
+
/** Classifies a frame without applying it. */
|
|
114
|
+
export function classifyDocFrame(data) {
|
|
115
|
+
try {
|
|
116
|
+
const decoder = decoding.createDecoder(data);
|
|
117
|
+
const type = decoding.readVarUint(decoder);
|
|
118
|
+
if (type === MESSAGE.SYNC) {
|
|
119
|
+
return decoding.peekVarUint(decoder) ===
|
|
120
|
+
syncProtocol.messageYjsSyncStep1
|
|
121
|
+
? { _tag: 'SyncStep1' }
|
|
122
|
+
: { _tag: 'SyncWrite' };
|
|
123
|
+
}
|
|
124
|
+
if (type === MESSAGE.AWARENESS)
|
|
125
|
+
return {
|
|
126
|
+
_tag: 'Awareness',
|
|
127
|
+
update: decoding.readVarUint8Array(decoder),
|
|
128
|
+
};
|
|
129
|
+
if (type === MESSAGE.QUERY_AWARENESS)
|
|
130
|
+
return { _tag: 'QueryAwareness' };
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Truncated: unknown.
|
|
134
|
+
}
|
|
135
|
+
return { _tag: 'Unknown' };
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Applies a sync frame (step 1 answers with step 2; step 2 / update
|
|
139
|
+
* writes) with `origin` as the transaction origin. Returns the reply, if any.
|
|
140
|
+
*/
|
|
141
|
+
export function applySync(ydoc, data, origin) {
|
|
142
|
+
const decoder = decoding.createDecoder(data);
|
|
143
|
+
decoding.readVarUint(decoder);
|
|
144
|
+
const encoder = encoding.createEncoder();
|
|
145
|
+
encoding.writeVarUint(encoder, MESSAGE.SYNC);
|
|
146
|
+
syncProtocol.readSyncMessage(decoder, encoder, ydoc, origin);
|
|
147
|
+
return encoding.length(encoder) > 1
|
|
148
|
+
? encoding.toUint8Array(encoder)
|
|
149
|
+
: undefined;
|
|
150
|
+
}
|
|
151
|
+
/** Most awareness client ids one socket may announce (the attachment is ≤ 2 KB). */
|
|
152
|
+
export const MAX_AWARENESS_IDS = 8;
|
|
153
|
+
/** The awareness clocks a socket announced, updated with one awareness update. */
|
|
154
|
+
export function trackAwareness(previous, update) {
|
|
155
|
+
const next = { ...previous };
|
|
156
|
+
const decoder = decoding.createDecoder(update);
|
|
157
|
+
const count = decoding.readVarUint(decoder);
|
|
158
|
+
for (let i = 0; i < count; i += 1) {
|
|
159
|
+
const clientId = decoding.readVarUint(decoder);
|
|
160
|
+
const clock = decoding.readVarUint(decoder);
|
|
161
|
+
const state = decoding.readVarString(decoder);
|
|
162
|
+
if (state === 'null')
|
|
163
|
+
delete next[clientId];
|
|
164
|
+
else if (clientId in next ||
|
|
165
|
+
Object.keys(next).length < MAX_AWARENESS_IDS)
|
|
166
|
+
next[clientId] = clock;
|
|
167
|
+
}
|
|
168
|
+
return next;
|
|
169
|
+
}
|
|
170
|
+
/** An awareness update removing a closed socket's states (clock + 1, state null). */
|
|
171
|
+
export function awarenessRemovalFrame(clocks) {
|
|
172
|
+
const entries = Object.entries(clocks);
|
|
173
|
+
if (entries.length === 0)
|
|
174
|
+
return undefined;
|
|
175
|
+
const inner = encoding.createEncoder();
|
|
176
|
+
encoding.writeVarUint(inner, entries.length);
|
|
177
|
+
for (const [clientId, clock] of entries) {
|
|
178
|
+
encoding.writeVarUint(inner, Number(clientId));
|
|
179
|
+
encoding.writeVarUint(inner, clock + 1);
|
|
180
|
+
encoding.writeVarString(inner, 'null');
|
|
181
|
+
}
|
|
182
|
+
const outer = encoding.createEncoder();
|
|
183
|
+
encoding.writeVarUint(outer, MESSAGE.AWARENESS);
|
|
184
|
+
encoding.writeVarUint8Array(outer, encoding.toUint8Array(inner));
|
|
185
|
+
return encoding.toUint8Array(outer);
|
|
186
|
+
}
|
|
187
|
+
export { Y };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type RouteOptions } from './route.ts';
|
|
2
|
+
import type { LiveRoomsHooks, RoomRuntime, RoomSocket, RoomState } from './types.ts';
|
|
3
|
+
/**
|
|
4
|
+
* `@alecsibilia/ui-kit/live/server`: live rooms on Cloudflare (Durable Objects with
|
|
5
|
+
* hibernating WebSockets). An app declares its room types once
|
|
6
|
+
* (`declareLiveRooms`, `@alecsibilia/ui-kit/live`), supplies hooks here, mounts the
|
|
7
|
+
* route in its Worker and exports the room class:
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* // worker/live.ts
|
|
11
|
+
* export const liveRooms = createLiveRooms(LIVE_ROOMS, {
|
|
12
|
+
* resolveUser: (request, env) => ..., // the app's session
|
|
13
|
+
* types: {
|
|
14
|
+
* page: { authorize: (_user, _room, action) => action === "join" },
|
|
15
|
+
* plan: {
|
|
16
|
+
* authorize: (user, room, action, { env }) => ..., // owner + members
|
|
17
|
+
* docs: { notes: { seed: ..., persist: { run: ... } } },
|
|
18
|
+
* },
|
|
19
|
+
* },
|
|
20
|
+
* });
|
|
21
|
+
* // worker/index.ts
|
|
22
|
+
* export const LiveRoom = liveRooms.RoomObject; // the declared className
|
|
23
|
+
* const live = liveRooms.route(request, env); if (live) return live;
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Guide, client contract and costs: `docs/guides/ui-kit-live-rooms.md`.
|
|
27
|
+
*/
|
|
28
|
+
import type { AnyLiveRoomsDecl } from '../declaration.ts';
|
|
29
|
+
export * from './types.ts';
|
|
30
|
+
export { createRoomCore, DEFAULT_RECHECK_EDIT_MS, MAX_DOC_FRAME, RATE, type RoomCore, } from './room.ts';
|
|
31
|
+
export { createLiveRoomsRoute, isAllowedOrigin, liveRoomsEnv, randomPeerId, type LiveRoomsEnv, type RouteOptions, } from './route.ts';
|
|
32
|
+
export { COMPACT_AFTER_ROWS, DEFAULT_DOC_MAX_BYTES } from './doc-store.ts';
|
|
33
|
+
/** The runtime in workerd (only constructed inside the room object). */
|
|
34
|
+
export declare function workerdRoomRuntime(): RoomRuntime;
|
|
35
|
+
/** The Durable Object class shape workerd constructs (`new RoomObject(ctx, env)`). */
|
|
36
|
+
export interface RoomObjectClass {
|
|
37
|
+
new (ctx: RoomState, env: unknown): {
|
|
38
|
+
fetch(request: Request): Promise<Response>;
|
|
39
|
+
webSocketMessage(socket: RoomSocket, message: string | ArrayBuffer): Promise<void>;
|
|
40
|
+
webSocketClose(socket: RoomSocket, code: number): Promise<void>;
|
|
41
|
+
webSocketError(socket: RoomSocket): Promise<void>;
|
|
42
|
+
alarm(): Promise<void>;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export interface LiveRooms<D extends AnyLiveRoomsDecl, Env> {
|
|
46
|
+
readonly decl: D;
|
|
47
|
+
/** The Worker route: a `Response` for `/live/room/*`, `undefined` for anything else. */
|
|
48
|
+
readonly route: (request: Request, env: Env, options?: RouteOptions) => Promise<Response> | undefined;
|
|
49
|
+
/** The room Durable Object class. Export it from the Worker entry as `decl.durableObject.className`. */
|
|
50
|
+
readonly RoomObject: RoomObjectClass;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Builds live rooms from the declaration and the app's hooks. Throws at
|
|
54
|
+
* startup when the hooks don't cover the declaration (a room type without
|
|
55
|
+
* hooks, hooks for an undeclared type or doc).
|
|
56
|
+
*
|
|
57
|
+
* @param decl - `declareLiveRooms(...)` (shared with the client and Alchemy)
|
|
58
|
+
* @param hooks - `resolveUser`, and per type `authorize` (+ `key`, doc `seed` / `persist`)
|
|
59
|
+
*/
|
|
60
|
+
export declare function createLiveRooms<D extends AnyLiveRoomsDecl, Env>(decl: D, hooks: LiveRoomsHooks<D, Env>): LiveRooms<D, Env>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createRoomCore } from './room.js';
|
|
2
|
+
import { createLiveRoomsRoute } from './route.js';
|
|
3
|
+
import { LIVE_PING } from '../protocol.js';
|
|
4
|
+
export * from './types.js';
|
|
5
|
+
export { createRoomCore, DEFAULT_RECHECK_EDIT_MS, MAX_DOC_FRAME, RATE, } from './room.js';
|
|
6
|
+
export { createLiveRoomsRoute, isAllowedOrigin, liveRoomsEnv, randomPeerId, } from './route.js';
|
|
7
|
+
export { COMPACT_AFTER_ROWS, DEFAULT_DOC_MAX_BYTES } from './doc-store.js';
|
|
8
|
+
/** The runtime in workerd (only constructed inside the room object). */
|
|
9
|
+
export function workerdRoomRuntime() {
|
|
10
|
+
return {
|
|
11
|
+
newPair: () => {
|
|
12
|
+
const pair = new WebSocketPair();
|
|
13
|
+
return { client: pair[0], server: pair[1] };
|
|
14
|
+
},
|
|
15
|
+
switchingProtocols: (client) => new Response(null, {
|
|
16
|
+
status: 101,
|
|
17
|
+
webSocket: client,
|
|
18
|
+
}),
|
|
19
|
+
autoResponse: (request, response) => new WebSocketRequestResponsePair(request, response),
|
|
20
|
+
now: () => Date.now(),
|
|
21
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
22
|
+
randomId: () => crypto.randomUUID(),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Builds live rooms from the declaration and the app's hooks. Throws at
|
|
27
|
+
* startup when the hooks don't cover the declaration (a room type without
|
|
28
|
+
* hooks, hooks for an undeclared type or doc).
|
|
29
|
+
*
|
|
30
|
+
* @param decl - `declareLiveRooms(...)` (shared with the client and Alchemy)
|
|
31
|
+
* @param hooks - `resolveUser`, and per type `authorize` (+ `key`, doc `seed` / `persist`)
|
|
32
|
+
*/
|
|
33
|
+
export function createLiveRooms(decl, hooks) {
|
|
34
|
+
const declared = Object.keys(decl.types);
|
|
35
|
+
const given = Object.keys(hooks.types);
|
|
36
|
+
for (const type of declared) {
|
|
37
|
+
if (!given.includes(type))
|
|
38
|
+
throw new Error(`createLiveRooms: no hooks for declared room type "${type}"`);
|
|
39
|
+
}
|
|
40
|
+
for (const type of given) {
|
|
41
|
+
if (!declared.includes(type)) {
|
|
42
|
+
throw new Error(`createLiveRooms: hooks for room type "${type}", which declareLiveRooms doesn't declare`);
|
|
43
|
+
}
|
|
44
|
+
const docs = hooks.types[type]?.docs ?? {};
|
|
45
|
+
for (const doc of Object.keys(docs)) {
|
|
46
|
+
if (!(decl.types[type]?.docs ?? []).includes(doc)) {
|
|
47
|
+
throw new Error(`createLiveRooms: hooks for doc "${doc}" of "${type}", which isn't declared`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// Why a class: Cloudflare constructs a Durable Object with `new`. A thin
|
|
52
|
+
// shell over `createRoomCore` (same approved exception as `FeedChannel`).
|
|
53
|
+
class RoomObject {
|
|
54
|
+
core;
|
|
55
|
+
constructor(ctx, env) {
|
|
56
|
+
const runtime = workerdRoomRuntime();
|
|
57
|
+
ctx.setWebSocketAutoResponse(runtime.autoResponse(LIVE_PING.request, LIVE_PING.response));
|
|
58
|
+
this.core = createRoomCore(decl, hooks, ctx, env, runtime);
|
|
59
|
+
}
|
|
60
|
+
fetch(request) {
|
|
61
|
+
return this.core.fetch(request);
|
|
62
|
+
}
|
|
63
|
+
webSocketMessage(socket, message) {
|
|
64
|
+
return this.core.message(socket, message);
|
|
65
|
+
}
|
|
66
|
+
webSocketClose(socket, code) {
|
|
67
|
+
return this.core.close(socket, code);
|
|
68
|
+
}
|
|
69
|
+
webSocketError(socket) {
|
|
70
|
+
return this.core.close(socket, 1011);
|
|
71
|
+
}
|
|
72
|
+
alarm() {
|
|
73
|
+
return this.core.alarm();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return { decl, route: createLiveRoomsRoute(decl, hooks), RoomObject };
|
|
77
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Attachment, type Bucket } from './room-sockets.ts';
|
|
2
|
+
import type { RoomRuntime, RoomSocket, RoomState } from './types.ts';
|
|
3
|
+
import type { RoomCapabilities } from '../declaration.ts';
|
|
4
|
+
import { type CursorEntry, type Peer, type RoomServerFrame } from '../protocol.ts';
|
|
5
|
+
/**
|
|
6
|
+
* The room's presence and cursor fan-out: who is here, the room broadcast,
|
|
7
|
+
* and the 50 ms cursor flush. Memory only (rebuilt after a wake); created
|
|
8
|
+
* once per room object by `createRoomCore` (`room.ts`).
|
|
9
|
+
*/
|
|
10
|
+
export declare function createRoomPresence({ state, runtime, }: {
|
|
11
|
+
state: RoomState;
|
|
12
|
+
runtime: RoomRuntime;
|
|
13
|
+
}): {
|
|
14
|
+
movedPids: Set<string>;
|
|
15
|
+
peers: (except?: RoomSocket) => {
|
|
16
|
+
peers: Peer[];
|
|
17
|
+
tabs: number;
|
|
18
|
+
};
|
|
19
|
+
broadcastRoom: (frame: RoomServerFrame, except?: RoomSocket) => void;
|
|
20
|
+
broadcastPresence: (caps: RoomCapabilities, except?: RoomSocket) => void;
|
|
21
|
+
queueCursor: (entry: CursorEntry) => void;
|
|
22
|
+
roomMessage: (socket: RoomSocket, att: Attachment, caps: RoomCapabilities, data: string | ArrayBuffer) => void;
|
|
23
|
+
bucketOf: (socket: RoomSocket, burst: number) => Bucket;
|
|
24
|
+
};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { attachmentOf, RATE, ROOM_TAG, sendSafe, take, } from './room-sockets.js';
|
|
2
|
+
import { CURSOR_FLUSH_MS, decodeCursor, hueOf, } from '../protocol.js';
|
|
3
|
+
/**
|
|
4
|
+
* The room's presence and cursor fan-out: who is here, the room broadcast,
|
|
5
|
+
* and the 50 ms cursor flush. Memory only (rebuilt after a wake); created
|
|
6
|
+
* once per room object by `createRoomCore` (`room.ts`).
|
|
7
|
+
*/
|
|
8
|
+
export function createRoomPresence({ state, runtime, }) {
|
|
9
|
+
const pendingCursors = new Map();
|
|
10
|
+
/** Presence ids that sent a cursor since the last wake (only they need a "left" entry on close). */
|
|
11
|
+
const movedPids = new Set();
|
|
12
|
+
let flushArmed = false;
|
|
13
|
+
const buckets = new WeakMap();
|
|
14
|
+
// --- presence ------------------------------------------------------------
|
|
15
|
+
function peers(except) {
|
|
16
|
+
const seen = new Map();
|
|
17
|
+
let tabs = 0;
|
|
18
|
+
for (const socket of state.getWebSockets(ROOM_TAG)) {
|
|
19
|
+
if (socket === except)
|
|
20
|
+
continue;
|
|
21
|
+
const att = attachmentOf(socket);
|
|
22
|
+
if (!att)
|
|
23
|
+
continue;
|
|
24
|
+
tabs += 1;
|
|
25
|
+
if (seen.has(att.pid))
|
|
26
|
+
continue;
|
|
27
|
+
seen.set(att.pid, {
|
|
28
|
+
id: att.pid,
|
|
29
|
+
name: att.user._tag === 'Member' ? att.user.name : 'Guest',
|
|
30
|
+
kind: att.user._tag,
|
|
31
|
+
hue: hueOf(att.pid),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return { peers: [...seen.values()], tabs };
|
|
35
|
+
}
|
|
36
|
+
function broadcastRoom(frame, except) {
|
|
37
|
+
const text = JSON.stringify(frame);
|
|
38
|
+
for (const socket of state.getWebSockets(ROOM_TAG)) {
|
|
39
|
+
if (socket !== except)
|
|
40
|
+
sendSafe(socket, text);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function broadcastPresence(caps, except) {
|
|
44
|
+
if (!caps.presence)
|
|
45
|
+
return;
|
|
46
|
+
const list = peers(except);
|
|
47
|
+
broadcastRoom({ t: 'presence', peers: list.peers, tabs: list.tabs }, except);
|
|
48
|
+
}
|
|
49
|
+
// --- cursors -------------------------------------------------------------
|
|
50
|
+
function flushCursors() {
|
|
51
|
+
flushArmed = false;
|
|
52
|
+
if (pendingCursors.size === 0)
|
|
53
|
+
return;
|
|
54
|
+
const entries = [...pendingCursors.values()];
|
|
55
|
+
pendingCursors.clear();
|
|
56
|
+
const shared = JSON.stringify({
|
|
57
|
+
t: 'cursors',
|
|
58
|
+
c: entries,
|
|
59
|
+
});
|
|
60
|
+
for (const socket of state.getWebSockets(ROOM_TAG)) {
|
|
61
|
+
const att = attachmentOf(socket);
|
|
62
|
+
if (!att)
|
|
63
|
+
continue;
|
|
64
|
+
// Never echo a peer its own cursor.
|
|
65
|
+
if (!entries.some((entry) => entry[0] === att.pid)) {
|
|
66
|
+
sendSafe(socket, shared);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const others = entries.filter((entry) => entry[0] !== att.pid);
|
|
70
|
+
if (others.length > 0)
|
|
71
|
+
sendSafe(socket, JSON.stringify({ t: 'cursors', c: others }));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function queueCursor(entry) {
|
|
75
|
+
pendingCursors.set(entry[0], entry);
|
|
76
|
+
if (flushArmed)
|
|
77
|
+
return;
|
|
78
|
+
flushArmed = true;
|
|
79
|
+
runtime.setTimeout(flushCursors, CURSOR_FLUSH_MS);
|
|
80
|
+
}
|
|
81
|
+
/** Whether any room socket belongs to another presence id. */
|
|
82
|
+
function hasOtherPeers(pid) {
|
|
83
|
+
for (const socket of state.getWebSockets(ROOM_TAG)) {
|
|
84
|
+
const att = attachmentOf(socket);
|
|
85
|
+
if (att && att.pid !== pid)
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
function roomMessage(socket, att, caps, data) {
|
|
91
|
+
if (!caps.cursors || typeof data !== 'string')
|
|
92
|
+
return;
|
|
93
|
+
const bucket = bucketOf(socket, RATE.ROOM.burst);
|
|
94
|
+
if (!take(bucket, RATE.ROOM, runtime.now()))
|
|
95
|
+
return;
|
|
96
|
+
const cursor = decodeCursor(data);
|
|
97
|
+
if (cursor === undefined)
|
|
98
|
+
return;
|
|
99
|
+
// Alone: nobody to tell, so no timer and no work.
|
|
100
|
+
if (!hasOtherPeers(att.pid))
|
|
101
|
+
return;
|
|
102
|
+
if (cursor !== null)
|
|
103
|
+
movedPids.add(att.pid);
|
|
104
|
+
queueCursor(cursor === null ? [att.pid] : [att.pid, cursor[0], cursor[1]]);
|
|
105
|
+
}
|
|
106
|
+
function bucketOf(socket, burst) {
|
|
107
|
+
let bucket = buckets.get(socket);
|
|
108
|
+
if (!bucket) {
|
|
109
|
+
bucket = { tokens: burst, at: runtime.now() };
|
|
110
|
+
buckets.set(socket, bucket);
|
|
111
|
+
}
|
|
112
|
+
return bucket;
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
movedPids,
|
|
116
|
+
peers,
|
|
117
|
+
broadcastRoom,
|
|
118
|
+
broadcastPresence,
|
|
119
|
+
queueCursor,
|
|
120
|
+
roomMessage,
|
|
121
|
+
bucketOf,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type LiveIdentity, type LiveUser, type RoomSocket } from './types.ts';
|
|
2
|
+
import { type RoomAccess } from '../protocol.ts';
|
|
3
|
+
/**
|
|
4
|
+
* The room's socket plumbing: per-socket attachments, token buckets, safe
|
|
5
|
+
* send and close, and the identity the Worker forwards. Used by
|
|
6
|
+
* `room.ts`; module-level constants and pure helpers only.
|
|
7
|
+
*/
|
|
8
|
+
/** Per-socket token buckets (burst, refill per second). */
|
|
9
|
+
export declare const RATE: {
|
|
10
|
+
/** Room socket frames (cursors): 20/s sent, some slack for jitter. */
|
|
11
|
+
readonly ROOM: {
|
|
12
|
+
readonly burst: 40;
|
|
13
|
+
readonly perSecond: 25;
|
|
14
|
+
};
|
|
15
|
+
/** Doc socket frames (updates + awareness). */
|
|
16
|
+
readonly DOC: {
|
|
17
|
+
readonly burst: 60;
|
|
18
|
+
readonly perSecond: 30;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
/** Largest doc frame the room reads (bytes). */
|
|
22
|
+
export declare const MAX_DOC_FRAME: number;
|
|
23
|
+
/** Largest awareness frame the room relays (bytes). */
|
|
24
|
+
export declare const MAX_AWARENESS_FRAME: number;
|
|
25
|
+
/** Default `recheckEditMs`. */
|
|
26
|
+
export declare const DEFAULT_RECHECK_EDIT_MS = 30000;
|
|
27
|
+
/** Default persist debounce. */
|
|
28
|
+
export declare const DEFAULT_PERSIST_DEBOUNCE_MS = 2000;
|
|
29
|
+
export declare const ROOM_TAG = "r";
|
|
30
|
+
export declare const docTag: (doc: string) => string;
|
|
31
|
+
export declare const sessionTag: (session: string) => string;
|
|
32
|
+
export declare const PERSIST_PREFIX = "persist:";
|
|
33
|
+
export declare const ROOM_META = "room";
|
|
34
|
+
/** What survives hibernation for one socket (≤ 2 KB serialized). */
|
|
35
|
+
export interface Attachment {
|
|
36
|
+
readonly peer: string;
|
|
37
|
+
/** Presence / cursor id: per user for members (their tabs count once), per tab for guests. */
|
|
38
|
+
readonly pid: string;
|
|
39
|
+
readonly user: LiveUser;
|
|
40
|
+
access: RoomAccess;
|
|
41
|
+
readonly kind: 'r' | 'd';
|
|
42
|
+
readonly doc?: string;
|
|
43
|
+
readonly type: string;
|
|
44
|
+
readonly key: string;
|
|
45
|
+
/** Epoch ms of the last `authorize(…, "edit")` that passed. */
|
|
46
|
+
checkedAt: number;
|
|
47
|
+
/** Awareness client id → last clock this socket announced (doc sockets). */
|
|
48
|
+
aw?: Record<string, number>;
|
|
49
|
+
}
|
|
50
|
+
export interface Bucket {
|
|
51
|
+
tokens: number;
|
|
52
|
+
at: number;
|
|
53
|
+
}
|
|
54
|
+
export declare function take(bucket: Bucket, spec: {
|
|
55
|
+
readonly burst: number;
|
|
56
|
+
readonly perSecond: number;
|
|
57
|
+
}, now: number): boolean;
|
|
58
|
+
export declare function attachmentOf(socket: RoomSocket): Attachment | undefined;
|
|
59
|
+
export declare function sendSafe(socket: RoomSocket, data: string | Uint8Array): void;
|
|
60
|
+
export declare function closeSafe(socket: RoomSocket, code: number, reason: string): void;
|
|
61
|
+
/** Whether an endpoint may send `code` in a close frame. */
|
|
62
|
+
export declare function sendableCode(code: number): number;
|
|
63
|
+
/** A 64-bit hex digest of a string (two FNV-1a lanes): a member's presence id, not reversible to the user id in practice. */
|
|
64
|
+
export declare function presenceIdOf(user: LiveUser, peer: string): string;
|
|
65
|
+
export declare function parseIdentity(request: Request): LiveIdentity | undefined;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { IDENTITY_HEADER, } from './types.js';
|
|
2
|
+
import {} from '../protocol.js';
|
|
3
|
+
/**
|
|
4
|
+
* The room's socket plumbing: per-socket attachments, token buckets, safe
|
|
5
|
+
* send and close, and the identity the Worker forwards. Used by
|
|
6
|
+
* `room.ts`; module-level constants and pure helpers only.
|
|
7
|
+
*/
|
|
8
|
+
/** Per-socket token buckets (burst, refill per second). */
|
|
9
|
+
export const RATE = {
|
|
10
|
+
/** Room socket frames (cursors): 20/s sent, some slack for jitter. */
|
|
11
|
+
ROOM: { burst: 40, perSecond: 25 },
|
|
12
|
+
/** Doc socket frames (updates + awareness). */
|
|
13
|
+
DOC: { burst: 60, perSecond: 30 },
|
|
14
|
+
};
|
|
15
|
+
/** Largest doc frame the room reads (bytes). */
|
|
16
|
+
export const MAX_DOC_FRAME = 64 * 1024;
|
|
17
|
+
/** Largest awareness frame the room relays (bytes). */
|
|
18
|
+
export const MAX_AWARENESS_FRAME = 8 * 1024;
|
|
19
|
+
/** Default `recheckEditMs`. */
|
|
20
|
+
export const DEFAULT_RECHECK_EDIT_MS = 30_000;
|
|
21
|
+
/** Default persist debounce. */
|
|
22
|
+
export const DEFAULT_PERSIST_DEBOUNCE_MS = 2_000;
|
|
23
|
+
export const ROOM_TAG = 'r';
|
|
24
|
+
export const docTag = (doc) => `d:${doc}`;
|
|
25
|
+
export const sessionTag = (session) => `s:${session}`;
|
|
26
|
+
export const PERSIST_PREFIX = 'persist:';
|
|
27
|
+
export const ROOM_META = 'room';
|
|
28
|
+
export function take(bucket, spec, now) {
|
|
29
|
+
bucket.tokens = Math.min(spec.burst, bucket.tokens + ((now - bucket.at) / 1000) * spec.perSecond);
|
|
30
|
+
bucket.at = now;
|
|
31
|
+
if (bucket.tokens < 1)
|
|
32
|
+
return false;
|
|
33
|
+
bucket.tokens -= 1;
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
export function attachmentOf(socket) {
|
|
37
|
+
try {
|
|
38
|
+
return (socket.deserializeAttachment() ?? undefined);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function sendSafe(socket, data) {
|
|
45
|
+
try {
|
|
46
|
+
socket.send(data);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// Gone meanwhile; its close handler cleans up.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function closeSafe(socket, code, reason) {
|
|
53
|
+
try {
|
|
54
|
+
socket.close(code, reason);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// Already closed.
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Whether an endpoint may send `code` in a close frame. */
|
|
61
|
+
export function sendableCode(code) {
|
|
62
|
+
if ((code >= 1000 && code <= 1003) ||
|
|
63
|
+
(code >= 1007 && code <= 1014) ||
|
|
64
|
+
(code >= 3000 && code <= 4999)) {
|
|
65
|
+
return code;
|
|
66
|
+
}
|
|
67
|
+
return 1000;
|
|
68
|
+
}
|
|
69
|
+
/** A 64-bit hex digest of a string (two FNV-1a lanes): a member's presence id, not reversible to the user id in practice. */
|
|
70
|
+
export function presenceIdOf(user, peer) {
|
|
71
|
+
if (user._tag === 'Guest')
|
|
72
|
+
return peer;
|
|
73
|
+
let a = 0x811c9dc5;
|
|
74
|
+
let b = 0x01000193 ^ 0x5bd1e995;
|
|
75
|
+
const text = `member:${user.userId}`;
|
|
76
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
77
|
+
const c = text.charCodeAt(i);
|
|
78
|
+
a = Math.imul(a ^ c, 0x01000193);
|
|
79
|
+
b = Math.imul(b ^ c, 0x5bd1e995);
|
|
80
|
+
}
|
|
81
|
+
return `m${(a >>> 0).toString(16).padStart(8, '0')}${(b >>> 0).toString(16).padStart(8, '0')}`;
|
|
82
|
+
}
|
|
83
|
+
export function parseIdentity(request) {
|
|
84
|
+
const raw = request.headers.get(IDENTITY_HEADER);
|
|
85
|
+
if (raw === null)
|
|
86
|
+
return undefined;
|
|
87
|
+
try {
|
|
88
|
+
const value = JSON.parse(raw);
|
|
89
|
+
return typeof value?.peer === 'string' &&
|
|
90
|
+
typeof value.room?.type === 'string'
|
|
91
|
+
? value
|
|
92
|
+
: undefined;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type LiveRoomsHooks, type RoomSocket, type RoomRuntime, type RoomState } from './types.ts';
|
|
2
|
+
import { type AnyLiveRoomsDecl } from '../declaration.ts';
|
|
3
|
+
export { DEFAULT_PERSIST_DEBOUNCE_MS, DEFAULT_RECHECK_EDIT_MS, MAX_AWARENESS_FRAME, MAX_DOC_FRAME, RATE, } from './room-sockets.ts';
|
|
4
|
+
/** The room's handlers (what the Durable Object class forwards to). */
|
|
5
|
+
export interface RoomCore {
|
|
6
|
+
fetch(request: Request): Promise<Response>;
|
|
7
|
+
message(socket: RoomSocket, data: string | ArrayBuffer): Promise<void>;
|
|
8
|
+
close(socket: RoomSocket, code: number): Promise<void>;
|
|
9
|
+
alarm(): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* One room object's logic.
|
|
13
|
+
*
|
|
14
|
+
* @param decl - the app's declaration (capabilities per type)
|
|
15
|
+
* @param hooks - the app's hooks (authorize, doc seed / persist)
|
|
16
|
+
* @param state - the object's `DurableObjectState` (or a fake)
|
|
17
|
+
* @param env - the object's bindings, handed to hooks
|
|
18
|
+
* @param runtime - workerd's socket pair, `101`, clock and timers (or fakes)
|
|
19
|
+
*/
|
|
20
|
+
export declare function createRoomCore<D extends AnyLiveRoomsDecl, Env>(decl: D, hooks: LiveRoomsHooks<D, Env>, state: RoomState, env: Env, runtime: RoomRuntime): RoomCore;
|