@alexsun-top/opencode-chat-room 0.8.2 → 0.8.3

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.
Files changed (92) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +466 -188
  5. package/package.json +8 -5
  6. package/packages/chat-room-channeld/README.md +25 -3
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +5 -0
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +17 -2
  11. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  12. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  13. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  14. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  15. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  16. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  17. package/packages/chat-room-channeld/src/protocol.ts +1 -0
  18. package/packages/chat-room-channeld/src/state.ts +73 -97
  19. package/packages/chat-room-channeld/src/stats.ts +140 -109
  20. package/server/assets/base.css +3 -1
  21. package/server/assets/chat/admin-badge.js +32 -30
  22. package/server/assets/chat/admin.js +198 -161
  23. package/server/assets/chat/announcements.js +295 -208
  24. package/server/assets/chat/attachment-store.js +106 -75
  25. package/server/assets/chat/attachments.js +686 -441
  26. package/server/assets/chat/chat-background.js +185 -156
  27. package/server/assets/chat/clipboard.js +44 -25
  28. package/server/assets/chat/confirm-dialog.js +36 -33
  29. package/server/assets/chat/copy-action.js +40 -40
  30. package/server/assets/chat/create-room-dialog.js +50 -47
  31. package/server/assets/chat/diagram-viewer.js +293 -234
  32. package/server/assets/chat/doc-preview.js +507 -441
  33. package/server/assets/chat/editor.js +423 -335
  34. package/server/assets/chat/events.js +637 -510
  35. package/server/assets/chat/files.js +476 -430
  36. package/server/assets/chat/history-loader.js +79 -73
  37. package/server/assets/chat/icons.js +9 -11
  38. package/server/assets/chat/image-zoom.js +239 -176
  39. package/server/assets/chat/index.js +2 -3
  40. package/server/assets/chat/install-prompt.js +86 -66
  41. package/server/assets/chat/integration-account-schema.js +88 -86
  42. package/server/assets/chat/integration-editor.js +162 -153
  43. package/server/assets/chat/integration-values.js +109 -100
  44. package/server/assets/chat/integrations.js +689 -622
  45. package/server/assets/chat/join-requests.js +408 -358
  46. package/server/assets/chat/locales/de.js +193 -194
  47. package/server/assets/chat/locales/es.js +193 -194
  48. package/server/assets/chat/locales/fr.js +193 -194
  49. package/server/assets/chat/locales/index.js +1 -2
  50. package/server/assets/chat/locales/it.js +193 -194
  51. package/server/assets/chat/locales/ja.js +193 -193
  52. package/server/assets/chat/locales/ko.js +193 -193
  53. package/server/assets/chat/markdown-footnotes.js +134 -102
  54. package/server/assets/chat/markdown.js +547 -403
  55. package/server/assets/chat/members.js +236 -197
  56. package/server/assets/chat/mentions.js +157 -133
  57. package/server/assets/chat/message-cache.js +40 -33
  58. package/server/assets/chat/message-polling.js +280 -227
  59. package/server/assets/chat/message-window.js +74 -55
  60. package/server/assets/chat/messages.js +552 -480
  61. package/server/assets/chat/office-preview.js +46 -45
  62. package/server/assets/chat/palette.js +450 -417
  63. package/server/assets/chat/panels.js +94 -78
  64. package/server/assets/chat/pwa.js +144 -73
  65. package/server/assets/chat/questions.js +372 -302
  66. package/server/assets/chat/recall.js +320 -273
  67. package/server/assets/chat/receipts.js +149 -121
  68. package/server/assets/chat/reminders.js +331 -214
  69. package/server/assets/chat/replies.js +165 -130
  70. package/server/assets/chat/resource-format.js +59 -62
  71. package/server/assets/chat/room-list.js +58 -55
  72. package/server/assets/chat/room-watcher.js +72 -50
  73. package/server/assets/chat/rooms.js +623 -500
  74. package/server/assets/chat/search.js +136 -114
  75. package/server/assets/chat/settings.js +223 -200
  76. package/server/assets/chat/shiki.js +61 -62
  77. package/server/assets/chat/shortcuts.js +212 -187
  78. package/server/assets/chat/side-pane.js +160 -150
  79. package/server/assets/chat/state.js +849 -735
  80. package/server/assets/chat/system-events.js +45 -43
  81. package/server/assets/chat/system-messages.js +57 -56
  82. package/server/assets/chat/task-form.js +178 -182
  83. package/server/assets/chat/task-row.js +158 -155
  84. package/server/assets/chat/tasks.js +653 -587
  85. package/server/assets/chat/viewport.js +32 -29
  86. package/server/assets/chat/window-controls.js +32 -32
  87. package/server/assets/conversation.css +10 -4
  88. package/server/chat-server.ts +9 -1
  89. package/server/chat.html +2 -1
  90. package/server/routes/pages.ts +7 -5
  91. package/server/sw.js +346 -268
  92. package/src/web/integration-rules-editor.ts +2 -0
