@alexsun-top/opencode-chat-room 0.8.0 → 0.8.2
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 +52 -0
- package/LICENSE +2 -2
- package/README.md +40 -8
- package/README.zh-CN.md +40 -8
- package/cli.ts +27 -1
- package/dist/cli.js +5406 -3088
- package/package.json +25 -5
- package/packages/chat-room-channeld/README.md +111 -33
- package/packages/chat-room-channeld/src/adapter.ts +179 -7
- package/packages/chat-room-channeld/src/config.ts +63 -1
- package/packages/chat-room-channeld/src/delivery.ts +6 -1
- package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
- package/packages/chat-room-channeld/src/host.ts +142 -9
- package/packages/chat-room-channeld/src/inbound.ts +35 -0
- package/packages/chat-room-channeld/src/protocol.ts +52 -1
- package/packages/chat-room-channeld/src/rules.ts +7 -2
- package/packages/chat-room-channeld/src/state.ts +17 -0
- package/packages/chat-room-channeld/src/stats.ts +43 -1
- package/plugin.ts +1 -1
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +21 -9
- package/server/assets/chat/admin.js +0 -2
- package/server/assets/chat/announcements.js +69 -8
- package/server/assets/chat/chat-background.js +177 -0
- package/server/assets/chat/confirm-dialog.js +0 -1
- package/server/assets/chat/create-room-dialog.js +0 -1
- package/server/assets/chat/diagram-viewer.js +7 -1
- package/server/assets/chat/doc-preview.js +251 -46
- package/server/assets/chat/events.js +16 -5
- package/server/assets/chat/files.js +53 -7
- package/server/assets/chat/image-zoom.js +8 -1
- package/server/assets/chat/index.js +6 -2
- package/server/assets/chat/integration-account-schema.js +99 -0
- package/server/assets/chat/integration-editor.js +163 -0
- package/server/assets/chat/integration-values.js +124 -0
- package/server/assets/chat/integrations.js +648 -0
- package/server/assets/chat/locales/de.js +40 -4
- package/server/assets/chat/locales/es.js +40 -4
- package/server/assets/chat/locales/fr.js +40 -4
- package/server/assets/chat/locales/it.js +40 -4
- package/server/assets/chat/locales/ja.js +40 -4
- package/server/assets/chat/locales/ko.js +40 -4
- package/server/assets/chat/markdown-footnotes.js +1 -1
- package/server/assets/chat/markdown.js +45 -8
- package/server/assets/chat/messages.js +6 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/palette.js +6 -1
- package/server/assets/chat/panels.js +56 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +17 -6
- package/server/assets/chat/reminders.js +68 -9
- package/server/assets/chat/replies.js +0 -6
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/rooms.js +1 -6
- package/server/assets/chat/settings.js +98 -4
- package/server/assets/chat/shortcuts.js +0 -3
- package/server/assets/chat/side-pane.js +34 -10
- package/server/assets/chat/state.js +125 -12
- package/server/assets/chat/system-events.js +58 -0
- package/server/assets/chat/system-messages.js +32 -14
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +119 -37
- package/server/assets/chat/window-controls.js +37 -0
- package/server/assets/code-highlight.css +71 -32
- package/server/assets/conversation.css +174 -31
- package/server/assets/doc-preview.css +40 -3
- package/server/assets/files.css +8 -0
- package/server/assets/fluent-icons.svg +2 -0
- package/server/assets/monaco/LICENSE +21 -0
- package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
- package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
- package/server/assets/monaco/editor.worker.js +45 -0
- package/server/assets/monaco/integration-rules.css +1 -0
- package/server/assets/monaco/integration-rules.js +1605 -0
- package/server/assets/monaco/json.worker.js +77 -0
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
- package/server/assets/office/docx.bundle.js +33 -0
- package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
- package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
- package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
- package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
- package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
- package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
- package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
- package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
- package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
- package/server/assets/office/pptx.bundle.js +104 -0
- package/server/assets/office/xlsx.bundle.js +141 -0
- package/server/assets/recall.css +5 -4
- package/server/assets/responsive.css +80 -11
- package/server/assets/settings.css +185 -9
- package/server/assets/tasks.css +57 -7
- package/server/assets/window-controls.css +36 -0
- package/server/channel-attachments.ts +133 -0
- package/server/channel-integration.ts +572 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +274 -21
- package/server/chat-server.ts +32 -580
- package/server/chat.html +234 -34
- package/server/http-server.ts +3 -182
- package/server/manifest.webmanifest +1 -0
- package/server/resource-routes.ts +16 -16
- package/server/routes/inbox.ts +100 -0
- package/server/routes/pages.ts +83 -0
- package/server/routes/questions.ts +39 -0
- package/server/routes/room-actions.ts +162 -0
- package/server/routes/rooms.ts +160 -0
- package/server/startup.ts +84 -0
- package/server/sw.js +5 -0
- package/server/task-routes.ts +1 -1
- package/src/center/center-client.ts +3 -11
- package/src/config/file-config.ts +7 -54
- package/src/platform/http-server.ts +182 -0
- package/src/protocol/addressing.ts +21 -0
- package/src/protocol/config.ts +58 -0
- package/src/protocol/room.ts +51 -0
- package/src/rooms/resources.ts +26 -16
- package/src/rooms/room-service.ts +2 -48
- package/src/rooms/storage.ts +329 -0
- package/src/rooms/tasks.ts +21 -5
- package/src/runtime/watch.ts +1 -1
- package/src/state/pg-database.ts +183 -0
- package/src/state/pg-migrate.ts +175 -0
- package/src/state/pg-sql.mjs +175 -0
- package/src/state/pg-worker.mjs +133 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +130 -0
- package/src/state/sqlite-legacy.ts +90 -0
- package/src/state/sqlite-members.ts +155 -0
- package/src/state/sqlite-messages.ts +288 -0
- package/src/state/sqlite-resources.ts +39 -0
- package/src/state/sqlite-rooms.ts +194 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +34 -0
- package/src/state/sqlite-state.ts +15 -897
- package/src/state/sqlite-tasks.ts +65 -0
- package/src/state/sqlite-transaction.ts +13 -0
- package/src/state/sqlite.ts +21 -1
- package/src/state/store.ts +5 -1
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- package/src/tui/i18n.mjs +38 -0
- package/src/tui/info-app.mjs +50 -51
- package/src/tui/info-content.mjs +79 -44
- package/src/tui/join-app.mjs +9 -9
- package/src/tui/locales/en.mjs +349 -0
- package/src/tui/locales/zh-CN.mjs +349 -0
- package/src/tui/main.mjs +85 -37
- package/src/tui/markdown.mjs +3 -2
- package/src/tui/mentions.mjs +3 -1
- package/src/tui/message-app.mjs +22 -21
- package/src/tui/message-view.mjs +2 -1
- package/src/tui/palette-app.mjs +9 -8
- package/src/tui/palette.mjs +30 -24
- package/src/tui/prefs.mjs +92 -0
- package/src/tui/reminder-app.mjs +18 -17
- package/src/tui/room-settings-app.mjs +30 -28
- package/src/tui/settings-app.mjs +153 -0
- package/src/tui/ui-content.mjs +65 -86
- package/src/tui/ui-help.mjs +73 -0
- package/src/tui/ui-overlay-view.mjs +23 -7
- package/src/tui/ui-suggest.mjs +6 -5
- package/src/tui/ui-theme.mjs +37 -33
- package/src/tui/ui-view.mjs +22 -7
- package/src/tui/ui.mjs +15 -3
- package/src/web/editor.worker.ts +1 -0
- package/src/web/integration-rules-editor.ts +573 -0
- package/src/web/integration-rules.ts +26 -0
- package/src/web/integration-schema.ts +229 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -499
- package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -473
- package/server/assets/chat/forward.js +0 -69
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { stat } from "node:fs/promises";
|
|
3
|
-
import { Readable } from "node:stream";
|
|
4
|
-
import { deleteResource, findResource, listRoomResources, maxResourceBytes, resourcePath, uploadResource, type Resource } from "../src/rooms/resources.ts";
|
|
1
|
+
import { deleteResource, findResource, listRoomResources, maxResourceBytes, openResource, uploadResource, type Resource } from "../src/rooms/resources.ts";
|
|
5
2
|
import { readState } from "../src/state/store.ts";
|
|
6
3
|
import { isRoomAdmin, isUser } from "./room-owner.ts";
|
|
7
4
|
|
|
@@ -77,23 +74,26 @@ export async function resourceRoutes(req: Request, url: URL): Promise<Response |
|
|
|
77
74
|
}
|
|
78
75
|
|
|
79
76
|
async function content(req: Request, resource: Resource): Promise<Response> {
|
|
80
|
-
|
|
81
|
-
|
|
77
|
+
// The database row is authoritative for size and Range validation; storage
|
|
78
|
+
// streams exactly the validated window.
|
|
79
|
+
const size = resource.size;
|
|
82
80
|
const range = req.headers.get("range");
|
|
83
|
-
if (range &&
|
|
84
|
-
if (
|
|
85
|
-
let start = 0, end =
|
|
81
|
+
if (range && size === 0) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": "bytes */0" } });
|
|
82
|
+
if (size === 0) return new Response(null, { headers: { ...safeHeaders, "Content-Type": resource.mimeType, "Content-Disposition": contentDisposition(resource.name, false), "Content-Length": "0" } });
|
|
83
|
+
let start = 0, end = size - 1, status = 200;
|
|
86
84
|
if (range) {
|
|
87
85
|
const match = range.match(/^bytes=(\d*)-(\d*)$/);
|
|
88
|
-
if (!match || (!match[1] && !match[2])) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${
|
|
89
|
-
if (!match[1]) { const suffix = Number(match[2]); if (!Number.isSafeInteger(suffix) || suffix <= 0) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${
|
|
90
|
-
else { start = Number(match[1]); if (!Number.isSafeInteger(start)) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${
|
|
91
|
-
if (match[1] && match[2]) { const requestedEnd = Number(match[2]); if (!Number.isSafeInteger(requestedEnd)) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${
|
|
92
|
-
if (start >=
|
|
86
|
+
if (!match || (!match[1] && !match[2])) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${size}` } });
|
|
87
|
+
if (!match[1]) { const suffix = Number(match[2]); if (!Number.isSafeInteger(suffix) || suffix <= 0) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${size}` } }); start = Math.max(0, size - suffix); }
|
|
88
|
+
else { start = Number(match[1]); if (!Number.isSafeInteger(start)) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${size}` } }); }
|
|
89
|
+
if (match[1] && match[2]) { const requestedEnd = Number(match[2]); if (!Number.isSafeInteger(requestedEnd)) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${size}` } }); end = Math.min(requestedEnd, end); }
|
|
90
|
+
if (start >= size || end < start) return new Response(null, { status: 416, headers: { ...safeHeaders, "Content-Range": `bytes */${size}` } });
|
|
93
91
|
status = 206;
|
|
94
92
|
}
|
|
93
|
+
const opened = await openResource(resource, status === 206 ? start : undefined, status === 206 ? end : undefined);
|
|
94
|
+
if (!opened) return json({ error: "resource not found" }, 404);
|
|
95
95
|
const inline = /^(image\/(png|jpeg|gif|webp)|audio\/(mpeg|ogg|wav)|video\/(mp4|webm))$/.test(resource.mimeType);
|
|
96
96
|
const headers = new Headers({ ...safeHeaders, "Content-Type": resource.mimeType, "Content-Disposition": contentDisposition(resource.name, inline), "Content-Length": String(end - start + 1) });
|
|
97
|
-
if (status === 206) headers.set("Content-Range", `bytes ${start}-${end}/${
|
|
98
|
-
return new Response(
|
|
97
|
+
if (status === 206) headers.set("Content-Range", `bytes ${start}-${end}/${size}`);
|
|
98
|
+
return new Response(opened.stream, { status, headers });
|
|
99
99
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Inbox long-poll, queue acknowledgements and wake arbitration.
|
|
2
|
+
import { acknowledgeQueued } from "../../src/state/store.ts";
|
|
3
|
+
import { clearPendingAdmission } from "../../src/center/queue.ts";
|
|
4
|
+
import { readInbox } from "../inbox.ts";
|
|
5
|
+
import { jsonObject } from "../json-body.ts";
|
|
6
|
+
import { claimWake, touchActive } from "../wake.ts";
|
|
7
|
+
|
|
8
|
+
const json = (body: unknown, status = 200) =>
|
|
9
|
+
new Response(JSON.stringify(body), {
|
|
10
|
+
status,
|
|
11
|
+
headers: { "Content-Type": "application/json" },
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
15
|
+
|
|
16
|
+
export async function inboxRoutes(req: Request, url: URL): Promise<Response | undefined> {
|
|
17
|
+
const p = url.pathname;
|
|
18
|
+
if (req.method === "GET" && p === "/inbox") {
|
|
19
|
+
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
20
|
+
const roomFilter = url.searchParams.get("roomId");
|
|
21
|
+
const afterValue = url.searchParams.get("afterTs");
|
|
22
|
+
const afterTs = afterValue === null ? undefined : Number(afterValue);
|
|
23
|
+
const recallVersionValue = url.searchParams.get("recallVersion");
|
|
24
|
+
if (url.searchParams.has("recallVersion") && (recallVersionValue === "" || !/^\d+$/.test(recallVersionValue ?? "") ||
|
|
25
|
+
!Number.isSafeInteger(Number(recallVersionValue)))) {
|
|
26
|
+
return json({ error: "recallVersion must be a non-negative safe integer" }, 400);
|
|
27
|
+
}
|
|
28
|
+
const clientRecallVersion = recallVersionValue === null ? undefined : Number(recallVersionValue);
|
|
29
|
+
if (url.searchParams.has("afterTs") && (afterValue === "" || !/^\d+$/.test(afterValue ?? "") ||
|
|
30
|
+
!Number.isSafeInteger(afterTs) || afterTs! < 0 || !roomFilter || url.searchParams.get("excludeSelf") !== "0")) {
|
|
31
|
+
return json({ error: "afterTs requires a roomId and excludeSelf=0, with a non-negative safe integer value" }, 400);
|
|
32
|
+
}
|
|
33
|
+
// ponytail: poll includes the caller's own messages (echo), the
|
|
34
|
+
// notification self-pull excludes them — aligned with standalone poll
|
|
35
|
+
const excludeSelf = url.searchParams.get("excludeSelf") === "1";
|
|
36
|
+
// long-poll: wait up to `timeout` ms for the first new message
|
|
37
|
+
// instead of returning empty immediately (web chat + sub-agent
|
|
38
|
+
// watchers); empty responses only happen on timeout
|
|
39
|
+
const timeout = Math.min(
|
|
40
|
+
Math.max(Number(url.searchParams.get("timeout") ?? 0) || 0, 0),
|
|
41
|
+
30000,
|
|
42
|
+
);
|
|
43
|
+
const deadline = Date.now() + timeout;
|
|
44
|
+
let result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
|
|
45
|
+
// The client's rendered snapshot version is the baseline; using the first
|
|
46
|
+
// read instead would hide a recall that landed before this request started.
|
|
47
|
+
const initialRecallVersion = clientRecallVersion ?? result.recallVersion;
|
|
48
|
+
// A recall bumps the version without creating a message; wake the poll so
|
|
49
|
+
// the client can refetch the room snapshot (reliable version compare).
|
|
50
|
+
while (result.items.length === 0 && result.recallVersion === initialRecallVersion && Date.now() < deadline) {
|
|
51
|
+
// ponytail: 500ms between disk scans keeps notification latency under
|
|
52
|
+
// half a second; a longer interval makes deliveries feel stuck.
|
|
53
|
+
await sleep(Math.max(1, Math.min(500, deadline - Date.now())));
|
|
54
|
+
result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
|
|
55
|
+
}
|
|
56
|
+
return json(result);
|
|
57
|
+
}
|
|
58
|
+
if (req.method === "POST" && p === "/queued") {
|
|
59
|
+
const body = await jsonObject<Record<string, unknown>>(req);
|
|
60
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
61
|
+
const ts = Number(body.ts);
|
|
62
|
+
const roomId = String(body.roomId ?? "");
|
|
63
|
+
const sessionID = String(body.sessionID ?? "");
|
|
64
|
+
if (
|
|
65
|
+
body.ts === undefined ||
|
|
66
|
+
body.ts === null ||
|
|
67
|
+
!roomId ||
|
|
68
|
+
!sessionID ||
|
|
69
|
+
!Number.isFinite(ts)
|
|
70
|
+
) {
|
|
71
|
+
return json({ error: "roomId/sessionID/finite ts are required" }, 400);
|
|
72
|
+
}
|
|
73
|
+
// Clamp to the room tail so a forged future ts cannot silence delivery.
|
|
74
|
+
const updated = await acknowledgeQueued(roomId, sessionID, ts);
|
|
75
|
+
if (updated === null) {
|
|
76
|
+
return json({ error: "registry entry not found" }, 404);
|
|
77
|
+
}
|
|
78
|
+
clearPendingAdmission(sessionID, roomId, updated);
|
|
79
|
+
touchActive(sessionID);
|
|
80
|
+
return json({ ok: true });
|
|
81
|
+
}
|
|
82
|
+
if (req.method === "POST" && p === "/active") {
|
|
83
|
+
// Active report: the plugin calls this for sessions it successfully pushed
|
|
84
|
+
// in-process (genuinely active), so the server avoids a duplicate serve wake.
|
|
85
|
+
const body = await jsonObject<Record<string, unknown>>(req);
|
|
86
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
87
|
+
touchActive(String(body.sessionID ?? ""));
|
|
88
|
+
return json({ ok: true });
|
|
89
|
+
}
|
|
90
|
+
if (req.method === "POST" && p === "/wake-claim") {
|
|
91
|
+
// ponytail: atomic cross-process wake dedupe (see claimWake) — the
|
|
92
|
+
// server only arbitrates, it never spawns anything itself
|
|
93
|
+
const body = await jsonObject<Record<string, unknown>>(req);
|
|
94
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
95
|
+
const sessionID = String(body.sessionID ?? "");
|
|
96
|
+
const ok = claimWake(sessionID);
|
|
97
|
+
return json({ ok });
|
|
98
|
+
}
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Static pages and assets served before the JSON API auth gate.
|
|
2
|
+
import { promises as fs } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const json = (body: unknown, status = 200) =>
|
|
6
|
+
new Response(JSON.stringify(body), {
|
|
7
|
+
status,
|
|
8
|
+
headers: { "Content-Type": "application/json" },
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
// The chat page shows this next to the app title; a missing package must not
|
|
12
|
+
// leave a placeholder behind.
|
|
13
|
+
let versionTag: Promise<string> | undefined;
|
|
14
|
+
function chatVersionTag(here: string): Promise<string> {
|
|
15
|
+
return (versionTag ??= fs.readFile(path.join(here, "../package.json"), "utf8")
|
|
16
|
+
.then((text) => {
|
|
17
|
+
const pkg = JSON.parse(text) as { version?: unknown };
|
|
18
|
+
return typeof pkg?.version === "string" && pkg.version ? `v${pkg.version}` : "";
|
|
19
|
+
})
|
|
20
|
+
.catch(() => ""));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function pageRoutes(
|
|
24
|
+
req: Request,
|
|
25
|
+
url: URL,
|
|
26
|
+
here: string,
|
|
27
|
+
channeld: boolean,
|
|
28
|
+
): Promise<Response | undefined> {
|
|
29
|
+
const p = url.pathname;
|
|
30
|
+
if (req.method === "GET" && p === "/") {
|
|
31
|
+
return Response.redirect(new URL("/chat", url).toString(), 302);
|
|
32
|
+
}
|
|
33
|
+
if (req.method === "GET" && p === "/chat") {
|
|
34
|
+
const html = await fs
|
|
35
|
+
.readFile(path.join(here, "chat.html"), "utf8")
|
|
36
|
+
.catch(() => null);
|
|
37
|
+
if (html === null) {
|
|
38
|
+
return json({ error: "chat page not found" }, 404);
|
|
39
|
+
}
|
|
40
|
+
const version = await chatVersionTag(here);
|
|
41
|
+
return new Response(html.replaceAll("{{version}}", version)
|
|
42
|
+
.replaceAll("{{channeld}}", channeld ? "on" : "off")
|
|
43
|
+
.replaceAll("{{integrationsAdmin}}", process.env.CHATROOM_ALLOW_ADMIN === "true" ? "true" : "false"), {
|
|
44
|
+
headers: {
|
|
45
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
46
|
+
"Cache-Control": "no-store",
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
// The install surface lives at the origin root so the worker controls /chat, not /assets.
|
|
51
|
+
if (req.method === "GET" && p === "/manifest.webmanifest") {
|
|
52
|
+
const body = await fs.readFile(path.join(here, "manifest.webmanifest"), "utf8").catch(() => null);
|
|
53
|
+
if (body === null) return json({ error: "manifest not found" }, 404);
|
|
54
|
+
return new Response(body, {
|
|
55
|
+
headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-store" },
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (req.method === "GET" && p === "/sw.js") {
|
|
59
|
+
const body = await fs.readFile(path.join(here, "sw.js"), "utf8").catch(() => null);
|
|
60
|
+
if (body === null) return json({ error: "service worker not found" }, 404);
|
|
61
|
+
const version = (await chatVersionTag(here)) || "dev";
|
|
62
|
+
return new Response(body.replaceAll("{{version}}", version), {
|
|
63
|
+
headers: {
|
|
64
|
+
"Content-Type": "text/javascript; charset=utf-8",
|
|
65
|
+
"Cache-Control": "no-store",
|
|
66
|
+
"Service-Worker-Allowed": "/",
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
if (req.method === "GET" && p.startsWith("/assets/")) {
|
|
71
|
+
let relative: string;
|
|
72
|
+
try { relative = decodeURIComponent(p.slice("/assets/".length)); }
|
|
73
|
+
catch { return json({ error: "invalid asset path" }, 400); }
|
|
74
|
+
const root = path.resolve(here, "assets");
|
|
75
|
+
const file = path.resolve(root, relative);
|
|
76
|
+
if (!relative || !file.startsWith(`${root}${path.sep}`) || !/\.(?:css|js|mjs|svg|png|jpg|ttf|woff2?)$/i.test(file)) return json({ error: "not found" }, 404);
|
|
77
|
+
const data = await fs.readFile(file).catch(() => null);
|
|
78
|
+
if (!data) return json({ error: "not found" }, 404);
|
|
79
|
+
const type = file.endsWith(".css") ? "text/css" : file.endsWith(".svg") ? "image/svg+xml" : /\.(?:js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".png") ? "image/png" : file.endsWith(".jpg") ? "image/jpeg" : file.endsWith(".ttf") ? "font/ttf" : "font/woff2";
|
|
80
|
+
return new Response(data, { headers: { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
|
|
81
|
+
}
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Room question listing and answer submission.
|
|
2
|
+
import { answerQuestion, readQuestions, readState } from "../../src/state/store.ts";
|
|
3
|
+
import { touchActive, wakeMentionedSessions } from "../wake.ts";
|
|
4
|
+
|
|
5
|
+
const json = (body: unknown, status = 200) =>
|
|
6
|
+
new Response(JSON.stringify(body), {
|
|
7
|
+
status,
|
|
8
|
+
headers: { "Content-Type": "application/json" },
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
export async function questionRoutes(req: Request, url: URL, serveWakeUrl: string): Promise<Response | undefined> {
|
|
12
|
+
const questions = url.pathname.match(/^\/rooms\/([^/]+)\/questions$/);
|
|
13
|
+
if (req.method === "GET" && questions) {
|
|
14
|
+
const roomId = decodeURIComponent(questions[1]!);
|
|
15
|
+
const exists = await readState((svc) => svc.listRooms().some((room) => room.id === roomId));
|
|
16
|
+
if (!exists) return json({ error: "room not found" }, 404);
|
|
17
|
+
return json({ questions: await readQuestions(roomId) });
|
|
18
|
+
}
|
|
19
|
+
const answer = url.pathname.match(/^\/rooms\/([^/]+)\/questions\/([^/]+)\/answers$/);
|
|
20
|
+
if (req.method === "POST" && answer) {
|
|
21
|
+
const roomId = decodeURIComponent(answer[1]!);
|
|
22
|
+
const questionID = decodeURIComponent(answer[2]!);
|
|
23
|
+
const body: unknown = await req.json();
|
|
24
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return json({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
|
|
25
|
+
const input = body as Record<string, unknown>;
|
|
26
|
+
if (typeof input.sessionID !== "string" || !input.sessionID || typeof input.text !== "string" || !input.text.trim() || input.text.trim().length > 5000) return json({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
|
|
27
|
+
const result = await answerQuestion(roomId, questionID, input.sessionID, input.text.trim());
|
|
28
|
+
if (result.status === "missing") return json({ error: "room not found" }, 404);
|
|
29
|
+
if (result.status === "question") return json({ error: "question not found" }, 404);
|
|
30
|
+
if (result.status === "member") return json({ error: "session is not a room member" }, 409);
|
|
31
|
+
if (result.status === "answered") return json({ error: "question already answered" }, 409);
|
|
32
|
+
if (result.status !== "ok") return json({ error: "question not found" }, 404);
|
|
33
|
+
touchActive(input.sessionID);
|
|
34
|
+
const room = await readState((svc) => svc.getRoom(roomId));
|
|
35
|
+
void wakeMentionedSessions(serveWakeUrl, roomId, room.name, result.answer.text, input.sessionID, result.answer);
|
|
36
|
+
return json({ questionID, answer: result.answer }, 201);
|
|
37
|
+
}
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Join, leave and message append routes for a single room.
|
|
2
|
+
import { appendRoomMessage, databasePath, readState, sendReply, writeState } from "../../src/state/store.ts";
|
|
3
|
+
import { saveJoinRequest, writeSqliteStateWithDatabase } from "../../src/state/sqlite-state.ts";
|
|
4
|
+
import { isReceiverOwnerID } from "../../src/state/receiver-owner.ts";
|
|
5
|
+
import { jsonObject } from "../json-body.ts";
|
|
6
|
+
import { isUser, settleAdmins, settleOwner } from "../room-owner.ts";
|
|
7
|
+
import { joinRoomMember } from "../room-join.ts";
|
|
8
|
+
import { roomPayload } from "../room-payload.ts";
|
|
9
|
+
import { touchActive, wakeMentionedSessions } from "../wake.ts";
|
|
10
|
+
|
|
11
|
+
const json = (body: unknown, status = 200) =>
|
|
12
|
+
new Response(JSON.stringify(body), {
|
|
13
|
+
status,
|
|
14
|
+
headers: { "Content-Type": "application/json" },
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export async function roomActionRoutes(req: Request, url: URL, serveWakeUrl: string): Promise<Response | undefined> {
|
|
18
|
+
const m = url.pathname.match(/^\/rooms\/([^/]+)\/(join|leave|messages)$/);
|
|
19
|
+
if (!m) return undefined;
|
|
20
|
+
const roomId = decodeURIComponent(m[1]!);
|
|
21
|
+
const body = await jsonObject<Record<string, string>>(req);
|
|
22
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
23
|
+
const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
24
|
+
if (req.method === "POST" && m[2] === "join") {
|
|
25
|
+
if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
|
|
26
|
+
return json({ error: "invalid receiver ownership" }, 400);
|
|
27
|
+
}
|
|
28
|
+
// ponytail: F4/F5 — names must be non-empty, and re-joining under a
|
|
29
|
+
// new name must retire the old participant (no ghost members)
|
|
30
|
+
const id = typeof body.participantId === "string" ? body.participantId.trim() : "";
|
|
31
|
+
const name = typeof body.participantName === "string" ? body.participantName.trim() : "";
|
|
32
|
+
if (!id || !name || !sessionID) {
|
|
33
|
+
return json(
|
|
34
|
+
{ error: "participantId/participantName/sessionID are required" },
|
|
35
|
+
400,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
if (id.length > 64 || name.length > 64) {
|
|
39
|
+
return json({ error: "name too long (max 64)" }, 400);
|
|
40
|
+
}
|
|
41
|
+
const result = await writeSqliteStateWithDatabase(databasePath(), (svc, reg, db) => {
|
|
42
|
+
const currentRoom = svc.getRoom(roomId);
|
|
43
|
+
// A restricted room treats a new identity as a pending request; no
|
|
44
|
+
// participant or registry entry exists until a reviewer approves.
|
|
45
|
+
if (currentRoom.joinPolicy === "approval" && currentRoom.kind !== "direct" && !reg[roomId]?.[sessionID]) {
|
|
46
|
+
if (svc.containsParticipant(roomId, id)) return { status: 409 as const, error: "participant name is already in use in this room" };
|
|
47
|
+
const duplicate = db.query("SELECT 1 FROM room_join_requests WHERE room_id=? AND session_id<>? AND (participant_id=? OR name=?)").get(roomId, sessionID, id, name);
|
|
48
|
+
if (duplicate) return { status: 409 as const, error: "participant name is already in use in this room" };
|
|
49
|
+
saveJoinRequest(db, {
|
|
50
|
+
roomID: roomId, sessionID, participantId: id, name,
|
|
51
|
+
isAgent: Boolean(body.protocol || body.receiverOwnerID || body.host),
|
|
52
|
+
createdAt: Date.now(),
|
|
53
|
+
...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
|
|
54
|
+
...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
|
|
55
|
+
...(body.directory ? { directory: body.directory } : {}),
|
|
56
|
+
...(body.host ? { host: body.host } : {}),
|
|
57
|
+
});
|
|
58
|
+
return { pending: true as const };
|
|
59
|
+
}
|
|
60
|
+
return { room: joinRoomMember(svc, reg, roomId, {
|
|
61
|
+
sessionID, participantId: id, name,
|
|
62
|
+
...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
|
|
63
|
+
...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
|
|
64
|
+
...(body.directory ? { directory: body.directory } : {}),
|
|
65
|
+
host: body.host ?? "",
|
|
66
|
+
}) };
|
|
67
|
+
});
|
|
68
|
+
if ("status" in result) return json({ error: result.error }, result.status);
|
|
69
|
+
if ("pending" in result) return json({
|
|
70
|
+
status: "pending",
|
|
71
|
+
message: "Join request submitted. You are not a member yet; a human administrator must approve it before you can send or poll.",
|
|
72
|
+
}, 202);
|
|
73
|
+
touchActive(sessionID); // join = active
|
|
74
|
+
return json(await roomPayload(result.room), 201);
|
|
75
|
+
}
|
|
76
|
+
if (req.method === "POST" && m[2] === "leave") {
|
|
77
|
+
await writeState((svc, reg) => {
|
|
78
|
+
const room = svc.getRoom(roomId);
|
|
79
|
+
const entry = reg[roomId]?.[sessionID];
|
|
80
|
+
const participantId = room.kind === "direct" ? sessionID : entry?.name ?? sessionID;
|
|
81
|
+
// Shared-name guard: when another session still holds this name, remove
|
|
82
|
+
// only this registry entry, not the participant (otherwise a sibling tab
|
|
83
|
+
// would start getting NOT_JOINED).
|
|
84
|
+
const shared = Object.entries(reg[roomId] ?? {}).some(
|
|
85
|
+
([sid, e]) => e.name === participantId && sid !== sessionID,
|
|
86
|
+
);
|
|
87
|
+
if (!shared) {
|
|
88
|
+
svc.leaveRoom(roomId, participantId);
|
|
89
|
+
svc.addEvent(roomId, `${participantId} left the room`);
|
|
90
|
+
}
|
|
91
|
+
if (reg[roomId]) {
|
|
92
|
+
delete reg[roomId][sessionID];
|
|
93
|
+
if (Object.keys(reg[roomId]).length === 0) {
|
|
94
|
+
delete reg[roomId];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// A departing delegated admin passes the role to the room's explicit successor.
|
|
98
|
+
if (entry?.name && room.ownerId && (room.adminIds ?? []).includes(entry.name)) {
|
|
99
|
+
const successor = Object.values(reg[roomId] ?? {}).find((candidate) =>
|
|
100
|
+
isUser(candidate) && (room.successorMembershipID ? candidate.membershipID === room.successorMembershipID : candidate.name === room.successorId));
|
|
101
|
+
if (successor?.name && successor.name !== room.ownerId) {
|
|
102
|
+
room.adminIds = [...new Set([...(room.adminIds ?? []).filter((name) => name !== successor.name), successor.name])];
|
|
103
|
+
if (successor.membershipID) room.adminMembershipIDs = [...new Set([...(room.adminMembershipIDs ?? []).filter((id) => id !== successor.membershipID), successor.membershipID])];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (entry && (room.successorMembershipID ? entry.membershipID === room.successorMembershipID : entry.name === room.successorId)) {
|
|
107
|
+
delete room.successorId;
|
|
108
|
+
delete room.successorMembershipID;
|
|
109
|
+
}
|
|
110
|
+
// A departing owner hands the room to the next person; the last one leaves it open.
|
|
111
|
+
settleAdmins(svc.getRoom(roomId), reg[roomId] ?? {});
|
|
112
|
+
settleOwner(svc.getRoom(roomId), reg[roomId] ?? {});
|
|
113
|
+
});
|
|
114
|
+
return json({ ok: true });
|
|
115
|
+
}
|
|
116
|
+
if (req.method === "POST" && m[2] === "messages") {
|
|
117
|
+
const isQuestion = (body as Record<string, unknown>).isQuestion;
|
|
118
|
+
if (isQuestion !== undefined && typeof isQuestion !== "boolean") return json({ error: "isQuestion must be a boolean" }, 400);
|
|
119
|
+
// ponytail: F3 — mirror the plugin's zod limit at the HTTP boundary
|
|
120
|
+
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
121
|
+
if (!text) {
|
|
122
|
+
return json({ error: "text is required" }, 400);
|
|
123
|
+
}
|
|
124
|
+
if (text.length > 5000) {
|
|
125
|
+
return json({ error: "text too long (max 5000)" }, 400);
|
|
126
|
+
}
|
|
127
|
+
// parentMessageId is the addressing alias of the web client's reply field.
|
|
128
|
+
const replyTo = (body as Record<string, unknown>).replyToMessageID ?? (body as Record<string, unknown>).parentMessageId;
|
|
129
|
+
if (replyTo !== undefined && (typeof replyTo !== "string" || !replyTo)) return json({ error: "parentMessageId must be a non-empty message ID" }, 400);
|
|
130
|
+
// Optional retry key: a lost response may be retried without creating a twin.
|
|
131
|
+
const clientMessageID = (body as Record<string, unknown>).clientMessageID;
|
|
132
|
+
if (clientMessageID !== undefined && (typeof clientMessageID !== "string" || !clientMessageID || clientMessageID.length > 100)) {
|
|
133
|
+
return json({ error: "clientMessageID must be a non-empty string (max 100)" }, 400);
|
|
134
|
+
}
|
|
135
|
+
if (replyTo !== undefined) {
|
|
136
|
+
const result = await sendReply(roomId, replyTo, sessionID, text, clientMessageID);
|
|
137
|
+
if (result.status !== "ok") {
|
|
138
|
+
if (result.status === "missing") return json({ error: "room not found" }, 404);
|
|
139
|
+
if (result.status === "target") return json({ error: "reply target not found in room" }, 404);
|
|
140
|
+
if (result.status === "recalled") return json({ error: "reply target was recalled" }, 409);
|
|
141
|
+
if (result.status === "question") return json({ error: "use the question answers endpoint to reply to a question" }, 409);
|
|
142
|
+
// Reply addressing is member-only and uniformly missing otherwise.
|
|
143
|
+
return json({ error: "not found" }, 404);
|
|
144
|
+
}
|
|
145
|
+
touchActive(sessionID);
|
|
146
|
+
const room = await readState((svc) => svc.getRoom(roomId));
|
|
147
|
+
if (!result.duplicate) void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
|
|
148
|
+
return json(await roomPayload(room), 201);
|
|
149
|
+
}
|
|
150
|
+
const result = await appendRoomMessage(roomId, sessionID, text, isQuestion === true, clientMessageID);
|
|
151
|
+
if (result.status !== "ok") {
|
|
152
|
+
if (result.status === "missing") return json({ error: "room not found" }, 404);
|
|
153
|
+
return json({ error: "session is not a room member" }, 409);
|
|
154
|
+
}
|
|
155
|
+
touchActive(sessionID); // sender is active
|
|
156
|
+
const room = await readState((svc) => svc.getRoom(roomId));
|
|
157
|
+
// Immediate wake only when the message explicitly @-mentions members.
|
|
158
|
+
if (!result.duplicate) void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
|
|
159
|
+
return json(await roomPayload(room), 201);
|
|
160
|
+
}
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Room listing, creation, room snapshots and the session registry.
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { readRoomSummaries, readState, writeState, type RegistryEntry } from "../../src/state/store.ts";
|
|
4
|
+
import { isReceiverOwnerID } from "../../src/state/receiver-owner.ts";
|
|
5
|
+
import { jsonObject } from "../json-body.ts";
|
|
6
|
+
import { roomPayload } from "../room-payload.ts";
|
|
7
|
+
|
|
8
|
+
const json = (body: unknown, status = 200) =>
|
|
9
|
+
new Response(JSON.stringify(body), {
|
|
10
|
+
status,
|
|
11
|
+
headers: { "Content-Type": "application/json" },
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
// Only canonical non-negative decimal integers are accepted; URLSearchParams
|
|
15
|
+
// keeps values as strings, so "1.5", "1e2" and "" must not be coerced.
|
|
16
|
+
const integerParam = (value: string): number | undefined => {
|
|
17
|
+
if (!/^\d+$/.test(value)) return undefined;
|
|
18
|
+
const parsed = Number(value);
|
|
19
|
+
return Number.isSafeInteger(parsed) ? parsed : undefined;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export async function roomListRoutes(req: Request, url: URL): Promise<Response | undefined> {
|
|
23
|
+
const p = url.pathname;
|
|
24
|
+
if (req.method === "GET" && p === "/rooms/summary") {
|
|
25
|
+
// Lightweight room summary without messages: wakeSessions polls this every
|
|
26
|
+
// 10s to compute the latest sequence without downloading full histories.
|
|
27
|
+
return json(await readRoomSummaries());
|
|
28
|
+
}
|
|
29
|
+
if (req.method === "GET" && p === "/receiver/memberships") {
|
|
30
|
+
const ownerID = url.searchParams.get("ownerID");
|
|
31
|
+
if (!isReceiverOwnerID(ownerID)) return json({ error: "invalid ownerID" }, 400);
|
|
32
|
+
const sessionIDs = await readState((_svc, registry) => {
|
|
33
|
+
return [...new Set(Object.values(registry).flatMap((entries) =>
|
|
34
|
+
Object.entries(entries).filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id),
|
|
35
|
+
))];
|
|
36
|
+
});
|
|
37
|
+
return json({ sessionIDs });
|
|
38
|
+
}
|
|
39
|
+
if (req.method === "GET" && p === "/rooms") {
|
|
40
|
+
const caller = url.searchParams.get("sessionID");
|
|
41
|
+
const limitParam = url.searchParams.get("limit");
|
|
42
|
+
const offsetParam = url.searchParams.get("offset");
|
|
43
|
+
// No page size with an offset; reject rather than silently ignoring it.
|
|
44
|
+
if (limitParam === null && offsetParam !== null) return json({ error: "offset requires limit" }, 400);
|
|
45
|
+
let limit: number | undefined;
|
|
46
|
+
let offset = 0;
|
|
47
|
+
if (limitParam !== null) {
|
|
48
|
+
limit = integerParam(limitParam);
|
|
49
|
+
if (limit === undefined || limit < 1 || limit > 200) return json({ error: "limit must be an integer between 1 and 200" }, 400);
|
|
50
|
+
if (offsetParam !== null) {
|
|
51
|
+
offset = integerParam(offsetParam) ?? -1;
|
|
52
|
+
if (offset < 0) return json({ error: "offset must be a non-negative integer" }, 400);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const rows = await readState((svc, registry) => svc.listRooms()
|
|
56
|
+
.filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller))
|
|
57
|
+
.map((room) => ({ room, entry: caller ? registry[room.id]?.[caller] : undefined })));
|
|
58
|
+
// Without limit keep the legacy bare array and full list; with limit only
|
|
59
|
+
// hydrate the room payloads on the requested page.
|
|
60
|
+
const page = limit === undefined ? rows : rows.slice(offset, offset + limit);
|
|
61
|
+
const rooms = [];
|
|
62
|
+
for (const { room, entry } of page) {
|
|
63
|
+
// The browser keeps its watermark per tab; a new tab starts from this one.
|
|
64
|
+
rooms.push({ ...await roomPayload(room), joined: Boolean(entry), ...(entry?.lastReadTs ? { lastReadTs: entry.lastReadTs } : {}) });
|
|
65
|
+
}
|
|
66
|
+
if (limit === undefined) return json(rooms);
|
|
67
|
+
const nextOffset = offset + rooms.length < rows.length ? offset + rooms.length : null;
|
|
68
|
+
return json({ rooms, hasMore: nextOffset !== null, nextOffset });
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function roomCreateRoute(req: Request, url: URL): Promise<Response | undefined> {
|
|
74
|
+
if (!(req.method === "POST" && url.pathname === "/rooms")) return undefined;
|
|
75
|
+
const body = await jsonObject<Record<string, string>>(req);
|
|
76
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
77
|
+
if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
|
|
78
|
+
return json({ error: "invalid receiver ownership" }, 400);
|
|
79
|
+
}
|
|
80
|
+
const name = body.name?.trim();
|
|
81
|
+
if (!name) {
|
|
82
|
+
return json({ error: "name is required" }, 400);
|
|
83
|
+
}
|
|
84
|
+
if (name.length > 64) {
|
|
85
|
+
return json({ error: "name too long (max 64)" }, 400);
|
|
86
|
+
}
|
|
87
|
+
const owner = (body.ownerId ?? "").trim() || "访客";
|
|
88
|
+
if (owner.length > 64) {
|
|
89
|
+
return json({ error: "ownerId too long (max 64)" }, 400);
|
|
90
|
+
}
|
|
91
|
+
if (body.joinPolicy !== undefined && body.joinPolicy !== "open" && body.joinPolicy !== "approval") {
|
|
92
|
+
return json({ error: "joinPolicy must be open or approval" }, 400);
|
|
93
|
+
}
|
|
94
|
+
const joinPolicy = body.joinPolicy === "approval" ? "approval" : body.joinPolicy === "open" ? "open" : undefined;
|
|
95
|
+
const room = await writeState((svc, reg) => {
|
|
96
|
+
const created = svc.createRoom(name, owner, joinPolicy);
|
|
97
|
+
if (body.sessionID) {
|
|
98
|
+
const regRoom = (reg[created.id] =
|
|
99
|
+
reg[created.id] ?? Object.create(null) as Record<string, RegistryEntry>);
|
|
100
|
+
regRoom[body.sessionID] = {
|
|
101
|
+
// ponytail: central mode self-pulls the inbox; no cross-host URL
|
|
102
|
+
serverUrl: "",
|
|
103
|
+
apiPrefix: "/api",
|
|
104
|
+
membershipID: randomUUID(),
|
|
105
|
+
...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
|
|
106
|
+
...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
|
|
107
|
+
name: owner,
|
|
108
|
+
directory: body.directory || undefined,
|
|
109
|
+
// Owning host: cross-machine @-wake is executed only by the owner.
|
|
110
|
+
host: body.host ?? "",
|
|
111
|
+
lastReadTs: Math.max(
|
|
112
|
+
Date.now(),
|
|
113
|
+
created.messages.at(-1)?.createdAt ?? 0,
|
|
114
|
+
),
|
|
115
|
+
lastQueuedTs: 0,
|
|
116
|
+
};
|
|
117
|
+
created.ownerMembershipID = regRoom[body.sessionID]!.membershipID;
|
|
118
|
+
}
|
|
119
|
+
return created;
|
|
120
|
+
});
|
|
121
|
+
return json(await roomPayload(room), 201);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function roomDetailRoutes(req: Request, url: URL): Promise<Response | undefined> {
|
|
125
|
+
const g = url.pathname.match(/^\/rooms\/([^/]+)$/);
|
|
126
|
+
if (g && req.method === "GET") {
|
|
127
|
+
const room = await readState((svc) =>
|
|
128
|
+
svc.getRoom(decodeURIComponent(g[1]!)),
|
|
129
|
+
);
|
|
130
|
+
return json(await roomPayload(room));
|
|
131
|
+
}
|
|
132
|
+
const r = url.pathname.match(/^\/rooms\/([^/]+)\/registry$/);
|
|
133
|
+
if (r && req.method === "GET") {
|
|
134
|
+
// ponytail: session registry for the in-plugin wake watcher — lets the
|
|
135
|
+
// plugin find which sessions have unread messages without polling every
|
|
136
|
+
// session's inbox; host is included for the @-wake ownership gate
|
|
137
|
+
const roomId = decodeURIComponent(r[1]!);
|
|
138
|
+
const reg = await readState((svc, registry) => {
|
|
139
|
+
const entries = registry[roomId] ?? {};
|
|
140
|
+
return Object.fromEntries(
|
|
141
|
+
Object.entries(entries).map(([sid, e]) => [
|
|
142
|
+
sid,
|
|
143
|
+
{
|
|
144
|
+
name: e.name,
|
|
145
|
+
membershipID: e.membershipID,
|
|
146
|
+
protocol: e.protocol,
|
|
147
|
+
receiverOwnerID: e.receiverOwnerID,
|
|
148
|
+
lastReadTs: e.lastReadTs ?? 0,
|
|
149
|
+
lastQueuedTs: e.lastQueuedTs ?? 0,
|
|
150
|
+
host: e.host ?? "",
|
|
151
|
+
directory: e.directory,
|
|
152
|
+
roomKind: svc.getRoom(roomId).kind ?? "group",
|
|
153
|
+
},
|
|
154
|
+
]),
|
|
155
|
+
);
|
|
156
|
+
});
|
|
157
|
+
return json(reg);
|
|
158
|
+
}
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|