@alexsun-top/opencode-chat-room 0.8.4 → 0.8.6

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 (206) hide show
  1. package/CHANGELOG.md +17 -3
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/cli.ts +20 -1
  5. package/dist/cli.js +3785 -1462
  6. package/package.json +19 -11
  7. package/packages/chat-room-channeld/README.md +16 -10
  8. package/packages/chat-room-channeld/src/delivery.ts +0 -4
  9. package/packages/chat-room-channeld/src/host.ts +48 -37
  10. package/packages/chat-room-channeld/src/inbound.ts +3 -6
  11. package/packages/chat-room-channeld/src/pg/database.ts +141 -49
  12. package/packages/chat-room-channeld/src/pg/sql.mjs +157 -142
  13. package/packages/chat-room-channeld/src/pg/sql.mts +175 -0
  14. package/packages/chat-room-channeld/src/pg/worker.mjs +148 -99
  15. package/packages/chat-room-channeld/src/pg/worker.mts +201 -0
  16. package/packages/chat-room-channeld/src/state-rows.ts +132 -0
  17. package/packages/chat-room-channeld/src/state.ts +129 -157
  18. package/plugin.ts +21 -5
  19. package/server/app.ts +9 -0
  20. package/server/assets/base.css +22 -2
  21. package/server/assets/chat/admin.js +17 -1
  22. package/server/assets/chat/announcements.js +79 -34
  23. package/server/assets/chat/attachments.js +3 -3
  24. package/server/assets/chat/clipboard.js +1 -1
  25. package/server/assets/chat/confirm-dialog.js +3 -0
  26. package/server/assets/chat/copy-action.js +1 -1
  27. package/server/assets/chat/create-room-dialog.js +7 -0
  28. package/server/assets/chat/diagram-viewer.js +4 -8
  29. package/server/assets/chat/doc-preview.js +71 -31
  30. package/server/assets/chat/editor.js +49 -10
  31. package/server/assets/chat/events.js +13 -6
  32. package/server/assets/chat/files.js +33 -27
  33. package/server/assets/chat/history-loader.js +31 -15
  34. package/server/assets/chat/integration-editor.js +27 -1
  35. package/server/assets/chat/integrations.js +108 -16
  36. package/server/assets/chat/join-requests.js +40 -2
  37. package/server/assets/chat/locales/de.js +5 -3
  38. package/server/assets/chat/locales/es.js +5 -3
  39. package/server/assets/chat/locales/fr.js +5 -3
  40. package/server/assets/chat/locales/it.js +5 -3
  41. package/server/assets/chat/locales/ja.js +5 -3
  42. package/server/assets/chat/locales/ko.js +5 -3
  43. package/server/assets/chat/markdown-footnotes.js +27 -15
  44. package/server/assets/chat/markdown.js +6 -12
  45. package/server/assets/chat/members.js +34 -22
  46. package/server/assets/chat/mentions.js +8 -5
  47. package/server/assets/chat/message-cache.js +9 -3
  48. package/server/assets/chat/message-polling.js +10 -4
  49. package/server/assets/chat/message-window.js +58 -1
  50. package/server/assets/chat/messages.js +90 -37
  51. package/server/assets/chat/office-preview.js +3 -3
  52. package/server/assets/chat/operator.js +624 -0
  53. package/server/assets/chat/palette.js +7 -10
  54. package/server/assets/chat/panels.js +42 -0
  55. package/server/assets/chat/questions.js +75 -58
  56. package/server/assets/chat/recall.js +14 -5
  57. package/server/assets/chat/receipts.js +63 -7
  58. package/server/assets/chat/refresh-timing.js +6 -0
  59. package/server/assets/chat/reminders.js +47 -13
  60. package/server/assets/chat/replies.js +39 -25
  61. package/server/assets/chat/resource-format.js +6 -3
  62. package/server/assets/chat/room-list.js +202 -3
  63. package/server/assets/chat/room-watcher.js +3 -1
  64. package/server/assets/chat/rooms.js +29 -7
  65. package/server/assets/chat/settings.js +37 -6
  66. package/server/assets/chat/shortcuts.js +3 -1
  67. package/server/assets/chat/side-pane.js +1 -1
  68. package/server/assets/chat/state.js +51 -18
  69. package/server/assets/chat/system-events.js +3 -2
  70. package/server/assets/chat/system-messages.js +15 -15
  71. package/server/assets/chat/tasks.js +37 -14
  72. package/server/assets/chat/window-controls.js +25 -15
  73. package/server/assets/code-highlight.css +0 -13
  74. package/server/assets/conversation.css +45 -5
  75. package/server/assets/doc-preview.css +9 -0
  76. package/server/assets/files.css +4 -0
  77. package/server/assets/monaco/integration-rules.js +1 -1
  78. package/server/assets/office/THIRD-PARTY-NOTICES.txt +23 -1
  79. package/server/assets/office/licenses/docx-preview-HEADER.txt +6 -0
  80. package/server/assets/office/licenses/echarts-LICENSE-d3.txt +27 -0
  81. package/server/assets/office/licenses/echarts-NOTICE.txt +5 -0
  82. package/server/assets/office/licenses/immediate-LICENSE.txt +20 -0
  83. package/server/assets/office/licenses/lie-LICENSE.txt +7 -0
  84. package/server/assets/office/licenses/pako-LICENSE.txt +21 -0
  85. package/server/assets/office/licenses/pako-ZLIB.txt +18 -0
  86. package/server/assets/office/licenses/setimmediate-LICENSE.txt +20 -0
  87. package/server/assets/responsive.css +12 -2
  88. package/server/assets/settings.css +3 -1
  89. package/server/assets/tasks.css +6 -1
  90. package/server/assets/window-controls.css +3 -1
  91. package/server/channels.ts +3 -2
  92. package/server/chat.html +7 -2
  93. package/server/inbox.ts +3 -1
  94. package/server/join-requests.ts +8 -1
  95. package/server/member-routes.ts +16 -2
  96. package/server/newrooms.ts +2 -13
  97. package/server/operator-auth.ts +21 -0
  98. package/server/operator-routes.ts +150 -0
  99. package/server/operator-state.ts +64 -0
  100. package/server/operator.css +139 -0
  101. package/server/room-owner.ts +17 -0
  102. package/server/routes/inbox.ts +15 -5
  103. package/server/routes/pages.ts +12 -2
  104. package/server/routes/room-actions.ts +4 -3
  105. package/server/sw.js +3 -1
  106. package/server/system.html +109 -0
  107. package/server/wake.ts +1 -1
  108. package/skills/chatroom/SKILL.md +9 -0
  109. package/src/README.md +1 -1
  110. package/src/acp/client.ts +254 -0
  111. package/src/acp/protocol.ts +300 -0
  112. package/src/acp/watch.ts +498 -0
  113. package/src/agent/agent-receipts.ts +98 -8
  114. package/src/center/center-client.ts +6 -1
  115. package/src/center/center-inbox.ts +54 -7
  116. package/src/center/center-wake.ts +57 -3
  117. package/src/center/forward-client.ts +48 -0
  118. package/src/center/mentions.ts +16 -3
  119. package/src/center/notification-delay.ts +139 -0
  120. package/src/center/queue.ts +3 -0
  121. package/src/config/file-config.ts +25 -0
  122. package/src/mcp/server.ts +389 -0
  123. package/src/protocol/config.ts +7 -0
  124. package/src/runtime/plugin-notifications.ts +43 -9
  125. package/src/runtime/v2-plugin.ts +14 -3
  126. package/src/runtime/v2-receiver.ts +10 -2
  127. package/src/runtime/watch.ts +5 -1
  128. package/src/state/pg-database.ts +133 -49
  129. package/src/state/pg-sql.mjs +157 -142
  130. package/src/state/pg-sql.mts +175 -0
  131. package/src/state/pg-worker.mjs +148 -99
  132. package/src/state/pg-worker.mts +201 -0
  133. package/src/state/receiver-state.ts +47 -0
  134. package/src/state/sqlite-database.ts +6 -2
  135. package/src/state/sqlite-members.ts +48 -4
  136. package/src/state/sqlite-messages.ts +25 -12
  137. package/src/state/sqlite-schema.ts +4 -1
  138. package/src/state/sqlite-state.ts +1 -1
  139. package/src/state/store.ts +31 -11
  140. package/src/tui/app-types.mjs +1 -0
  141. package/src/tui/app-types.mts +175 -0
  142. package/src/tui/app.mjs +473 -423
  143. package/src/tui/app.mts +543 -0
  144. package/src/tui/config.mjs +166 -158
  145. package/src/tui/config.mts +247 -0
  146. package/src/tui/http.mjs +239 -206
  147. package/src/tui/http.mts +412 -0
  148. package/src/tui/i18n.mjs +17 -20
  149. package/src/tui/i18n.mts +42 -0
  150. package/src/tui/info-app.mjs +431 -427
  151. package/src/tui/info-app.mts +500 -0
  152. package/src/tui/info-content.mjs +205 -199
  153. package/src/tui/info-content.mts +341 -0
  154. package/src/tui/join-app.mjs +75 -64
  155. package/src/tui/join-app.mts +99 -0
  156. package/src/tui/locales/en.mjs +302 -320
  157. package/src/tui/locales/en.mts +349 -0
  158. package/src/tui/locales/zh-CN.mjs +302 -320
  159. package/src/tui/locales/zh-CN.mts +349 -0
  160. package/src/tui/main.mjs +219 -213
  161. package/src/tui/main.mts +255 -0
  162. package/src/tui/markdown.mjs +128 -272
  163. package/src/tui/markdown.mts +152 -0
  164. package/src/tui/mentions.mjs +181 -184
  165. package/src/tui/mentions.mts +251 -0
  166. package/src/tui/message-app.mjs +181 -173
  167. package/src/tui/message-app.mts +213 -0
  168. package/src/tui/message-view.mjs +90 -111
  169. package/src/tui/message-view.mts +151 -0
  170. package/src/tui/messages.mjs +55 -49
  171. package/src/tui/messages.mts +106 -0
  172. package/src/tui/palette-app.mjs +364 -344
  173. package/src/tui/palette-app.mts +388 -0
  174. package/src/tui/palette.mjs +100 -98
  175. package/src/tui/palette.mts +176 -0
  176. package/src/tui/prefs.mjs +56 -63
  177. package/src/tui/prefs.mts +126 -0
  178. package/src/tui/reminder-app.mjs +191 -181
  179. package/src/tui/reminder-app.mts +228 -0
  180. package/src/tui/room-settings-app.mjs +275 -242
  181. package/src/tui/room-settings-app.mts +318 -0
  182. package/src/tui/session.mjs +30 -29
  183. package/src/tui/session.mts +51 -0
  184. package/src/tui/settings-app.mjs +151 -138
  185. package/src/tui/settings-app.mts +179 -0
  186. package/src/tui/ui-content.mjs +426 -421
  187. package/src/tui/ui-content.mts +499 -0
  188. package/src/tui/ui-help.mjs +58 -67
  189. package/src/tui/ui-help.mts +87 -0
  190. package/src/tui/ui-mentions.mjs +34 -36
  191. package/src/tui/ui-mentions.mts +60 -0
  192. package/src/tui/ui-overlay-view.mjs +259 -267
  193. package/src/tui/ui-overlay-view.mts +322 -0
  194. package/src/tui/ui-suggest-view.mjs +54 -57
  195. package/src/tui/ui-suggest-view.mts +78 -0
  196. package/src/tui/ui-suggest.mjs +164 -167
  197. package/src/tui/ui-suggest.mts +248 -0
  198. package/src/tui/ui-theme.mjs +52 -57
  199. package/src/tui/ui-theme.mts +98 -0
  200. package/src/tui/ui-view.mjs +267 -275
  201. package/src/tui/ui-view.mts +308 -0
  202. package/src/tui/ui.mjs +372 -359
  203. package/src/tui/ui.mts +440 -0
  204. package/src/tui/wire.mjs +215 -0
  205. package/src/tui/wire.mts +383 -0
  206. package/src/web/integration-rules-editor.ts +25 -2