@@ -0,0 +1,60 @@
1
+ import type { StateDatabase } from "./sqlite.ts";
2
+
3
+ export const SCHEMA = `
4
+ CREATE TABLE IF NOT EXISTS channel_events (
5
+ event_id TEXT PRIMARY KEY,
6
+ dedup_key TEXT NOT NULL UNIQUE,
7
+ payload TEXT NOT NULL,
8
+ ingress_seq INTEGER,
9
+ committed_at INTEGER NOT NULL
10
+ );
11
+ CREATE TABLE IF NOT EXISTS channel_deliveries (
12
+ delivery_id TEXT PRIMARY KEY,
13
+ event_id TEXT NOT NULL,
14
+ rule_id TEXT NOT NULL,
15
+ rule_version INTEGER NOT NULL,
16
+ target TEXT NOT NULL,
17
+ idempotency_key TEXT NOT NULL UNIQUE,
18
+ payload TEXT NOT NULL,
19
+ state TEXT NOT NULL,
20
+ attempt_count INTEGER NOT NULL DEFAULT 0,
21
+ next_attempt_at INTEGER,
22
+ last_error TEXT,
23
+ provider_message TEXT,
24
+ created_at INTEGER NOT NULL,
25
+ updated_at INTEGER NOT NULL
26
+ );
27
+ CREATE TABLE IF NOT EXISTS channel_receipts (
28
+ receipt_id TEXT PRIMARY KEY,
29
+ delivery_id TEXT NOT NULL,
30
+ attempt_id TEXT NOT NULL,
31
+ state TEXT NOT NULL,
32
+ provider_message TEXT,
33
+ detail TEXT,
34
+ observed_at INTEGER NOT NULL
35
+ );
36
+ CREATE TABLE IF NOT EXISTS channel_echoes (
37
+ endpoint TEXT NOT NULL,
38
+ native_message_id TEXT NOT NULL,
39
+ logical_message_id TEXT NOT NULL,
40
+ delivery_id TEXT,
41
+ created_at INTEGER NOT NULL DEFAULT 0,
42
+ PRIMARY KEY (endpoint, native_message_id)
43
+ );
44
+ `;
45
+
46
+ /** Create tables, add missing columns, and backfill legacy echo order from rowid. */
47
+ export function initializeChannelSchema(
48
+ db: StateDatabase,
49
+ options: { backfillEchoOrder?: boolean } = {},
50
+ ): void {
51
+ db.exec(SCHEMA);
52
+ const columns = db.query("PRAGMA table_info(channel_echoes)").all() as Array<{ name?: unknown }>;
53
+ if (!columns.some((column) => column.name === "created_at")) {
54
+ db.exec("ALTER TABLE channel_echoes ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0");
55
+ }
56
+ if (options.backfillEchoOrder) {
57
+ // Legacy rows predate created_at; rowid keeps their original insertion order.
58
+ db.exec("UPDATE channel_echoes SET created_at = rowid WHERE created_at = 0");
59
+ }
60
+ }
@@ -0,0 +1,175 @@
1
+ // SQLite -> PostgreSQL translation for the chat-room state SQL. The app's SQL
2
+ // uses ? placeholders, SQLite DDL, a few pragmas and a handful of scalar
3
+ // functions; everything else is deliberately passed through unchanged.
4
+ //
5
+ // This is intentionally not a general SQLite translator. Keep the dialect
6
+ // narrow and add a test when the state layer starts using a new construct.
7
+
8
+ const PRAGMA_TABLE_INFO = /PRAGMA\s+table_info\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)/gi;
9
+
10
+ function pragmaTableInfo(table) {
11
+ const tableName = table.replace(/'/g, "''");
12
+ return `SELECT c.column_name AS name,c.data_type AS type,` +
13
+ `CASE WHEN c.is_nullable='NO' THEN 1 ELSE 0 END AS "notnull",` +
14
+ `c.column_default AS dflt_value,` +
15
+ `CASE WHEN EXISTS (SELECT 1 FROM pg_index i JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=ANY(i.indkey) ` +
16
+ `WHERE i.indrelid=(quote_ident(c.table_schema)||'.'||quote_ident(c.table_name))::regclass AND i.indisprimary AND a.attname=c.column_name) ` +
17
+ `THEN 1 ELSE 0 END AS pk ` +
18
+ `FROM information_schema.columns c WHERE c.table_schema=current_schema() AND c.table_name='${tableName}' ORDER BY c.ordinal_position`;
19
+ }
20
+
21
+ const isIdentStart = (ch) => !!ch && /[A-Za-z_]/.test(ch);
22
+ const isIdentChar = (ch) => !!ch && /[A-Za-z0-9_$]/.test(ch);
23
+
24
+ function skipQuoted(sql, index) {
25
+ const quote = sql[index];
26
+ let i = index + 1;
27
+ while (i < sql.length) {
28
+ if (sql[i] === quote) {
29
+ if (sql[i + 1] === quote) { i += 2; continue; }
30
+ return i + 1;
31
+ }
32
+ i++;
33
+ }
34
+ return i;
35
+ }
36
+
37
+ function skipComment(sql, index) {
38
+ if (sql[index + 1] === "-") {
39
+ const end = sql.indexOf("\n", index + 2);
40
+ return end < 0 ? sql.length : end;
41
+ }
42
+ const end = sql.indexOf("*/", index + 2);
43
+ return end < 0 ? sql.length : end + 2;
44
+ }
45
+
46
+ function hasTopLevelComma(sql, openIndex) {
47
+ let depth = 0;
48
+ for (let i = openIndex; i < sql.length; i++) {
49
+ const ch = sql[i];
50
+ if (ch === "'" || ch === '"') { i = skipQuoted(sql, i) - 1; continue; }
51
+ if (ch === "-" && sql[i + 1] === "-") { i = skipComment(sql, i) - 1; continue; }
52
+ if (ch === "/" && sql[i + 1] === "*") { i = skipComment(sql, i) - 1; continue; }
53
+ if (ch === "(") depth++;
54
+ else if (ch === ")") { depth--; if (depth === 0) return false; }
55
+ else if (ch === "," && depth === 1) return true;
56
+ }
57
+ return false;
58
+ }
59
+
60
+ function wordBefore(sql, index) {
61
+ let i = index - 1;
62
+ while (i >= 0 && /\s/.test(sql[i])) i--;
63
+ const end = i + 1;
64
+ while (i >= 0 && isIdentChar(sql[i])) i--;
65
+ return sql.slice(i + 1, end).toLowerCase();
66
+ }
67
+
68
+ function wordAfter(sql, index) {
69
+ let i = index + 1;
70
+ while (i < sql.length && /\s/.test(sql[i])) i++;
71
+ const start = i;
72
+ while (i < sql.length && isIdentChar(sql[i])) i++;
73
+ return sql.slice(start, i).toLowerCase();
74
+ }
75
+
76
+ function scan(sql) {
77
+ let out = "";
78
+ let index = 0;
79
+ let parameter = 0;
80
+ while (index < sql.length) {
81
+ const ch = sql[index];
82
+ if (ch === "'" || ch === '"') {
83
+ const end = skipQuoted(sql, index);
84
+ out += sql.slice(index, end);
85
+ index = end;
86
+ continue;
87
+ }
88
+ if (ch === "-" && sql[index + 1] === "-") {
89
+ const end = skipComment(sql, index);
90
+ out += sql.slice(index, end);
91
+ index = end;
92
+ continue;
93
+ }
94
+ if (ch === "/" && sql[index + 1] === "*") {
95
+ const end = skipComment(sql, index);
96
+ out += sql.slice(index, end);
97
+ index = end;
98
+ continue;
99
+ }
100
+ if (ch === "?") {
101
+ // CASE WHEN ? needs a boolean; a bare `? IS NULL` has no type to infer.
102
+ const nextWord = wordAfter(sql, index);
103
+ const cast = (wordBefore(sql, index) === "when" && nextWord === "then") || nextWord === "is";
104
+ out += `$${++parameter}${cast ? (nextWord === "is" ? "::text" : "::boolean") : ""}`;
105
+ index++;
106
+ continue;
107
+ }
108
+ if (isIdentStart(ch)) {
109
+ let end = index + 1;
110
+ while (isIdentChar(sql[end])) end++;
111
+ const word = sql.slice(index, end);
112
+ const lower = word.toLowerCase();
113
+ // SQLite's scalar max(a,b)/min(a,b); the one-argument aggregate forms stay.
114
+ if (lower === "max" || lower === "min") {
115
+ let next = end;
116
+ while (next < sql.length && /\s/.test(sql[next])) next++;
117
+ if (sql[next] === "(" && hasTopLevelComma(sql, next)) {
118
+ out += lower === "max" ? "GREATEST" : "LEAST";
119
+ index = end;
120
+ continue;
121
+ }
122
+ }
123
+ // Preserve camelCase result aliases: PostgreSQL folds unquoted identifiers.
124
+ if (lower === "as") {
125
+ const previous = wordBefore(sql, index);
126
+ let next = end;
127
+ while (next < sql.length && /\s/.test(sql[next])) next++;
128
+ if (isIdentStart(sql[next])) {
129
+ let aliasEnd = next + 1;
130
+ while (isIdentChar(sql[aliasEnd])) aliasEnd++;
131
+ const alias = sql.slice(next, aliasEnd);
132
+ if (/[A-Z]/.test(alias) && previous !== "default" && alias.toLowerCase() !== "identity") {
133
+ out += `AS "${alias}"`;
134
+ index = aliasEnd;
135
+ continue;
136
+ }
137
+ }
138
+ }
139
+ out += word;
140
+ index = end;
141
+ continue;
142
+ }
143
+ out += ch;
144
+ index++;
145
+ }
146
+ return out;
147
+ }
148
+
149
+ function appendOnConflictDoNothing(sql) {
150
+ return `${sql.replace(/[\s;]+$/, "")} ON CONFLICT DO NOTHING`;
151
+ }
152
+
153
+ export function translate(sql) {
154
+ let text = String(sql);
155
+ // Connection tuning pragmas have no PostgreSQL equivalent; foreign keys are
156
+ // always enforced and concurrency is handled by advisory locks.
157
+ text = text.replace(/PRAGMA\s+(?:busy_timeout|journal_mode|foreign_keys)\s*(?:=\s*[^;]+)?\s*;?/gi, "");
158
+ text = text.replace(PRAGMA_TABLE_INFO, (_, table) => pragmaTableInfo(table));
159
+ // SQLite INTEGER is 64-bit; PostgreSQL INTEGER is 32-bit and epoch
160
+ // milliseconds overflow it.
161
+ text = text.replace(/\bINTEGER\b/gi, "BIGINT");
162
+ text = text.replace(/\bBIGINT\s+PRIMARY\s+KEY\s+AUTOINCREMENT\b/gi, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
163
+ // Manual `BEGIN IMMEDIATE` appears inside receiver-state's schema script.
164
+ text = text.replace(/\bBEGIN\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE)\b/gi, "BEGIN");
165
+ if (/\bINSERT\s+OR\s+IGNORE\b/i.test(text)) {
166
+ text = text.replace(/\bINSERT\s+OR\s+IGNORE\b/gi, "INSERT");
167
+ if (!/\bON\s+CONFLICT\b/i.test(text)) text = appendOnConflictDoNothing(text);
168
+ }
169
+ // SQLite treats 1/0 as booleans; PostgreSQL needs an explicit cast.
170
+ return scan(text).trim();
171
+ }
172
+
173
+ export function hasSql(text) {
174
+ return text.replace(/[;\s]/g, "").length > 0;
175
+ }
@@ -0,0 +1,100 @@
1
+ import { DatabaseSync, type StatementSync } from "node:sqlite";
2
+
3
+ // The subset of bun:sqlite that this codebase uses, backed by node:sqlite so the
4
+ // same synchronous driver runs on Node, Bun and Deno.
5
+ export type SQLQueryBindings = null | number | bigint | string | boolean | Uint8Array | undefined;
6
+ export type RunResult = { changes: number; lastInsertRowid: number };
7
+ type RawBindings = Array<null | number | bigint | string | Uint8Array>;
8
+
9
+ // bun:sqlite binds booleans as 1/0 and undefined as NULL; node:sqlite rejects both.
10
+ function bindings(params: SQLQueryBindings[]): RawBindings {
11
+ let values: SQLQueryBindings[] | undefined;
12
+ for (let index = 0; index < params.length; index++) {
13
+ const value = params[index];
14
+ if (value === undefined || typeof value === "boolean") {
15
+ values ??= params.slice();
16
+ values[index] = value === undefined ? null : value ? 1 : 0;
17
+ }
18
+ }
19
+ return (values ?? params) as RawBindings;
20
+ }
21
+
22
+ export class Statement {
23
+ readonly #statement: StatementSync;
24
+ constructor(statement: StatementSync) { this.#statement = statement; }
25
+ all(...params: SQLQueryBindings[]): unknown[] {
26
+ return this.#statement.all(...bindings(params));
27
+ }
28
+ // bun:sqlite returns null for a missing row, node:sqlite returns undefined.
29
+ get(...params: SQLQueryBindings[]): unknown {
30
+ return this.#statement.get(...bindings(params)) ?? null;
31
+ }
32
+ run(...params: SQLQueryBindings[]): RunResult {
33
+ const result = this.#statement.run(...bindings(params));
34
+ return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) };
35
+ }
36
+ }
37
+
38
+ export type Transaction<T> = (() => T) & { deferred(): T; immediate(): T };
39
+
40
+ export type QueryStatement = {
41
+ all(...params: SQLQueryBindings[]): unknown[];
42
+ get(...params: SQLQueryBindings[]): unknown;
43
+ run(...params: SQLQueryBindings[]): RunResult;
44
+ };
45
+
46
+ // The synchronous surface used by the state layer. Implemented by the
47
+ // node:sqlite adapter and by PgDatabase's worker-thread bridge.
48
+ export interface StateDatabase {
49
+ query(sql: string): QueryStatement;
50
+ prepare(sql: string): QueryStatement;
51
+ exec(sql: string): void;
52
+ transaction<T>(fn: () => T): Transaction<T>;
53
+ close(): void;
54
+ }
55
+
56
+ export class Database implements StateDatabase {
57
+ readonly #db: DatabaseSync;
58
+ #savepoints = 0;
59
+
60
+ // node:sqlite always creates a missing file, matching the default Bun options.
61
+ constructor(file: string, options: { readOnly?: boolean } = {}) {
62
+ this.#db = options.readOnly ? new DatabaseSync(file, { readOnly: true }) : new DatabaseSync(file);
63
+ }
64
+
65
+ query(sql: string): Statement { return new Statement(this.#db.prepare(sql)); }
66
+ prepare(sql: string): Statement { return this.query(sql); }
67
+ exec(sql: string): void { this.#db.exec(sql); }
68
+
69
+ transaction<T>(fn: () => T): Transaction<T> {
70
+ const run = (begin: string) => this.#run(begin, fn);
71
+ return Object.assign(() => run("BEGIN"), { deferred: () => run("BEGIN"), immediate: () => run("BEGIN IMMEDIATE") });
72
+ }
73
+
74
+ close(): void { this.#db.close(); }
75
+
76
+ #run<T>(begin: string, fn: () => T): T {
77
+ // Nested calls become savepoints, like bun:sqlite transactions.
78
+ const nested = this.#db.isTransaction;
79
+ const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
80
+ this.#db.exec(nested ? `SAVEPOINT ${savepoint}` : begin);
81
+ try {
82
+ const result = fn();
83
+ this.#db.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
84
+ return result;
85
+ } catch (error) {
86
+ try { this.#db.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK"); } catch { /* keep the original error */ }
87
+ throw error;
88
+ }
89
+ }
90
+ }
91
+
92
+ export function isBusyError(error: unknown): boolean {
93
+ const err = error as { code?: string; errcode?: number; message?: string } | null;
94
+ if (!err) return false;
95
+ // PostgreSQL serialization failure, deadlock, and advisory-lock timeout. The
96
+ // existing immediate() retry loop treats these like SQLITE_BUSY/SQLITE_LOCKED.
97
+ if (err.code === "40001" || err.code === "40P01" || err.code === "55P03") return true;
98
+ if (typeof err.errcode === "number" && ((err.errcode & 0xff) === 5 || (err.errcode & 0xff) === 6)) return true;
99
+ return /SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || /database (?:is|table is) locked/i.test(err.message ?? "");
100
+ }
@@ -0,0 +1,133 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ import pg from "pg";
3
+ import { hasSql, translate } from "./sql.mjs";
4
+
5
+ // One pg.Client per worker: transactions and their advisory locks belong to a
6
+ // single session, so a pool would be incorrect here.
7
+ //
8
+ // The worker deliberately starts with no workerData. Some Bun versions fail to
9
+ // load `pg` in a worker that received any workerData at startup. The main
10
+ // thread sends one init message over the default worker channel instead; that
11
+ // message also transfers the request MessagePort and the ready SharedArrayBuffer.
12
+
13
+ let client;
14
+ let port;
15
+ let readyFlag;
16
+ let statementTimeout = 4_500;
17
+ let connected = false;
18
+ let draining = false;
19
+ let closing = false;
20
+ const queue = [];
21
+
22
+ // SQLite returns all integers as JS numbers; int8 is a string in node-postgres
23
+ // by default and COUNT(*) / BIGINT columns must stay numbers.
24
+ pg.types.setTypeParser(20, (value) => Number(value));
25
+ pg.types.setTypeParser(1700, (value) => Number(value));
26
+
27
+ function normalize(params) {
28
+ return params.map((value) =>
29
+ value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
30
+ }
31
+
32
+ function serialize(error) {
33
+ return {
34
+ name: error?.name,
35
+ message: error?.message ?? String(error),
36
+ code: error?.code,
37
+ detail: error?.detail,
38
+ hint: error?.hint,
39
+ severity: error?.severity,
40
+ position: error?.position,
41
+ constraint: error?.constraint,
42
+ table: error?.table,
43
+ column: error?.column,
44
+ dataType: error?.dataType,
45
+ };
46
+ }
47
+
48
+ function signalReady() {
49
+ Atomics.store(readyFlag, 0, 1);
50
+ Atomics.notify(readyFlag, 0);
51
+ }
52
+
53
+ function reply(request, payload) {
54
+ port.postMessage({ id: request.id, ...payload });
55
+ const flag = new Int32Array(request.signal);
56
+ Atomics.store(flag, 0, 1);
57
+ Atomics.notify(flag, 0);
58
+ }
59
+
60
+ async function handle(request) {
61
+ try {
62
+ const text = translate(request.sql);
63
+ if (!hasSql(text)) return reply(request, { ok: true, rows: [], row: null, changes: 0 });
64
+ const params = normalize(request.params ?? []);
65
+ // exec without params uses the simple-query protocol so multi-statement
66
+ // schema scripts (and BEGIN/COMMIT) run in one round trip.
67
+ const result = request.mode === "exec" && params.length === 0
68
+ ? await client.query(text)
69
+ : await client.query({ text, values: params });
70
+ if (request.mode === "get") return reply(request, { ok: true, row: result.rows?.[0] ?? null });
71
+ if (request.mode === "all") return reply(request, { ok: true, rows: result.rows ?? [] });
72
+ const last = Array.isArray(result) ? result[result.length - 1] : result;
73
+ // Identity columns are never read through Database.run in the state layer;
74
+ // keep the API shape without pretending to know an insert id.
75
+ return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
76
+ } catch (error) {
77
+ return reply(request, { ok: false, error: serialize(error) });
78
+ }
79
+ }
80
+
81
+ async function drain() {
82
+ draining = true;
83
+ while (queue.length && !closing) await handle(queue.shift());
84
+ draining = false;
85
+ }
86
+
87
+ async function shutdown(signal) {
88
+ closing = true;
89
+ try { await client.end(); } catch { /* connection already gone */ }
90
+ try { port.close(); } catch { /* already closed */ }
91
+ if (signal) {
92
+ const flag = new Int32Array(signal);
93
+ Atomics.store(flag, 0, 1);
94
+ Atomics.notify(flag, 0);
95
+ }
96
+ }
97
+
98
+ function handlePortMessage(message) {
99
+ if (message?.type === "close") {
100
+ void shutdown(message.signal);
101
+ return;
102
+ }
103
+ queue.push(message);
104
+ if (connected && !draining) void drain();
105
+ }
106
+
107
+ async function startup(connectionString, ready, timeout) {
108
+ readyFlag = new Int32Array(ready);
109
+ statementTimeout = timeout;
110
+ try {
111
+ client = new pg.Client({
112
+ connectionString,
113
+ application_name: "chat-room-channeld",
114
+ statement_timeout: statementTimeout,
115
+ });
116
+ await client.connect();
117
+ connected = true;
118
+ port.postMessage({ type: "ready" });
119
+ signalReady();
120
+ if (queue.length && !draining) void drain();
121
+ } catch (error) {
122
+ port.postMessage({ type: "fatal", error: serialize(error) });
123
+ signalReady();
124
+ }
125
+ }
126
+
127
+ parentPort.on("message", (message) => {
128
+ if (message?.type !== "init" || client) return;
129
+ port = message.port;
130
+ port.on("message", handlePortMessage);
131
+ parentPort.close();
132
+ void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
133
+ });
@@ -62,6 +62,7 @@ export type AdapterCapabilities = {
62
62
  displayName?: string;
63
63
  attachments?: AttachmentCapabilities;
64
64
  account?: AccountCapabilities;
65
+ send?: { idempotency?: string };
65
66
  };
66
67
 
67
68
  export interface IngestEvent {