@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.
Files changed (176) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +2 -2
  3. package/README.md +40 -8
  4. package/README.zh-CN.md +40 -8
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +5406 -3088
  7. package/package.json +25 -5
  8. package/packages/chat-room-channeld/README.md +111 -33
  9. package/packages/chat-room-channeld/src/adapter.ts +179 -7
  10. package/packages/chat-room-channeld/src/config.ts +63 -1
  11. package/packages/chat-room-channeld/src/delivery.ts +6 -1
  12. package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
  13. package/packages/chat-room-channeld/src/host.ts +142 -9
  14. package/packages/chat-room-channeld/src/inbound.ts +35 -0
  15. package/packages/chat-room-channeld/src/protocol.ts +52 -1
  16. package/packages/chat-room-channeld/src/rules.ts +7 -2
  17. package/packages/chat-room-channeld/src/state.ts +17 -0
  18. package/packages/chat-room-channeld/src/stats.ts +43 -1
  19. package/plugin.ts +1 -1
  20. package/server/admin-state.ts +13 -13
  21. package/server/app.ts +95 -0
  22. package/server/assets/NOTICE.txt +2 -1
  23. package/server/assets/base.css +21 -9
  24. package/server/assets/chat/admin.js +0 -2
  25. package/server/assets/chat/announcements.js +69 -8
  26. package/server/assets/chat/chat-background.js +177 -0
  27. package/server/assets/chat/confirm-dialog.js +0 -1
  28. package/server/assets/chat/create-room-dialog.js +0 -1
  29. package/server/assets/chat/diagram-viewer.js +7 -1
  30. package/server/assets/chat/doc-preview.js +251 -46
  31. package/server/assets/chat/events.js +16 -5
  32. package/server/assets/chat/files.js +53 -7
  33. package/server/assets/chat/image-zoom.js +8 -1
  34. package/server/assets/chat/index.js +6 -2
  35. package/server/assets/chat/integration-account-schema.js +99 -0
  36. package/server/assets/chat/integration-editor.js +163 -0
  37. package/server/assets/chat/integration-values.js +124 -0
  38. package/server/assets/chat/integrations.js +648 -0
  39. package/server/assets/chat/locales/de.js +40 -4
  40. package/server/assets/chat/locales/es.js +40 -4
  41. package/server/assets/chat/locales/fr.js +40 -4
  42. package/server/assets/chat/locales/it.js +40 -4
  43. package/server/assets/chat/locales/ja.js +40 -4
  44. package/server/assets/chat/locales/ko.js +40 -4
  45. package/server/assets/chat/markdown-footnotes.js +1 -1
  46. package/server/assets/chat/markdown.js +45 -8
  47. package/server/assets/chat/messages.js +6 -5
  48. package/server/assets/chat/office-preview.js +69 -0
  49. package/server/assets/chat/palette.js +6 -1
  50. package/server/assets/chat/panels.js +56 -0
  51. package/server/assets/chat/recall.js +58 -7
  52. package/server/assets/chat/receipts.js +17 -6
  53. package/server/assets/chat/reminders.js +68 -9
  54. package/server/assets/chat/replies.js +0 -6
  55. package/server/assets/chat/resource-format.js +11 -0
  56. package/server/assets/chat/rooms.js +1 -6
  57. package/server/assets/chat/settings.js +98 -4
  58. package/server/assets/chat/shortcuts.js +0 -3
  59. package/server/assets/chat/side-pane.js +34 -10
  60. package/server/assets/chat/state.js +125 -12
  61. package/server/assets/chat/system-events.js +58 -0
  62. package/server/assets/chat/system-messages.js +32 -14
  63. package/server/assets/chat/task-row.js +0 -6
  64. package/server/assets/chat/tasks.js +119 -37
  65. package/server/assets/chat/window-controls.js +37 -0
  66. package/server/assets/code-highlight.css +71 -32
  67. package/server/assets/conversation.css +174 -31
  68. package/server/assets/doc-preview.css +40 -3
  69. package/server/assets/files.css +8 -0
  70. package/server/assets/fluent-icons.svg +2 -0
  71. package/server/assets/monaco/LICENSE +21 -0
  72. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  73. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  74. package/server/assets/monaco/editor.worker.js +45 -0
  75. package/server/assets/monaco/integration-rules.css +1 -0
  76. package/server/assets/monaco/integration-rules.js +1605 -0
  77. package/server/assets/monaco/json.worker.js +77 -0
  78. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  79. package/server/assets/office/docx.bundle.js +33 -0
  80. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  81. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  82. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  83. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  84. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  85. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  86. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  87. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  88. package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
  89. package/server/assets/office/pptx.bundle.js +104 -0
  90. package/server/assets/office/xlsx.bundle.js +141 -0
  91. package/server/assets/recall.css +5 -4
  92. package/server/assets/responsive.css +80 -11
  93. package/server/assets/settings.css +185 -9
  94. package/server/assets/tasks.css +57 -7
  95. package/server/assets/window-controls.css +36 -0
  96. package/server/channel-attachments.ts +133 -0
  97. package/server/channel-integration.ts +572 -0
  98. package/server/channel-settings.ts +77 -0
  99. package/server/channels.ts +274 -21
  100. package/server/chat-server.ts +32 -580
  101. package/server/chat.html +234 -34
  102. package/server/http-server.ts +3 -182
  103. package/server/manifest.webmanifest +1 -0
  104. package/server/resource-routes.ts +16 -16
  105. package/server/routes/inbox.ts +100 -0
  106. package/server/routes/pages.ts +83 -0
  107. package/server/routes/questions.ts +39 -0
  108. package/server/routes/room-actions.ts +162 -0
  109. package/server/routes/rooms.ts +160 -0
  110. package/server/startup.ts +84 -0
  111. package/server/sw.js +5 -0
  112. package/server/task-routes.ts +1 -1
  113. package/src/center/center-client.ts +3 -11
  114. package/src/config/file-config.ts +7 -54
  115. package/src/platform/http-server.ts +182 -0
  116. package/src/protocol/addressing.ts +21 -0
  117. package/src/protocol/config.ts +58 -0
  118. package/src/protocol/room.ts +51 -0
  119. package/src/rooms/resources.ts +26 -16
  120. package/src/rooms/room-service.ts +2 -48
  121. package/src/rooms/storage.ts +329 -0
  122. package/src/rooms/tasks.ts +21 -5
  123. package/src/runtime/watch.ts +1 -1
  124. package/src/state/pg-database.ts +183 -0
  125. package/src/state/pg-migrate.ts +175 -0
  126. package/src/state/pg-sql.mjs +175 -0
  127. package/src/state/pg-worker.mjs +133 -0
  128. package/src/state/sqlite-announcements.ts +25 -0
  129. package/src/state/sqlite-database.ts +130 -0
  130. package/src/state/sqlite-legacy.ts +90 -0
  131. package/src/state/sqlite-members.ts +155 -0
  132. package/src/state/sqlite-messages.ts +288 -0
  133. package/src/state/sqlite-resources.ts +39 -0
  134. package/src/state/sqlite-rooms.ts +194 -0
  135. package/src/state/sqlite-schema.ts +80 -0
  136. package/src/state/sqlite-state-store.ts +34 -0
  137. package/src/state/sqlite-state.ts +15 -897
  138. package/src/state/sqlite-tasks.ts +65 -0
  139. package/src/state/sqlite-transaction.ts +13 -0
  140. package/src/state/sqlite.ts +21 -1
  141. package/src/state/store.ts +5 -1
  142. package/src/tui/app.mjs +32 -19
  143. package/src/tui/config.mjs +12 -4
  144. package/src/tui/i18n.mjs +38 -0
  145. package/src/tui/info-app.mjs +50 -51
  146. package/src/tui/info-content.mjs +79 -44
  147. package/src/tui/join-app.mjs +9 -9
  148. package/src/tui/locales/en.mjs +349 -0
  149. package/src/tui/locales/zh-CN.mjs +349 -0
  150. package/src/tui/main.mjs +85 -37
  151. package/src/tui/markdown.mjs +3 -2
  152. package/src/tui/mentions.mjs +3 -1
  153. package/src/tui/message-app.mjs +22 -21
  154. package/src/tui/message-view.mjs +2 -1
  155. package/src/tui/palette-app.mjs +9 -8
  156. package/src/tui/palette.mjs +30 -24
  157. package/src/tui/prefs.mjs +92 -0
  158. package/src/tui/reminder-app.mjs +18 -17
  159. package/src/tui/room-settings-app.mjs +30 -28
  160. package/src/tui/settings-app.mjs +153 -0
  161. package/src/tui/ui-content.mjs +65 -86
  162. package/src/tui/ui-help.mjs +73 -0
  163. package/src/tui/ui-overlay-view.mjs +23 -7
  164. package/src/tui/ui-suggest.mjs +6 -5
  165. package/src/tui/ui-theme.mjs +37 -33
  166. package/src/tui/ui-view.mjs +22 -7
  167. package/src/tui/ui.mjs +15 -3
  168. package/src/web/editor.worker.ts +1 -0
  169. package/src/web/integration-rules-editor.ts +573 -0
  170. package/src/web/integration-rules.ts +26 -0
  171. package/src/web/integration-schema.ts +229 -0
  172. package/src/web/json.worker.ts +1 -0
  173. package/src/web/office-viewer.ts +221 -0
  174. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -499
  175. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -473
  176. package/server/assets/chat/forward.js +0 -69
