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

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