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

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