@@ -11,6 +11,11 @@ import type { QueryStatement, SQLQueryBindings, StateDatabase, Transaction } fro
11
11
  // PostgreSQL support is experimental through the 0.8.2 multi-instance
12
12
  // milestone. Writers serialize per transaction with an advisory xact lock;
13
13
  // separate processes may share the database and apply disjoint diffs.
14
+ //
15
+ // A bridge timeout or a lost backend closes the worker instead of poisoning
16
+ // this handle: the connection is reopened by the next operation issued outside
17
+ // a transaction. The failed operation itself is never replayed, because its
18
+ // outcome is unknown (a timed-out INSERT may already have committed).
14
19
 
15
20
  type Reply = {
16
21
  id: number;
@@ -20,6 +25,7 @@ type Reply = {
20
25
  changes?: number;
21
26
  lastInsertRowid?: number;
22
27
  error?: Record<string, unknown>;
28
+ broken?: true;
23
29
  };
24
30
 
25
31
  type ReadyMessage = { type: "ready" } | { type: "fatal"; error?: Record<string, unknown> };
@@ -37,52 +43,105 @@ function databaseError(error: Record<string, unknown> | undefined): Error {
37
43
  return result;
38
44
  }
39
45
 
46
+ // A lost transport is not a retryable SQL condition: immediate() retries busy
47
+ // errors, and replaying a statement with an unknown outcome is unsafe.
48
+ function lostError(error: unknown): Error {
49
+ const cause = error instanceof Error ? error : new Error(String(error));
50
+ return Object.assign(new Error(`PostgreSQL connection lost: ${cause.message}`, { cause }), {
51
+ code: "PG_BRIDGE_LOST",
52
+ });
53
+ }
54
+
40
55
  export class PgDatabase implements StateDatabase {
41
- readonly #worker: Worker;
42
- readonly #port: MessagePort;
56
+ readonly #connectionString: string;
43
57
  readonly #timeout: number;
44
58
  readonly #lockTimeout: number;
59
+ #worker: Worker | undefined;
60
+ #port: MessagePort | undefined;
61
+ #generation = 0;
45
62
  #nextID = 1;
46
63
  #depth = 0;
47
64
  #savepoints = 0;
48
- #broken: Error | undefined;
65
+ #dead: Error | undefined;
49
66
  #closed = false;
50
67
 
51
68
  constructor(connectionString: string, options: { timeout?: number } = {}) {
52
69
  if (!connectionString) throw new Error("PostgreSQL connection string is empty");
70
+ this.#connectionString = connectionString;
53
71
  this.#timeout = options.timeout ?? 5_000;
54
72
  this.#lockTimeout = Math.max(1, this.#timeout - 1_000);
73
+ this.#open();
74
+ }
75
+
76
+ // Starts one worker and one pg.Client. Generation numbers hide events from a
77
+ // worker that was already discarded, so a late error or exit cannot mark the
78
+ // replacement connection dead.
79
+ #open(): void {
80
+ const generation = ++this.#generation;
55
81
  const ready = new SharedArrayBuffer(4);
56
82
  const { port1, port2 } = new MessageChannel();
83
+ const worker = new Worker(workerURL());
84
+ worker.unref();
85
+ port1.unref();
86
+ this.#worker = worker;
57
87
  this.#port = port1;
58
- this.#worker = new Worker(workerURL());
59
- this.#worker.unref();
60
- this.#port.unref();
88
+ this.#nextID = 1;
89
+ // Without an "error" listener an uncaught worker failure kills the server
90
+ // process; the worker forwards every connection failure it can observe, and
91
+ // these handlers cover the rest (including a failed startup).
92
+ worker.on("error", (error: Error) => this.#lose(generation, error));
93
+ worker.on("exit", (code: number) => this.#lose(generation, new Error(`PostgreSQL worker exited with code ${code}`)));
61
94
  try {
62
95
  // No workerData: some Bun versions break `pg` when a worker starts with
63
96
  // any workerData. The default worker channel carries one init message
64
97
  // and transfers the request port.
65
- this.#worker.postMessage({
98
+ worker.postMessage({
66
99
  type: "init",
67
- connectionString,
100
+ connectionString: this.#connectionString,
68
101
  ready,
69
102
  statementTimeout: Math.max(1, this.#timeout - 500),
70
103
  port: port2,
71
104
  }, [port2]);
105
+ const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
106
+ if (status === "timed-out") throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
107
+ const message = receiveMessageOnPort(port1)?.message as ReadyMessage | undefined;
108
+ if (message?.type === "fatal") throw databaseError(message.error);
109
+ if (message?.type !== "ready") throw new Error("PostgreSQL bridge did not report readiness");
72
110
  } catch (error) {
73
- void this.#worker.terminate();
74
- this.#port.close();
75
- throw error;
76
- }
77
- const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
78
- if (status === "timed-out") {
79
- void this.#worker.terminate();
80
- throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
111
+ if (!this.#dead) this.#dead = error instanceof Error ? error : new Error(String(error));
112
+ this.#discard();
113
+ throw this.#dead;
81
114
  }
82
- const message = receiveMessageOnPort(this.#port)?.message as ReadyMessage | undefined;
83
- if (message?.type === "fatal") {
84
- void this.#worker.terminate();
85
- throw databaseError(message.error);
115
+ this.#dead = undefined;
116
+ }
117
+
118
+ #discard(): void {
119
+ const worker = this.#worker;
120
+ const port = this.#port;
121
+ this.#worker = undefined;
122
+ this.#port = undefined;
123
+ try { port?.close(); } catch { /* already closed */ }
124
+ if (worker) void worker.terminate();
125
+ }
126
+
127
+ #lose(generation: number, error: Error): void {
128
+ if (generation !== this.#generation || this.#dead || this.#closed) return;
129
+ this.#dead = lostError(error);
130
+ this.#discard();
131
+ }
132
+
133
+ // Fails fast inside a transaction: the old transaction is already lost, so
134
+ // reopening here would run its remaining statements outside that transaction.
135
+ // A closed handle never reopens, even when it was also lost.
136
+ #ensureOpen(): void {
137
+ if (this.#closed) throw new Error("PostgreSQL database is closed");
138
+ if (!this.#dead) return;
139
+ if (this.#depth > 0) throw this.#dead;
140
+ this.#discard();
141
+ try {
142
+ this.#open();
143
+ } catch (error) {
144
+ throw lostError(error instanceof Error ? error : new Error(String(error)));
86
145
  }
87
146
  }
88
147
 
@@ -112,37 +171,37 @@ export class PgDatabase implements StateDatabase {
112
171
  close(): void {
113
172
  if (this.#closed) return;
114
173
  this.#closed = true;
174
+ const port = this.#port;
175
+ if (!port || this.#dead) { this.#discard(); return; }
115
176
  const signal = new SharedArrayBuffer(4);
116
177
  try {
117
- this.#port.postMessage({ type: "close", signal });
178
+ port.postMessage({ type: "close", signal });
118
179
  // Give client.end() time to flush before a caller opens the next
119
180
  // connection (migration and restart tests rely on it).
120
181
  Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
121
182
  } catch { /* worker already gone */ }
122
- this.#port.close();
123
- void this.#worker.terminate();
183
+ this.#discard();
124
184
  }
125
185
 
126
186
  #run<T>(fn: () => T, immediate: boolean): T {
127
187
  const nested = this.#depth > 0;
188
+ // Reopen only before the transaction starts. Once #depth is set, a lost
189
+ // connection fails the transaction instead of running its ROLLBACK on a
190
+ // replacement session.
191
+ if (!nested) this.#ensureOpen();
128
192
  const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
129
- if (nested) {
130
- this.exec(`SAVEPOINT ${savepoint}`);
131
- } else {
132
- // Deferred reads need one stable snapshot; immediate writers are
133
- // serialized by the transaction-level advisory lock.
134
- this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
135
- if (immediate) {
136
- try {
193
+ this.#depth++;
194
+ try {
195
+ if (nested) {
196
+ this.exec(`SAVEPOINT ${savepoint}`);
197
+ } else {
198
+ // Deferred reads need one stable snapshot; immediate writers are
199
+ // serialized by the transaction-level advisory lock.
200
+ this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
201
+ if (immediate) {
137
202
  this.exec(`SET LOCAL lock_timeout = '${this.#lockTimeout}ms'; SELECT pg_advisory_xact_lock(hashtext('chat-room-state')); SET LOCAL lock_timeout = 0`);
138
- } catch (error) {
139
- try { this.exec("ROLLBACK"); } catch { /* keep the original error */ }
140
- throw error;
141
203
  }
142
204
  }
143
- }
144
- this.#depth++;
145
- try {
146
205
  const result = fn();
147
206
  this.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
148
207
  return result;
@@ -157,27 +216,52 @@ export class PgDatabase implements StateDatabase {
157
216
  }
158
217
 
159
218
  #request(mode: "all" | "get" | "run" | "exec", sql: string, params: SQLQueryBindings[]): Reply {
160
- if (this.#broken) throw this.#broken;
161
- if (this.#closed) throw new Error("PostgreSQL database is closed");
219
+ this.#ensureOpen();
220
+ const port = this.#port as MessagePort;
162
221
  const id = this.#nextID++;
163
222
  const signal = new SharedArrayBuffer(4);
164
- this.#port.postMessage({ id, mode, sql, params, signal });
223
+ try {
224
+ port.postMessage({ id, mode, sql, params, signal });
225
+ } catch (error) {
226
+ // The bridge is gone, not the statement: retire it so the next operation
227
+ // reopens instead of surfacing a generic port error.
228
+ const failure = lostError(error instanceof Error ? error : new Error(String(error)));
229
+ this.#fail(failure);
230
+ throw failure;
231
+ }
165
232
  const status = Atomics.wait(new Int32Array(signal), 0, 0, this.#timeout);
233
+ const message = receiveMessageOnPort(port)?.message as Reply | undefined;
166
234
  if (status === "timed-out") {
167
- // The worker may still be inside the query. Its connection and queue are
168
- // no longer trustworthy, so fail closed rather than desynchronize later calls.
169
- this.#broken = Object.assign(
170
- new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the database connection must be reopened`),
235
+ // The worker may still be inside the statement, so its outcome is unknown.
236
+ // Closing the connection aborts its transaction; the statement is never
237
+ // replayed and a later independent operation reconnects.
238
+ const error = Object.assign(
239
+ new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the connection was closed and reopens on the next operation`),
171
240
  { code: "PG_BRIDGE_TIMEOUT" },
172
241
  );
173
- throw this.#broken;
242
+ this.#fail(error);
243
+ throw error;
174
244
  }
175
- const message = receiveMessageOnPort(this.#port)?.message as Reply | undefined;
176
245
  if (!message || message.id !== id) {
177
- this.#broken = Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
178
- throw this.#broken;
246
+ const error = this.#dead ?? Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
247
+ this.#fail(error);
248
+ throw error;
249
+ }
250
+ if (!message.ok) {
251
+ const error = databaseError(message.error);
252
+ if (message.broken) {
253
+ const lost = lostError(error);
254
+ this.#fail(lost);
255
+ throw lost;
256
+ }
257
+ throw error;
179
258
  }
180
- if (!message.ok) throw databaseError(message.error);
181
259
  return message;
182
260
  }
261
+
262
+ #fail(error: Error): void {
263
+ if (this.#dead) return;
264
+ this.#dead = error;
265
+ this.#discard();
266
+ }
183
267
  }
@@ -4,172 +4,187 @@
4
4
  //
5
5
  // This is intentionally not a general SQLite translator. Keep the dialect
6
6
  // narrow and add a test when the state layer starts using a new construct.
7
-
8
7
  const PRAGMA_TABLE_INFO = /PRAGMA\s+table_info\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)/gi;
9
-
10
8
  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`;
9
+ const tableName = table.replace(/'/g, "''");
10
+ return `SELECT c.column_name AS name,c.data_type AS type,` +
11
+ `CASE WHEN c.is_nullable='NO' THEN 1 ELSE 0 END AS "notnull",` +
12
+ `c.column_default AS dflt_value,` +
13
+ `CASE WHEN EXISTS (SELECT 1 FROM pg_index i JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=ANY(i.indkey) ` +
14
+ `WHERE i.indrelid=(quote_ident(c.table_schema)||'.'||quote_ident(c.table_name))::regclass AND i.indisprimary AND a.attname=c.column_name) ` +
15
+ `THEN 1 ELSE 0 END AS pk ` +
16
+ `FROM information_schema.columns c WHERE c.table_schema=current_schema() AND c.table_name='${tableName}' ORDER BY c.ordinal_position`;
19
17
  }
20
-
21
18
  const isIdentStart = (ch) => !!ch && /[A-Za-z_]/.test(ch);
22
19
  const isIdentChar = (ch) => !!ch && /[A-Za-z0-9_$]/.test(ch);
23
-
24
20
  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;
21
+ const quote = sql[index];
22
+ let i = index + 1;
23
+ while (i < sql.length) {
24
+ if (sql[i] === quote) {
25
+ if (sql[i + 1] === quote) {
26
+ i += 2;
27
+ continue;
28
+ }
29
+ return i + 1;
30
+ }
31
+ i++;
31
32
  }
32
- i++;
33
- }
34
- return i;
33
+ return i;
35
34
  }
36
-
37
35
  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;
36
+ if (sql[index + 1] === "-") {
37
+ const end = sql.indexOf("\n", index + 2);
38
+ return end < 0 ? sql.length : end;
39
+ }
40
+ const end = sql.indexOf("*/", index + 2);
41
+ return end < 0 ? sql.length : end + 2;
44
42
  }
45
-
46
43
  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;
44
+ let depth = 0;
45
+ for (let i = openIndex; i < sql.length; i++) {
46
+ const ch = sql[i];
47
+ if (ch === "'" || ch === '"') {
48
+ i = skipQuoted(sql, i) - 1;
49
+ continue;
50
+ }
51
+ if (ch === "-" && sql[i + 1] === "-") {
52
+ i = skipComment(sql, i) - 1;
53
+ continue;
54
+ }
55
+ if (ch === "/" && sql[i + 1] === "*") {
56
+ i = skipComment(sql, i) - 1;
57
+ continue;
58
+ }
59
+ if (ch === "(")
60
+ depth++;
61
+ else if (ch === ")") {
62
+ depth--;
63
+ if (depth === 0)
64
+ return false;
65
+ }
66
+ else if (ch === "," && depth === 1)
67
+ return true;
68
+ }
69
+ return false;
58
70
  }
59
-
60
71
  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();
72
+ let i = index - 1;
73
+ while (i >= 0 && /\s/.test(sql.charAt(i)))
74
+ i--;
75
+ const end = i + 1;
76
+ while (i >= 0 && isIdentChar(sql[i]))
77
+ i--;
78
+ return sql.slice(i + 1, end).toLowerCase();
66
79
  }
67
-
68
80
  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();
81
+ let i = index + 1;
82
+ while (i < sql.length && /\s/.test(sql.charAt(i)))
83
+ i++;
84
+ const start = i;
85
+ while (i < sql.length && isIdentChar(sql[i]))
86
+ i++;
87
+ return sql.slice(start, i).toLowerCase();
74
88
  }
75
-
76
89
  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;
90
+ let out = "";
91
+ let index = 0;
92
+ let parameter = 0;
93
+ while (index < sql.length) {
94
+ const ch = sql.charAt(index);
95
+ if (ch === "'" || ch === '"') {
96
+ const end = skipQuoted(sql, index);
97
+ out += sql.slice(index, end);
98
+ index = end;
99
+ continue;
121
100
  }
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;
101
+ if (ch === "-" && sql[index + 1] === "-") {
102
+ const end = skipComment(sql, index);
103
+ out += sql.slice(index, end);
104
+ index = end;
135
105
  continue;
136
- }
137
106
  }
138
- }
139
- out += word;
140
- index = end;
141
- continue;
107
+ if (ch === "/" && sql[index + 1] === "*") {
108
+ const end = skipComment(sql, index);
109
+ out += sql.slice(index, end);
110
+ index = end;
111
+ continue;
112
+ }
113
+ if (ch === "?") {
114
+ // CASE WHEN ? needs a boolean; a bare `? IS NULL` has no type to infer.
115
+ const nextWord = wordAfter(sql, index);
116
+ const cast = (wordBefore(sql, index) === "when" && nextWord === "then") || nextWord === "is";
117
+ out += `$${++parameter}${cast ? (nextWord === "is" ? "::text" : "::boolean") : ""}`;
118
+ index++;
119
+ continue;
120
+ }
121
+ if (isIdentStart(ch)) {
122
+ let end = index + 1;
123
+ while (isIdentChar(sql[end]))
124
+ end++;
125
+ const word = sql.slice(index, end);
126
+ const lower = word.toLowerCase();
127
+ // SQLite's scalar max(a,b)/min(a,b); the one-argument aggregate forms stay.
128
+ if (lower === "max" || lower === "min") {
129
+ let next = end;
130
+ while (next < sql.length && /\s/.test(sql.charAt(next)))
131
+ next++;
132
+ if (sql[next] === "(" && hasTopLevelComma(sql, next)) {
133
+ out += lower === "max" ? "GREATEST" : "LEAST";
134
+ index = end;
135
+ continue;
136
+ }
137
+ }
138
+ // Preserve camelCase result aliases: PostgreSQL folds unquoted identifiers.
139
+ if (lower === "as") {
140
+ const previous = wordBefore(sql, index);
141
+ let next = end;
142
+ while (next < sql.length && /\s/.test(sql.charAt(next)))
143
+ next++;
144
+ if (isIdentStart(sql[next])) {
145
+ let aliasEnd = next + 1;
146
+ while (isIdentChar(sql[aliasEnd]))
147
+ aliasEnd++;
148
+ const alias = sql.slice(next, aliasEnd);
149
+ if (/[A-Z]/.test(alias) && previous !== "default" && alias.toLowerCase() !== "identity") {
150
+ out += `AS "${alias}"`;
151
+ index = aliasEnd;
152
+ continue;
153
+ }
154
+ }
155
+ }
156
+ out += word;
157
+ index = end;
158
+ continue;
159
+ }
160
+ out += ch;
161
+ index++;
142
162
  }
143
- out += ch;
144
- index++;
145
- }
146
- return out;
163
+ return out;
147
164
  }
148
-
149
165
  function appendOnConflictDoNothing(sql) {
150
- return `${sql.replace(/[\s;]+$/, "")} ON CONFLICT DO NOTHING`;
166
+ return `${sql.replace(/[\s;]+$/, "")} ON CONFLICT DO NOTHING`;
151
167
  }
152
-
153
168
  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();
169
+ let text = String(sql);
170
+ // Connection tuning pragmas have no PostgreSQL equivalent; foreign keys are
171
+ // always enforced and concurrency is handled by advisory locks.
172
+ text = text.replace(/PRAGMA\s+(?:busy_timeout|journal_mode|foreign_keys)\s*(?:=\s*[^;]+)?\s*;?/gi, "");
173
+ text = text.replace(PRAGMA_TABLE_INFO, (_, table) => pragmaTableInfo(table));
174
+ // SQLite INTEGER is 64-bit; PostgreSQL INTEGER is 32-bit and epoch
175
+ // milliseconds overflow it.
176
+ text = text.replace(/\bINTEGER\b/gi, "BIGINT");
177
+ text = text.replace(/\bBIGINT\s+PRIMARY\s+KEY\s+AUTOINCREMENT\b/gi, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
178
+ // Manual `BEGIN IMMEDIATE` appears inside receiver-state's schema script.
179
+ text = text.replace(/\bBEGIN\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE)\b/gi, "BEGIN");
180
+ if (/\bINSERT\s+OR\s+IGNORE\b/i.test(text)) {
181
+ text = text.replace(/\bINSERT\s+OR\s+IGNORE\b/gi, "INSERT");
182
+ if (!/\bON\s+CONFLICT\b/i.test(text))
183
+ text = appendOnConflictDoNothing(text);
184
+ }
185
+ // SQLite treats 1/0 as booleans; PostgreSQL needs an explicit cast.
186
+ return scan(text).trim();
171
187
  }
172
-
173
188
  export function hasSql(text) {
174
- return text.replace(/[;\s]/g, "").length > 0;
175
- }
189
+ return text.replace(/[;\s]/g, "").length > 0;
190
+ }