@@ -0,0 +1,648 @@
1
+ // Settings > Integrations: runtime switch, accounts, plugin uploads, and rules.
2
+ import { initIntegrationEditor } from "./integration-editor.js";
3
+ import { iconNode } from "./icons.js";
4
+ import { readAccountSchema, renderAccountSchema } from "./integration-account-schema.js";
5
+ import { checkInbound, checkRules, knownPlugins, normalizeAccount, parseInbound, parseRules } from "./integration-values.js";
6
+ import { accountBody, cleanError, stateLabel } from "./integration-values.js";
7
+
8
+ const MAX_SOURCE = 256 * 1024;
9
+ const IDENTIFIER = /^[A-Za-z0-9._-]{1,128}$/;
10
+ const PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:js|mjs|cjs|ts)$/;
11
+ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
12
+
13
+ const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
14
+
15
+ export function initIntegrations(app) {
16
+ const $ = app.$;
17
+ const panel = $("#settingsPanelIntegrations"); if (!panel) return;
18
+ const enabledInput = $("#inIntegrationsEnabled"), statusText = $("#integrationStatus");
19
+ const integrationBody = $("#integrationBody"), disabledHint = $("#integrationDisabledHint");
20
+ const panelError = $("#integrationError"), accountsList = $("#integrationAccounts");
21
+ const externalNotice = $("#integrationExternalNotice"), addAccountButton = $("#btnAddIntegrationAccount");
22
+ const uploadPluginButton = $("#btnUploadPlugin");
23
+ const accountsEmpty = $("#integrationAccountsEmpty"), pluginsList = $("#integrationPlugins");
24
+ const pluginsEmpty = $("#integrationPluginsEmpty");
25
+ const rulesError = $("#integrationRulesError"), saveButton = $("#btnSaveIntegrations");
26
+ const accountDialog = $("#integrationAccountDialog"), accountForm = $("#integrationAccountForm");
27
+ const accountError = $("#integrationAccountError"), accountId = $("#integrationAccountId");
28
+ const accountPlugin = $("#integrationAccountPlugin");
29
+ const accountSchema = $("#integrationAccountSchema"), accountSchemaField = $("#integrationAccountSchemaField"), accountAdvanced = $("#integrationAccountAdvanced");
30
+ const accountEnv = $("#integrationAccountEnv"), accountEnvNote = $("#integrationAccountEnvNote");
31
+ const accountClear = $("#btnClearAccountEnv"), accountAddEnv = $("#btnAddAccountEnv");
32
+ const pluginDialog = $("#integrationPluginDialog"), pluginForm = $("#integrationPluginForm");
33
+ const pluginError = $("#integrationPluginError"), pluginFile = $("#integrationPluginFile");
34
+ let data = { enabled: false, source: "managed", editable: true, accounts: [], rules: [], inbound: [], plugins: [] };
35
+ let initialInbound = "[]";
36
+ let loaded = false, loading = false, saving = false, accountDraft = null, clearEnv = false;
37
+ let pluginUploadSource = "", pluginUploadName = "";
38
+
39
+ const text = (key, values) => app.t(key, values);
40
+ const clean = (error) => cleanError(error, text("integrationsLoadFailed"));
41
+ const showPanelError = (error) => { panelError.textContent = clean(error); panelError.hidden = false; };
42
+ const hidePanelError = () => { panelError.hidden = true; };
43
+ const showStatus = (value) => { statusText.textContent = value; };
44
+ const showAccountError = (error) => { accountError.textContent = clean(error); accountError.hidden = false; };
45
+ const hideAccountError = () => { accountError.hidden = true; };
46
+ const showPluginError = (error) => { pluginError.textContent = clean(error); pluginError.hidden = false; };
47
+ const hidePluginError = () => { pluginError.hidden = true; };
48
+ const showRulesError = (value) => { rulesError.textContent = value; rulesError.hidden = false; };
49
+ const hideRulesError = () => { rulesError.hidden = true; };
50
+ const rulesSection = initIntegrationEditor(app, {
51
+ kind: "rules",
52
+ editor: "#integrationRulesEditor",
53
+ textarea: "#integrationRules",
54
+ fallback: "#integrationRulesFallback",
55
+ error: "#integrationRulesError",
56
+ errors: "#integrationRulesErrorList",
57
+ formats: "#integrationRulesFormat",
58
+ getValue: () => data.rules,
59
+ getAccounts: () => data.accounts,
60
+ });
61
+ const inboundSection = initIntegrationEditor(app, {
62
+ kind: "inbound",
63
+ editor: "#integrationInboundEditor",
64
+ textarea: "#integrationInbound",
65
+ fallback: "#integrationInboundFallback",
66
+ error: "#integrationInboundError",
67
+ errors: "#integrationInboundErrorList",
68
+ formats: "#integrationInboundFormat",
69
+ getValue: () => data.inbound,
70
+ getAccounts: () => data.accounts,
71
+ });
72
+
73
+ function applyEditableState() {
74
+ const editable = data.editable !== false;
75
+ if (externalNotice) externalNotice.hidden = editable;
76
+ saveButton.disabled = saving || !editable;
77
+ if (addAccountButton) addAccountButton.disabled = !editable;
78
+ if (uploadPluginButton) uploadPluginButton.disabled = !editable;
79
+ rulesSection.setEditable(editable);
80
+ inboundSection.setEditable(editable);
81
+ }
82
+
83
+ function applyEnabledState() {
84
+ const enabled = enabledInput.checked;
85
+ integrationBody.hidden = !enabled;
86
+ disabledHint.hidden = enabled;
87
+ }
88
+
89
+ const pluginNameOf = (pluginId) => knownPlugins(data).find((plugin) => plugin.pluginId === pluginId)?.name || pluginId;
90
+
91
+ function adopt(snapshot) {
92
+ const raw = isRecord(snapshot) ? snapshot : {};
93
+ data = {
94
+ enabled: raw.enabled === true,
95
+ source: typeof raw.source === "string" ? raw.source : "managed",
96
+ editable: raw.editable !== false,
97
+ accounts: Array.isArray(raw.accounts) ? raw.accounts.filter(isRecord).map(normalizeAccount) : [],
98
+ rules: Array.isArray(raw.rules) ? raw.rules : [],
99
+ inbound: Array.isArray(raw.inbound) ? raw.inbound : data.inbound,
100
+ plugins: Array.isArray(raw.plugins)
101
+ ? raw.plugins.filter((plugin) => isRecord(plugin) && typeof plugin.pluginId === "string" && typeof plugin.name === "string" && typeof plugin.platform === "string")
102
+ : data.plugins,
103
+ };
104
+ initialInbound = JSON.stringify(data.inbound);
105
+ loaded = true;
106
+ }
107
+
108
+ function renderAccounts() {
109
+ accountsList.textContent = "";
110
+ for (const account of data.accounts) {
111
+ const row = document.createElement("li");
112
+ row.className = "integration-account";
113
+ const main = document.createElement("div");
114
+ main.className = "integration-account-main";
115
+ const head = document.createElement("p");
116
+ head.className = "integration-account-head";
117
+ const id = document.createElement("span");
118
+ id.className = "integration-account-id";
119
+ id.textContent = account.id;
120
+ const platform = document.createElement("span");
121
+ platform.className = "integration-platform";
122
+ platform.textContent = account.platform;
123
+ const state = document.createElement("span");
124
+ state.className = "integration-state";
125
+ state.dataset.state = account.state;
126
+ state.textContent = stateLabel(account.state, text);
127
+ head.append(id, platform, state);
128
+ const meta = document.createElement("p");
129
+ meta.className = "integration-account-meta";
130
+ const env = account.envClear ? "—" : account.envKeys.length ? account.envKeys.join(", ") : "—";
131
+ meta.textContent = `${text("integrationsPlugin")}: ${pluginNameOf(account.pluginId)} · ${text("integrationsEnv")}: ${env}`;
132
+ main.append(head, meta);
133
+ if (account.lastError) {
134
+ const error = document.createElement("p");
135
+ error.className = "integration-account-error";
136
+ error.textContent = `${text("integrationsLastError")}: ${clean(account.lastError)}`;
137
+ main.append(error);
138
+ }
139
+ const actions = document.createElement("div");
140
+ actions.className = "integration-account-actions";
141
+ const edit = document.createElement("button");
142
+ edit.type = "button"; edit.className = "btn ghost small"; edit.textContent = text("integrationsEdit");
143
+ edit.setAttribute("aria-label", `${text("integrationsEdit")}: ${account.id}`);
144
+ edit.disabled = data.editable === false;
145
+ edit.addEventListener("click", () => openAccount(account));
146
+ const remove = document.createElement("button");
147
+ remove.type = "button"; remove.className = "btn ghost small danger-text"; remove.textContent = text("integrationsRemove");
148
+ remove.setAttribute("aria-label", `${text("integrationsRemove")}: ${account.id}`);
149
+ remove.disabled = data.editable === false;
150
+ remove.addEventListener("click", async () => {
151
+ if (data.editable === false) return;
152
+ if (!(await app.confirmAction(text("integrationsRemoveAccountConfirm", { id: account.id })))) return;
153
+ data.accounts = data.accounts.filter((item) => item.id !== account.id);
154
+ renderAccounts();
155
+ showStatus(text("integrationsAccountRemoved"));
156
+ });
157
+ actions.append(edit, remove);
158
+ row.append(main, actions);
159
+ accountsList.append(row);
160
+ }
161
+ accountsEmpty.hidden = data.accounts.length > 0;
162
+ rulesSection.setAccounts(data.accounts);
163
+ inboundSection.setAccounts(data.accounts);
164
+ }
165
+
166
+ function renderPlugins() {
167
+ const plugins = knownPlugins(data);
168
+ pluginsList.textContent = "";
169
+ for (const plugin of plugins) {
170
+ const row = document.createElement("li");
171
+ row.className = "integration-plugin";
172
+ const name = document.createElement("span");
173
+ name.className = "integration-plugin-name";
174
+ name.textContent = plugin.name;
175
+ const platform = document.createElement("span");
176
+ platform.className = "integration-platform";
177
+ platform.textContent = plugin.platform;
178
+ const download = document.createElement("button");
179
+ download.type = "button";
180
+ download.className = "btn ghost small integration-plugin-download";
181
+ download.title = text("integrationsDownloadPlugin", { name: plugin.name });
182
+ download.setAttribute("aria-label", download.title);
183
+ download.append(iconNode("arrow_download"));
184
+ download.addEventListener("click", () => void downloadPlugin(plugin, download));
185
+ row.append(name, platform, download);
186
+ pluginsList.append(row);
187
+ }
188
+ pluginsEmpty.hidden = plugins.length > 0;
189
+ }
190
+
191
+ async function downloadPlugin(plugin, button) {
192
+ if (button.disabled) return;
193
+ button.disabled = true;
194
+ try {
195
+ const blob = await app.apiBlob(`/channeld/plugins/${encodeURIComponent(plugin.pluginId)}/download`);
196
+ const href = URL.createObjectURL(blob);
197
+ const anchor = document.createElement("a");
198
+ anchor.href = href;
199
+ anchor.download = plugin.name;
200
+ document.body.append(anchor);
201
+ anchor.click();
202
+ anchor.remove();
203
+ setTimeout(() => URL.revokeObjectURL(href), 1000);
204
+ } catch (error) {
205
+ showPanelError(error);
206
+ } finally { button.disabled = false; }
207
+ }
208
+
209
+ function renderRules() {
210
+ rulesSection.refresh();
211
+ inboundSection.refresh();
212
+ rulesSection.setAccounts(data.accounts);
213
+ inboundSection.setAccounts(data.accounts);
214
+ hideRulesError();
215
+ }
216
+
217
+ function renderAll() {
218
+ enabledInput.checked = data.enabled;
219
+ renderAccounts();
220
+ renderPlugins();
221
+ renderRules();
222
+ applyEnabledState();
223
+ applyEditableState();
224
+ }
225
+
226
+ async function load(force = false) {
227
+ if (loading || loaded && !force) return;
228
+ loading = true;
229
+ void rulesSection.ensure();
230
+ void inboundSection.ensure();
231
+ hidePanelError();
232
+ showStatus(text("integrationsLoading"));
233
+ try {
234
+ adopt(await app.api("/channeld/integration", { cache: "no-store" }));
235
+ renderAll();
236
+ showStatus("");
237
+ } catch (error) {
238
+ showStatus("");
239
+ showPanelError(error);
240
+ } finally { loading = false; }
241
+ }
242
+ app.loadIntegrations = () => { void load(true); };
243
+
244
+ function setSaving(busy) {
245
+ saving = busy;
246
+ saveButton.disabled = busy || data.editable === false;
247
+ enabledInput.disabled = busy;
248
+ }
249
+
250
+ let envMenuSerial = 0;
251
+
252
+ function envFields() {
253
+ const plugin = knownPlugins(data).find((item) => item.pluginId === accountPlugin.value);
254
+ return (plugin?.account?.env ?? []).filter((field) => ENV_KEY.test(field.key));
255
+ }
256
+
257
+ function closeEnvMenus(except) {
258
+ for (const menu of accountEnv.querySelectorAll(".integration-env-menu")) {
259
+ if (menu === except) continue;
260
+ menu.hidden = true;
261
+ menu.parentElement?.querySelector(".integration-env-key")?.setAttribute("aria-expanded", "false");
262
+ }
263
+ }
264
+
265
+ function addEnvRow(container, entry = {}, existing = false, onRemove = null) {
266
+ const row = document.createElement("div");
267
+ row.className = `integration-env-row${existing ? " is-stored" : ""}`;
268
+ const key = document.createElement("input");
269
+ key.className = "input integration-env-key";
270
+ key.value = entry.key || "";
271
+ key.readOnly = existing;
272
+ key.placeholder = text("integrationsEnvKey");
273
+ key.setAttribute("aria-label", text("integrationsEnvKey"));
274
+ key.autocomplete = "off";
275
+ const value = document.createElement("input");
276
+ value.className = "input integration-env-value";
277
+ value.type = "password";
278
+ value.value = "";
279
+ value.placeholder = existing ? text("integrationsLeaveBlank") : "";
280
+ value.setAttribute("aria-label", text("integrationsEnvValue"));
281
+ value.autocomplete = "new-password";
282
+ let keyControl = key;
283
+ if (!existing) {
284
+ const combo = document.createElement("div");
285
+ combo.className = "integration-env-combo";
286
+ const menu = document.createElement("div");
287
+ menu.className = "integration-env-menu";
288
+ menu.id = `integrationEnvMenu-${++envMenuSerial}`;
289
+ menu.role = "listbox";
290
+ menu.hidden = true;
291
+ key.setAttribute("role", "combobox");
292
+ key.setAttribute("aria-autocomplete", "list");
293
+ key.setAttribute("aria-expanded", "false");
294
+ key.setAttribute("aria-controls", menu.id);
295
+ const hide = () => {
296
+ menu.hidden = true;
297
+ key.setAttribute("aria-expanded", "false");
298
+ };
299
+ const choose = (option) => {
300
+ key.value = option.dataset.key;
301
+ hide();
302
+ value.focus();
303
+ };
304
+ const renderMenu = () => {
305
+ closeEnvMenus(menu);
306
+ const used = new Set([...container.querySelectorAll(".integration-env-key")]
307
+ .map((input) => input.value.trim())
308
+ .filter(Boolean));
309
+ const query = key.value.trim().toLowerCase();
310
+ const matches = envFields().filter((field) => !used.has(field.key)).filter((field) => {
311
+ if (!query) return true;
312
+ return [field.key, field.label, field.description]
313
+ .some((text) => String(text ?? "").toLowerCase().includes(query));
314
+ });
315
+ menu.replaceChildren(...matches.map((field) => {
316
+ const option = document.createElement("button");
317
+ option.type = "button";
318
+ option.className = "integration-env-option";
319
+ option.dataset.key = field.key;
320
+ option.tabIndex = -1;
321
+ option.setAttribute("role", "option");
322
+ const name = document.createElement("span");
323
+ name.className = "integration-env-option-key";
324
+ name.textContent = field.key;
325
+ option.append(name);
326
+ const detail = [field.label, field.description].filter(Boolean).join(" · ");
327
+ if (detail) {
328
+ const description = document.createElement("span");
329
+ description.className = "integration-env-option-desc";
330
+ description.textContent = detail;
331
+ option.append(description);
332
+ }
333
+ option.addEventListener("mousedown", (event) => event.preventDefault());
334
+ option.addEventListener("click", () => choose(option));
335
+ option.addEventListener("keydown", (event) => {
336
+ const options = [...menu.querySelectorAll(".integration-env-option")];
337
+ const index = options.indexOf(option);
338
+ if (event.key === "ArrowDown") {
339
+ event.preventDefault();
340
+ options[(index + 1) % options.length]?.focus();
341
+ } else if (event.key === "ArrowUp") {
342
+ event.preventDefault();
343
+ options[(index - 1 + options.length) % options.length]?.focus();
344
+ } else if (event.key === "Escape") {
345
+ event.preventDefault();
346
+ hide();
347
+ key.focus();
348
+ } else if (event.key === "Enter") {
349
+ event.preventDefault();
350
+ choose(option);
351
+ }
352
+ });
353
+ return option;
354
+ }));
355
+ menu.hidden = matches.length === 0;
356
+ key.setAttribute("aria-expanded", String(!menu.hidden));
357
+ };
358
+ key.addEventListener("focus", renderMenu);
359
+ key.addEventListener("click", renderMenu);
360
+ key.addEventListener("input", renderMenu);
361
+ key.addEventListener("keydown", (event) => {
362
+ if (event.key === "ArrowDown") {
363
+ event.preventDefault();
364
+ if (menu.hidden) renderMenu();
365
+ menu.querySelector(".integration-env-option")?.focus();
366
+ } else if (event.key === "Escape") {
367
+ hide();
368
+ }
369
+ });
370
+ key.addEventListener("blur", () => {
371
+ setTimeout(() => { if (!combo.contains(document.activeElement)) hide(); }, 0);
372
+ });
373
+ combo.append(key, menu);
374
+ keyControl = combo;
375
+ }
376
+ const remove = document.createElement("button");
377
+ remove.type = "button";
378
+ remove.className = "btn ghost small integration-env-remove";
379
+ remove.append(iconNode("subtract"));
380
+ remove.setAttribute("aria-label", text("integrationsRemove"));
381
+ remove.setAttribute("title", text("integrationsRemove"));
382
+ remove.addEventListener("click", () => {
383
+ const currentKey = key.value.trim();
384
+ row.remove();
385
+ onRemove?.(currentKey, existing);
386
+ });
387
+ row.append(keyControl, value, remove);
388
+ container.append(row);
389
+ return row;
390
+ }
391
+
392
+ function readEnv(container) {
393
+ const values = {};
394
+ for (const row of container.querySelectorAll(".integration-env-row")) {
395
+ const key = row.querySelector(".integration-env-key").value.trim();
396
+ const value = row.querySelector(".integration-env-value").value;
397
+ if (!key && !value) continue;
398
+ if (!ENV_KEY.test(key) || Object.hasOwn(values, key)) throw new Error(text("integrationsEnvInvalid"));
399
+ if (value !== "") values[key] = value;
400
+ }
401
+ return values;
402
+ }
403
+
404
+ function fillPlugins(selected) {
405
+ accountPlugin.textContent = "";
406
+ const plugins = knownPlugins(data);
407
+ if (!plugins.length) {
408
+ const option = document.createElement("option");
409
+ option.value = ""; option.textContent = text("integrationsPluginFirst");
410
+ accountPlugin.append(option);
411
+ }
412
+ for (const plugin of plugins) {
413
+ const option = document.createElement("option");
414
+ option.value = plugin.pluginId;
415
+ option.textContent = `${plugin.name} · ${plugin.platform}`;
416
+ accountPlugin.append(option);
417
+ }
418
+ accountPlugin.value = plugins.some((plugin) => plugin.pluginId === selected) ? selected : plugins[0]?.pluginId || "";
419
+ }
420
+
421
+ /** Stable once saved; a blank ID is only a convenience for new accounts. */
422
+ function newAccountId(plugin) {
423
+ const prefix = String(plugin?.platform || "account").replace(/[^A-Za-z0-9._-]/g, "") || "account";
424
+ const bytes = crypto.getRandomValues(new Uint8Array(4));
425
+ return `${prefix}-${[...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
426
+ }
427
+
428
+ function setClearEnv(next) {
429
+ clearEnv = next;
430
+ accountClear.textContent = text(next ? "integrationsKeepEnv" : "integrationsClearEnv");
431
+ accountEnvNote.hidden = !next;
432
+ accountEnvNote.textContent = next ? text("integrationsClearEnvActive") : "";
433
+ accountAddEnv.disabled = next;
434
+ for (const control of accountEnv.querySelectorAll("input, button")) control.disabled = next;
435
+ for (const control of accountSchema.querySelectorAll("input, select, button")) control.disabled = next;
436
+ }
437
+
438
+ function removeStoredKey(key) {
439
+ if (!key || !accountDraft) return;
440
+ if ((accountDraft.storedKeys || []).includes(key) && !accountDraft.envDelete.includes(key)) {
441
+ accountDraft.envDelete.push(key);
442
+ }
443
+ accountDraft.envKeys = (accountDraft.envKeys || []).filter((item) => item !== key);
444
+ if (accountDraft.envSet) delete accountDraft.envSet[key];
445
+ }
446
+
447
+ function syncAccountSchema() {
448
+ const plugin = knownPlugins(data).find((item) => item.pluginId === accountPlugin.value);
449
+ closeEnvMenus();
450
+ renderAccountSchema(accountSchema, plugin, accountDraft?.id ? accountDraft : null, text);
451
+ accountSchemaField.hidden = accountSchema.hidden;
452
+ // Without a declared schema the raw env rows are the only way to configure
453
+ // the account, so keep them open; schema-backed plugins can collapse them.
454
+ accountAdvanced.open = accountSchema.hidden;
455
+ }
456
+
457
+ function openAccount(account = null, presetPlugin = "") {
458
+ if (data.editable === false) return;
459
+ if (!knownPlugins(data).length) { showPanelError(text("integrationsPluginFirst")); return; }
460
+ accountDraft = account ? {
461
+ ...account,
462
+ storedKeys: [...(account.storedKeys || account.envKeys || [])],
463
+ envSet: { ...(account.envSet || {}) },
464
+ envDelete: [...(account.envDelete || [])],
465
+ } : { id: "", platform: "", pluginId: presetPlugin, envKeys: [], storedKeys: [], envSet: {}, envDelete: [], envClear: false, state: "unknown", lastError: "" };
466
+ accountId.value = account?.id || "";
467
+ accountId.readOnly = Boolean(account);
468
+ hideAccountError();
469
+ fillPlugins(account?.pluginId || presetPlugin);
470
+ syncAccountSchema();
471
+ accountEnv.textContent = "";
472
+ const keys = account?.envClear ? account.storedKeys : account?.envKeys || [];
473
+ for (const key of keys) addEnvRow(accountEnv, { key }, true, removeStoredKey);
474
+ if (!keys.length) addEnvRow(accountEnv);
475
+ setClearEnv(Boolean(account?.envClear));
476
+ accountDialog.showModal();
477
+ accountPlugin.focus();
478
+ }
479
+
480
+ function closeAccount() {
481
+ if (accountDialog.open) accountDialog.close();
482
+ accountDraft = null;
483
+ }
484
+
485
+ accountForm.addEventListener("submit", (event) => {
486
+ event.preventDefault();
487
+ if (!accountDraft) return;
488
+ hideAccountError();
489
+ const pluginId = accountPlugin.value;
490
+ const plugin = knownPlugins(data).find((item) => item.pluginId === pluginId);
491
+ if (!plugin) return showAccountError(text("integrationsAccountInvalid"));
492
+ const id = accountDraft.id || accountId.value.trim() || newAccountId(plugin);
493
+ if (!IDENTIFIER.test(id)) return showAccountError(text("integrationsAccountInvalid"));
494
+ if (data.accounts.some((item) => item.id === id && item.id !== accountDraft.id)) {
495
+ return showAccountError(text("integrationsDuplicateAccount"));
496
+ }
497
+ let values;
498
+ try { values = clearEnv ? {} : readEnv(accountEnv); }
499
+ catch (error) { return showAccountError(error); }
500
+ let schema;
501
+ try { schema = readAccountSchema(accountSchema, text); }
502
+ catch (error) { return showAccountError(error); }
503
+ // A schema field and a free-form env row can name the same key: the schema wins.
504
+ for (const key of schema.keys) delete values[key];
505
+ const schemaValues = clearEnv ? {} : schema.values;
506
+ const envSet = clearEnv ? {} : { ...(accountDraft.envSet || {}), ...values, ...schemaValues };
507
+ const deleted = new Set(clearEnv ? [] : accountDraft.envDelete || []);
508
+ for (const key of Object.keys(values)) deleted.delete(key);
509
+ for (const key of Object.keys(schemaValues)) deleted.delete(key);
510
+ const remaining = (accountDraft.envKeys || []).filter((key) => !deleted.has(key));
511
+ const next = {
512
+ id,
513
+ platform: plugin.platform,
514
+ pluginId: plugin.pluginId,
515
+ state: accountDraft.state,
516
+ lastError: accountDraft.lastError,
517
+ envKeys: clearEnv ? [] : [...new Set([...remaining, ...Object.keys(envSet)])],
518
+ storedKeys: accountDraft.storedKeys || [],
519
+ envSet,
520
+ envDelete: clearEnv ? [] : [...deleted].filter((key) => !Object.hasOwn(envSet, key)),
521
+ envClear: clearEnv,
522
+ };
523
+ data.accounts = accountDraft.id
524
+ ? data.accounts.map((item) => item.id === accountDraft.id ? next : item)
525
+ : [...data.accounts, next];
526
+ renderAccounts();
527
+ renderPlugins();
528
+ closeAccount();
529
+ showStatus(text("integrationsAccountSaved"));
530
+ });
531
+
532
+ async function save() {
533
+ if (saving || data.editable === false) return;
534
+ if (data.enabled && !enabledInput.checked && !(await app.confirmAction(text("integrationsDisableConfirm")))) {
535
+ enabledInput.checked = true;
536
+ applyEnabledState();
537
+ return;
538
+ }
539
+ hidePanelError();
540
+ hideRulesError();
541
+ if (!data.accounts.length) return showPanelError(text("integrationsNeedAccount"));
542
+ const rulesState = rulesSection.current();
543
+ let rules;
544
+ if (rulesState.editor) {
545
+ if (rulesState.errors.length) return;
546
+ try { rules = checkRules(rulesState.value, data.accounts, text); }
547
+ catch (error) { return rulesSection.showMessage(error.message); }
548
+ } else {
549
+ try { rules = parseRules(rulesState.text, data.accounts, text); }
550
+ catch (error) { return showRulesError(error.message); }
551
+ }
552
+ const inboundState = inboundSection.current();
553
+ let inbound;
554
+ if (inboundState.editor) {
555
+ if (inboundState.errors.length) return;
556
+ try { inbound = checkInbound(inboundState.value, data.accounts); }
557
+ catch (error) { return inboundSection.showMessage(error.message); }
558
+ } else {
559
+ try { inbound = parseInbound(inboundState.text, data.accounts, text); }
560
+ catch (error) { return inboundSection.showMessage(error.message); }
561
+ }
562
+ const inboundChanged = JSON.stringify(inbound) !== initialInbound;
563
+ setSaving(true);
564
+ try {
565
+ adopt(await app.api("/channeld/integration", {
566
+ method: "PUT",
567
+ body: JSON.stringify({
568
+ enabled: enabledInput.checked,
569
+ accounts: data.accounts.map(accountBody),
570
+ rules,
571
+ ...(inboundChanged ? { inbound } : {}),
572
+ }),
573
+ }));
574
+ const enabled = data.enabled;
575
+ await load(true);
576
+ if (panelError.hidden) showStatus(text(enabled ? "integrationsSavedEnabled" : "integrationsSavedDisabled"));
577
+ } catch (error) { showPanelError(error); }
578
+ finally { setSaving(false); }
579
+ }
580
+
581
+ function openUpload() {
582
+ if (data.editable === false) return;
583
+ pluginForm.reset();
584
+ pluginUploadSource = "";
585
+ pluginUploadName = "";
586
+ hidePluginError();
587
+ pluginDialog.showModal();
588
+ pluginFile.focus();
589
+ }
590
+
591
+ pluginFile.addEventListener("change", async () => {
592
+ const file = pluginFile.files?.[0];
593
+ pluginUploadSource = "";
594
+ pluginUploadName = "";
595
+ if (!file) return;
596
+ if (file.size > MAX_SOURCE) return showPluginError(text("integrationsSourceTooLarge"));
597
+ try {
598
+ pluginUploadSource = await file.text();
599
+ pluginUploadName = file.name;
600
+ hidePluginError();
601
+ } catch (error) { showPluginError(error); }
602
+ });
603
+
604
+ pluginForm.addEventListener("submit", async (event) => {
605
+ event.preventDefault();
606
+ hidePluginError();
607
+ const name = pluginUploadName || "plugin.js", source = pluginUploadSource;
608
+ if (!PLUGIN_NAME.test(name)) return showPluginError(text("integrationsNameRequired"));
609
+ if (!source.trim()) return showPluginError(text("integrationsSourceRequired"));
610
+ if (new TextEncoder().encode(source).length > MAX_SOURCE) return showPluginError(text("integrationsSourceTooLarge"));
611
+ const submit = $("#btnSaveIntegrationPlugin");
612
+ submit.disabled = true;
613
+ try {
614
+ const result = await app.api("/channeld/plugins", {
615
+ method: "POST",
616
+ body: JSON.stringify({ name, source }),
617
+ });
618
+ const plugin = {
619
+ pluginId: result.pluginId,
620
+ name: result.name,
621
+ platform: result.platform,
622
+ ...(result.displayName ? { displayName: result.displayName } : {}),
623
+ ...(result.account ? { account: result.account } : {}),
624
+ };
625
+ data.plugins = [...data.plugins.filter((item) => item.pluginId !== plugin.pluginId), plugin];
626
+ renderPlugins();
627
+ pluginDialog.close();
628
+ showStatus(text("integrationsUploaded"));
629
+ openAccount(null, plugin.pluginId);
630
+ } catch (error) { showPluginError(error); }
631
+ finally { submit.disabled = false; }
632
+ });
633
+
634
+ $("#btnAddAccountEnv").addEventListener("click", () => addEnvRow(accountEnv).querySelector(".integration-env-key").focus());
635
+ accountPlugin.addEventListener("change", syncAccountSchema);
636
+ accountClear.addEventListener("click", () => setClearEnv(!clearEnv));
637
+ enabledInput.addEventListener("change", applyEnabledState);
638
+ addAccountButton.addEventListener("click", () => openAccount(null));
639
+ uploadPluginButton.addEventListener("click", openUpload);
640
+ $("#btnRefreshIntegrations").addEventListener("click", () => void load(true));
641
+ saveButton.addEventListener("click", () => void save());
642
+ $("#btnCloseIntegrationAccount").addEventListener("click", closeAccount);
643
+ $("#btnCancelIntegrationAccount").addEventListener("click", closeAccount);
644
+ accountDialog.addEventListener("cancel", (event) => { event.preventDefault(); closeAccount(); });
645
+ $("#btnCloseIntegrationPlugin").addEventListener("click", () => pluginDialog.close());
646
+ $("#btnCancelIntegrationPlugin").addEventListener("click", () => pluginDialog.close());
647
+ pluginDialog.addEventListener("cancel", (event) => { event.preventDefault(); pluginDialog.close(); });
648
+ }