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

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 (183) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/LICENSE +21 -0
  3. package/README.md +77 -36
  4. package/README.zh-CN.md +82 -41
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +6905 -2764
  7. package/package.json +33 -3
  8. package/packages/chat-room-channeld/README.md +315 -0
  9. package/packages/chat-room-channeld/dist/feishu-adapter.js +1262 -0
  10. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  11. package/packages/chat-room-channeld/src/adapter.ts +509 -0
  12. package/packages/chat-room-channeld/src/cli.ts +124 -0
  13. package/packages/chat-room-channeld/src/config.ts +269 -0
  14. package/packages/chat-room-channeld/src/delivery.ts +163 -0
  15. package/packages/chat-room-channeld/src/feishu-adapter.ts +303 -0
  16. package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
  17. package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
  18. package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
  19. package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
  20. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
  21. package/packages/chat-room-channeld/src/framing.ts +128 -0
  22. package/packages/chat-room-channeld/src/host-helpers.ts +52 -0
  23. package/packages/chat-room-channeld/src/host.ts +627 -0
  24. package/packages/chat-room-channeld/src/inbound.ts +26 -0
  25. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  26. package/packages/chat-room-channeld/src/log.ts +26 -0
  27. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  28. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  29. package/packages/chat-room-channeld/src/published.ts +37 -0
  30. package/packages/chat-room-channeld/src/rules.ts +127 -0
  31. package/packages/chat-room-channeld/src/state.ts +502 -0
  32. package/packages/chat-room-channeld/src/stats.ts +209 -0
  33. package/plugin.ts +22 -5
  34. package/server/addressing-routes.ts +130 -0
  35. package/server/admin-state.ts +13 -13
  36. package/server/app.ts +95 -0
  37. package/server/assets/NOTICE.txt +3 -2
  38. package/server/assets/SHIKI-LICENSE +22 -0
  39. package/server/assets/base.css +24 -10
  40. package/server/assets/chat/announcements.js +70 -7
  41. package/server/assets/chat/doc-preview.js +187 -39
  42. package/server/assets/chat/events.js +3 -0
  43. package/server/assets/chat/files.js +46 -4
  44. package/server/assets/chat/forward.js +69 -0
  45. package/server/assets/chat/index.js +4 -0
  46. package/server/assets/chat/integration-editor.js +163 -0
  47. package/server/assets/chat/integration-values.js +124 -0
  48. package/server/assets/chat/integrations.js +498 -0
  49. package/server/assets/chat/locales/de.js +45 -4
  50. package/server/assets/chat/locales/es.js +45 -4
  51. package/server/assets/chat/locales/fr.js +45 -4
  52. package/server/assets/chat/locales/it.js +45 -4
  53. package/server/assets/chat/locales/ja.js +45 -4
  54. package/server/assets/chat/locales/ko.js +45 -4
  55. package/server/assets/chat/markdown-footnotes.js +115 -0
  56. package/server/assets/chat/markdown.js +46 -43
  57. package/server/assets/chat/messages.js +5 -5
  58. package/server/assets/chat/office-preview.js +69 -0
  59. package/server/assets/chat/palette.js +1 -1
  60. package/server/assets/chat/panels.js +36 -0
  61. package/server/assets/chat/recall.js +58 -7
  62. package/server/assets/chat/receipts.js +15 -3
  63. package/server/assets/chat/reminders.js +69 -8
  64. package/server/assets/chat/replies.js +7 -1
  65. package/server/assets/chat/resource-format.js +11 -0
  66. package/server/assets/chat/settings.js +30 -2
  67. package/server/assets/chat/shiki.js +87 -0
  68. package/server/assets/chat/side-pane.js +9 -3
  69. package/server/assets/chat/state.js +107 -11
  70. package/server/assets/chat/system-events.js +32 -0
  71. package/server/assets/chat/system-messages.js +23 -12
  72. package/server/assets/chat/task-row.js +0 -6
  73. package/server/assets/chat/tasks.js +121 -33
  74. package/server/assets/code-highlight.css +74 -62
  75. package/server/assets/conversation.css +126 -25
  76. package/server/assets/doc-preview.css +36 -3
  77. package/server/assets/files.css +5 -0
  78. package/server/assets/fluent-icons.svg +2 -0
  79. package/server/assets/monaco/LICENSE +21 -0
  80. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  81. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  82. package/server/assets/monaco/editor.worker.js +45 -0
  83. package/server/assets/monaco/integration-rules.css +1 -0
  84. package/server/assets/monaco/integration-rules.js +1297 -0
  85. package/server/assets/monaco/json.worker.js +77 -0
  86. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  87. package/server/assets/office/docx.bundle.js +33 -0
  88. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  89. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  90. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  91. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  92. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  93. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  94. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  95. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  96. package/server/assets/{HIGHLIGHT-LICENSE → office/licenses/zrender-LICENSE.txt} +2 -2
  97. package/server/assets/office/pptx.bundle.js +104 -0
  98. package/server/assets/office/xlsx.bundle.js +141 -0
  99. package/server/assets/recall.css +5 -4
  100. package/server/assets/responsive.css +52 -8
  101. package/server/assets/settings.css +73 -1
  102. package/server/assets/shiki.bundle.js +152 -0
  103. package/server/assets/tasks.css +57 -7
  104. package/server/channel-integration.ts +519 -0
  105. package/server/channel-settings.ts +77 -0
  106. package/server/channels.ts +557 -0
  107. package/server/chat-server.ts +33 -558
  108. package/server/chat.html +195 -22
  109. package/server/http-server.ts +3 -182
  110. package/server/resource-routes.ts +16 -16
  111. package/server/routes/inbox.ts +100 -0
  112. package/server/routes/pages.ts +83 -0
  113. package/server/routes/questions.ts +39 -0
  114. package/server/routes/room-actions.ts +162 -0
  115. package/server/routes/rooms.ts +160 -0
  116. package/server/startup.ts +84 -0
  117. package/server/sw.js +5 -2
  118. package/server/task-routes.ts +1 -1
  119. package/skills/chatroom/SKILL.md +1 -1
  120. package/src/center/center-client.ts +71 -1
  121. package/src/config/file-config.ts +29 -42
  122. package/src/platform/http-server.ts +182 -0
  123. package/src/protocol/addressing.ts +21 -0
  124. package/src/protocol/config.ts +58 -0
  125. package/src/protocol/room.ts +51 -0
  126. package/src/rooms/resources.ts +26 -16
  127. package/src/rooms/room-service.ts +2 -48
  128. package/src/rooms/storage.ts +329 -0
  129. package/src/rooms/tasks.ts +21 -5
  130. package/src/runtime/v2-plugin.ts +8 -2
  131. package/src/runtime/watch.ts +4 -3
  132. package/src/state/pg-database.ts +183 -0
  133. package/src/state/pg-migrate.ts +175 -0
  134. package/src/state/pg-sql.mjs +175 -0
  135. package/src/state/pg-worker.mjs +148 -0
  136. package/src/state/sqlite-announcements.ts +25 -0
  137. package/src/state/sqlite-database.ts +121 -0
  138. package/src/state/sqlite-legacy.ts +90 -0
  139. package/src/state/sqlite-members.ts +155 -0
  140. package/src/state/sqlite-messages.ts +288 -0
  141. package/src/state/sqlite-resources.ts +39 -0
  142. package/src/state/sqlite-rooms.ts +87 -0
  143. package/src/state/sqlite-schema.ts +80 -0
  144. package/src/state/sqlite-state-store.ts +33 -0
  145. package/src/state/sqlite-state.ts +15 -866
  146. package/src/state/sqlite-tasks.ts +65 -0
  147. package/src/state/sqlite-transaction.ts +13 -0
  148. package/src/state/sqlite.ts +21 -1
  149. package/src/state/store.ts +13 -3
  150. package/src/tui/app.mjs +32 -19
  151. package/src/tui/config.mjs +12 -4
  152. package/src/tui/http.mjs +16 -2
  153. package/src/tui/i18n.mjs +38 -0
  154. package/src/tui/info-app.mjs +50 -51
  155. package/src/tui/info-content.mjs +79 -44
  156. package/src/tui/join-app.mjs +9 -9
  157. package/src/tui/locales/en.mjs +349 -0
  158. package/src/tui/locales/zh-CN.mjs +349 -0
  159. package/src/tui/main.mjs +85 -37
  160. package/src/tui/markdown.mjs +3 -2
  161. package/src/tui/mentions.mjs +3 -1
  162. package/src/tui/message-app.mjs +22 -21
  163. package/src/tui/message-view.mjs +2 -1
  164. package/src/tui/palette-app.mjs +9 -8
  165. package/src/tui/palette.mjs +30 -24
  166. package/src/tui/prefs.mjs +92 -0
  167. package/src/tui/reminder-app.mjs +18 -17
  168. package/src/tui/room-settings-app.mjs +30 -28
  169. package/src/tui/settings-app.mjs +153 -0
  170. package/src/tui/ui-content.mjs +65 -86
  171. package/src/tui/ui-help.mjs +73 -0
  172. package/src/tui/ui-overlay-view.mjs +23 -7
  173. package/src/tui/ui-suggest.mjs +6 -5
  174. package/src/tui/ui-theme.mjs +37 -33
  175. package/src/tui/ui-view.mjs +22 -7
  176. package/src/tui/ui.mjs +15 -3
  177. package/src/web/editor.worker.ts +1 -0
  178. package/src/web/integration-rules-editor.ts +439 -0
  179. package/src/web/integration-rules.ts +22 -0
  180. package/src/web/integration-schema.ts +228 -0
  181. package/src/web/json.worker.ts +1 -0
  182. package/src/web/office-viewer.ts +221 -0
  183. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -0,0 +1,439 @@
1
+ /// <reference lib="dom" />
2
+
3
+ import * as monaco from "monaco-editor/editor/editor.api";
4
+ import { jsonDefaults } from "monaco-editor/languages/features/json/register";
5
+ import "monaco-editor/languages/definitions/yaml/register";
6
+ import { isMap, isScalar, isSeq, parseDocument, stringify as stringifyYaml } from "yaml";
7
+ import {
8
+ buildInboundSchema,
9
+ buildRulesSchema,
10
+ formatPath,
11
+ validateAgainstSchema,
12
+ type JsonSchema,
13
+ type RuleAccount,
14
+ type SchemaIssue,
15
+ } from "./integration-schema";
16
+
17
+ export type RulesKind = "rules" | "inbound";
18
+ export type RulesFormat = "json" | "yaml";
19
+ export type EditorError = { line: number; column: number; path: string; message: string };
20
+ export type EditorValidation = {
21
+ kind: RulesKind;
22
+ format: RulesFormat;
23
+ text: string;
24
+ value: unknown;
25
+ valid: boolean;
26
+ errors: EditorError[];
27
+ };
28
+ export type IntegrationRulesEditor = {
29
+ getKind: () => RulesKind;
30
+ getFormat: () => RulesFormat;
31
+ setFormat: (format: RulesFormat) => void;
32
+ setValue: (value: unknown) => void;
33
+ setAccounts: (accounts: RuleAccount[]) => void;
34
+ validate: () => EditorValidation;
35
+ reveal: (line: number, column: number) => void;
36
+ setReadOnly: (readOnly: boolean) => void;
37
+ focus: () => void;
38
+ dispose: () => void;
39
+ };
40
+ type Options = {
41
+ kind: RulesKind;
42
+ container: HTMLElement;
43
+ value: unknown;
44
+ format?: RulesFormat;
45
+ accounts: RuleAccount[];
46
+ onChange?: (validation: EditorValidation) => void;
47
+ };
48
+
49
+ type RegistryEntry = { kind: RulesKind; uri: string; schema: JsonSchema; modelUri: string };
50
+ const registry = new Map<RulesKind, RegistryEntry>();
51
+ let completionRegistered = false;
52
+ let themeObserver: MutationObserver | null = null;
53
+ let themeMedia: MediaQueryList | null = null;
54
+
55
+ const scope = globalThis as typeof globalThis & { MonacoEnvironment?: { getWorker?: (workerId: string, label: string) => Worker } };
56
+ scope.MonacoEnvironment = {
57
+ getWorker(_workerId, label) {
58
+ return new Worker(`/assets/monaco/${label === "json" ? "json" : "editor"}.worker.js`);
59
+ },
60
+ };
61
+
62
+ function isDarkTheme(): boolean {
63
+ const theme = document.documentElement.dataset.theme;
64
+ if (theme === "dark") return true;
65
+ return theme !== "light" && theme !== "forest" && theme !== "sand" && matchMedia("(prefers-color-scheme: dark)").matches;
66
+ }
67
+
68
+ function applyTheme() {
69
+ const style = getComputedStyle(document.documentElement);
70
+ const read = (name: string, fallback: string) => style.getPropertyValue(name).trim() || fallback;
71
+ monaco.editor.defineTheme("chatroom-light", {
72
+ base: "vs",
73
+ inherit: true,
74
+ rules: [],
75
+ colors: {
76
+ "editor.background": read("--surface", "#fffefa"),
77
+ "editorGutter.background": read("--surface", "#fffefa"),
78
+ "editor.lineHighlightBackground": read("--surface-2", "#f2f0e8"),
79
+ "editorLineNumber.foreground": read("--ink-3", "#63716b"),
80
+ },
81
+ });
82
+ monaco.editor.defineTheme("chatroom-dark", {
83
+ base: "vs-dark",
84
+ inherit: true,
85
+ rules: [],
86
+ colors: { "editor.background": read("--surface", "#182522") },
87
+ });
88
+ monaco.editor.setTheme(isDarkTheme() ? "chatroom-dark" : "chatroom-light");
89
+ }
90
+
91
+ function watchTheme() {
92
+ applyTheme();
93
+ if (themeObserver) return;
94
+ themeObserver = new MutationObserver(applyTheme);
95
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
96
+ themeMedia = matchMedia("(prefers-color-scheme: dark)");
97
+ themeMedia.addEventListener("change", applyTheme);
98
+ }
99
+
100
+ function publishJsonSchemas() {
101
+ jsonDefaults.setDiagnosticsOptions({
102
+ validate: false,
103
+ allowComments: false,
104
+ enableSchemaRequest: false,
105
+ schemas: [...registry.values()].map((entry) => ({
106
+ uri: entry.uri,
107
+ fileMatch: [`*integration-${entry.kind}*`],
108
+ schema: entry.schema,
109
+ })),
110
+ });
111
+ }
112
+
113
+ function schemaAtPath(root: JsonSchema, path: Array<string | number>, key?: string): JsonSchema | undefined {
114
+ let schema: JsonSchema | undefined = root;
115
+ for (const part of path) {
116
+ if (!schema) return undefined;
117
+ if (typeof part === "number") schema = schema.items;
118
+ else schema = schema.properties?.[part];
119
+ }
120
+ return key ? schema?.properties?.[key] : schema;
121
+ }
122
+
123
+ function nodeAtPath(node: any, path: Array<string | number>): any {
124
+ let current = node;
125
+ for (const part of path) {
126
+ if (!current) return current;
127
+ if (typeof part === "number") {
128
+ if (!isSeq(current)) return current;
129
+ current = current.items[part];
130
+ } else {
131
+ if (!isMap(current)) return current;
132
+ const pair = current.items.find((item: any) => isScalar(item.key) && item.key.value === part);
133
+ if (!pair) return current;
134
+ current = pair.value;
135
+ }
136
+ }
137
+ return current;
138
+ }
139
+
140
+ function pathAtOffset(node: any, offset: number, path: Array<string | number> = []): Array<string | number> | null {
141
+ const range = node?.range;
142
+ if (!Array.isArray(range) || offset < range[0] || offset > range[2]) return null;
143
+ if (isSeq(node)) {
144
+ for (let index = 0; index < node.items.length; index++) {
145
+ const found = pathAtOffset(node.items[index], offset, [...path, index]);
146
+ if (found) return found;
147
+ }
148
+ } else if (isMap(node)) {
149
+ for (const pair of node.items) {
150
+ if (!isScalar(pair.key) || typeof pair.key.value !== "string") continue;
151
+ const found = pathAtOffset(pair.value, offset, [...path, pair.key.value]);
152
+ if (found) return found;
153
+ }
154
+ }
155
+ return path;
156
+ }
157
+
158
+ function valueSuggestions(schema: JsonSchema, model: monaco.editor.ITextModel, position: monaco.Position) {
159
+ const values = schema.const !== undefined ? [schema.const] : schema.enum;
160
+ if (!values) return [];
161
+ const word = model.getWordUntilPosition(position);
162
+ const range = monaco.Range.fromPositions(
163
+ new monaco.Position(position.lineNumber, word.startColumn),
164
+ new monaco.Position(position.lineNumber, word.endColumn),
165
+ );
166
+ return values.map((value) => ({
167
+ label: String(value),
168
+ kind: monaco.languages.CompletionItemKind.Value,
169
+ insertText: String(value),
170
+ range,
171
+ detail: schema.description,
172
+ }));
173
+ }
174
+
175
+ function ensureYamlCompletion() {
176
+ if (completionRegistered) return;
177
+ completionRegistered = true;
178
+ monaco.languages.registerCompletionItemProvider("yaml", {
179
+ triggerCharacters: [":", " ", "-"],
180
+ provideCompletionItems(model, position) {
181
+ const entry = [...registry.values()].find((item) => item.modelUri === model.uri.toString());
182
+ if (!entry) return { suggestions: [] };
183
+ let doc: any;
184
+ try { doc = parseDocument(model.getValue()); } catch { return { suggestions: [] }; }
185
+ const root = doc.contents;
186
+ const offset = model.getOffsetAt(position);
187
+ const path = pathAtOffset(root, offset) ?? [];
188
+ const line = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
189
+ const match = /^\s*(?:-\s*)?["']?([A-Za-z0-9_.-]+)["']?\s*:\s*(.*)$/.exec(line);
190
+ if (match) {
191
+ const key = match[1]!;
192
+ const container = path[path.length - 1] === key ? path.slice(0, -1) : path;
193
+ const schema = schemaAtPath(entry.schema, container, key);
194
+ return { suggestions: schema ? valueSuggestions(schema, model, position) : [] };
195
+ }
196
+ const schema = schemaAtPath(entry.schema, path);
197
+ const properties = schema?.properties;
198
+ if (!properties) return { suggestions: [] };
199
+ const existing = new Set<string>();
200
+ const container = nodeAtPath(root, path);
201
+ if (isMap(container)) {
202
+ for (const pair of container.items) if (isScalar(pair.key) && typeof pair.key.value === "string") existing.add(pair.key.value);
203
+ }
204
+ const word = model.getWordUntilPosition(position);
205
+ const range = monaco.Range.fromPositions(
206
+ new monaco.Position(position.lineNumber, word.startColumn),
207
+ new monaco.Position(position.lineNumber, word.endColumn),
208
+ );
209
+ return {
210
+ suggestions: Object.entries(properties)
211
+ .filter(([key]) => !existing.has(key))
212
+ .map(([key, child]) => ({
213
+ label: key,
214
+ kind: monaco.languages.CompletionItemKind.Property,
215
+ insertText: `${key}: `,
216
+ range,
217
+ detail: child.type,
218
+ documentation: child.description,
219
+ })),
220
+ };
221
+ },
222
+ });
223
+ }
224
+
225
+ type ParseResult = {
226
+ value?: unknown;
227
+ doc?: any;
228
+ failure?: { line: number; column: number; message: string };
229
+ };
230
+
231
+ function lineStarts(text: string): number[] {
232
+ const starts = [0];
233
+ for (let index = 0; index < text.length; index++) if (text[index] === "\n") starts.push(index + 1);
234
+ return starts;
235
+ }
236
+
237
+ function positionAt(starts: number[], offset: number): { line: number; column: number } {
238
+ let low = 0, high = starts.length - 1;
239
+ while (low < high) {
240
+ const middle = Math.ceil((low + high) / 2);
241
+ if ((starts[middle] ?? 0) <= offset) low = middle;
242
+ else high = middle - 1;
243
+ }
244
+ return { line: low + 1, column: offset - (starts[low] ?? 0) + 1 };
245
+ }
246
+
247
+ function cleanSyntaxMessage(message: string): string {
248
+ return message
249
+ .replace(/ in JSON at position \d+.*$/i, "")
250
+ .replace(/\s*\(line \d+ column \d+\)$/i, "")
251
+ .replace(/\s+at line \d+, column \d+.*$/i, "")
252
+ .trim();
253
+ }
254
+
255
+ function parseJson(text: string): ParseResult {
256
+ if (!text.trim()) return { failure: { line: 1, column: 1, message: "Rules cannot be empty." } };
257
+ try {
258
+ const value = JSON.parse(text);
259
+ let doc;
260
+ try { doc = parseDocument(text); } catch { doc = undefined; }
261
+ return { value, doc };
262
+ } catch (error) {
263
+ const message = String((error as Error).message || error);
264
+ const starts = lineStarts(text);
265
+ const offset = Number(/position (\d+)/.exec(message)?.[1] ?? 0);
266
+ const position = positionAt(starts, offset);
267
+ return { failure: { ...position, message: cleanSyntaxMessage(message) || "Invalid JSON." } };
268
+ }
269
+ }
270
+
271
+ function parseYaml(text: string): ParseResult {
272
+ if (!text.trim()) return { failure: { line: 1, column: 1, message: "Rules cannot be empty." } };
273
+ const doc = parseDocument(text, { prettyErrors: true });
274
+ if (doc.errors.length) {
275
+ const error = doc.errors[0]!;
276
+ const starts = lineStarts(text);
277
+ const offset = Number(error.pos?.[0] ?? 0);
278
+ const fallback = positionAt(starts, offset);
279
+ const line = error.linePos?.[0]?.line ?? fallback.line;
280
+ const column = error.linePos?.[0]?.col ?? fallback.column;
281
+ return { failure: { line, column, message: cleanSyntaxMessage(error.message) || "Invalid YAML." } };
282
+ }
283
+ try {
284
+ return { value: doc.toJS(), doc };
285
+ } catch (error) {
286
+ return { failure: { line: 1, column: 1, message: String((error as Error).message || error) } };
287
+ }
288
+ }
289
+
290
+ function issuePosition(issue: SchemaIssue, doc: any, text: string, kind: RulesKind): EditorError {
291
+ const path = formatPath(kind === "inbound" ? "inbound" : "rules", issue.path);
292
+ if (doc) {
293
+ const node = nodeAtPath(doc.contents, issue.path);
294
+ const range = node?.range;
295
+ if (Array.isArray(range)) {
296
+ const starts = lineStarts(text);
297
+ const start = positionAt(starts, range[0]);
298
+ return { ...start, path, message: issue.message };
299
+ }
300
+ }
301
+ return { line: 1, column: 1, path, message: issue.message };
302
+ }
303
+
304
+ function stringifyValue(value: unknown, format: RulesFormat): string {
305
+ if (format === "yaml") return stringifyYaml(value, { indent: 2, lineWidth: 0 });
306
+ return JSON.stringify(value, null, 2);
307
+ }
308
+
309
+ function formatLabel(format: RulesFormat): string {
310
+ return format === "yaml" ? "YAML" : "JSON";
311
+ }
312
+
313
+ export function createIntegrationRulesEditor(options: Options): IntegrationRulesEditor {
314
+ const kind = options.kind;
315
+ let format: RulesFormat = options.format ?? "json";
316
+ let accounts = options.accounts;
317
+ let schema = kind === "inbound" ? buildInboundSchema(accounts) : buildRulesSchema(accounts);
318
+ const entry: RegistryEntry = {
319
+ kind,
320
+ uri: `inmemory://chat/integration-${kind}.schema.json`,
321
+ schema,
322
+ modelUri: `inmemory://chat/integration-${kind}.json`,
323
+ };
324
+ registry.set(kind, entry);
325
+ publishJsonSchemas();
326
+ ensureYamlCompletion();
327
+ watchTheme();
328
+
329
+ const text = stringifyValue(options.value ?? [], format);
330
+ const model = monaco.editor.createModel(text, formatLabel(format).toLowerCase(), monaco.Uri.parse(entry.modelUri));
331
+ const editor = monaco.editor.create(options.container, {
332
+ model,
333
+ theme: isDarkTheme() ? "chatroom-dark" : "chatroom-light",
334
+ automaticLayout: true,
335
+ ariaLabel: kind === "inbound" ? "Inbound routes" : "Integration rules",
336
+ minimap: { enabled: false },
337
+ scrollBeyondLastLine: false,
338
+ fontSize: 12,
339
+ lineNumbersMinChars: 3,
340
+ tabSize: 2,
341
+ insertSpaces: true,
342
+ autoIndent: "none",
343
+ autoClosingBrackets: "never",
344
+ autoClosingQuotes: "never",
345
+ wordWrap: "on",
346
+ fixedOverflowWidgets: true,
347
+ renderLineHighlight: "line",
348
+ overviewRulerLanes: 0,
349
+ hideCursorInOverviewRuler: true,
350
+ padding: { top: 8, bottom: 8 },
351
+ scrollbar: { verticalScrollbarSize: 8, horizontalScrollbarSize: 8 },
352
+ suggest: { showWords: false },
353
+ });
354
+
355
+ const validate = (): EditorValidation => {
356
+ const current = model.getValue();
357
+ const parsed = format === "yaml" ? parseYaml(current) : parseJson(current);
358
+ const errors: EditorError[] = [];
359
+ if (parsed.failure) {
360
+ errors.push({ line: parsed.failure.line, column: parsed.failure.column, path: "", message: parsed.failure.message });
361
+ } else {
362
+ for (const issue of validateAgainstSchema(parsed.value, schema)) {
363
+ errors.push(issuePosition(issue, parsed.doc, current, kind));
364
+ }
365
+ }
366
+ errors.sort((left, right) => left.line - right.line || left.column - right.column);
367
+ monaco.editor.setModelMarkers(model, "integration-rules", errors.map((error) => {
368
+ const lineLength = model.getLineMaxColumn(Math.min(error.line, model.getLineCount()));
369
+ return {
370
+ severity: monaco.MarkerSeverity.Error,
371
+ message: error.message,
372
+ startLineNumber: error.line,
373
+ startColumn: error.column,
374
+ endLineNumber: error.line,
375
+ endColumn: Math.max(error.column + 1, Math.min(lineLength, error.column + 80)),
376
+ };
377
+ }));
378
+ return { kind, format, text: current, value: parsed.value, valid: errors.length === 0, errors };
379
+ };
380
+
381
+ const emit = () => {
382
+ const validation = validate();
383
+ options.onChange?.(validation);
384
+ return validation;
385
+ };
386
+
387
+ const setValue = (value: unknown) => {
388
+ const next = stringifyValue(value ?? [], format);
389
+ if (next === model.getValue()) emit();
390
+ else model.setValue(next);
391
+ };
392
+
393
+ const setFormat = (next: RulesFormat) => {
394
+ if (next === format) return;
395
+ const parsed = format === "yaml" ? parseYaml(model.getValue()) : parseJson(model.getValue());
396
+ format = next;
397
+ monaco.editor.setModelLanguage(model, formatLabel(format).toLowerCase());
398
+ if (!parsed.failure) {
399
+ const nextText = stringifyValue(parsed.value, format);
400
+ if (nextText !== model.getValue()) model.setValue(nextText);
401
+ else emit();
402
+ } else {
403
+ emit();
404
+ }
405
+ };
406
+
407
+ const setAccounts = (next: RuleAccount[]) => {
408
+ accounts = next;
409
+ schema = kind === "inbound" ? buildInboundSchema(accounts) : buildRulesSchema(accounts);
410
+ entry.schema = schema;
411
+ publishJsonSchemas();
412
+ emit();
413
+ };
414
+
415
+ const change = model.onDidChangeContent(() => { emit(); });
416
+ return {
417
+ getKind: () => kind,
418
+ getFormat: () => format,
419
+ setFormat,
420
+ setValue,
421
+ setAccounts,
422
+ validate,
423
+ reveal: (line, column) => {
424
+ const position = { lineNumber: Math.max(1, line), column: Math.max(1, column) };
425
+ editor.revealPositionInCenter(position);
426
+ editor.setPosition(position);
427
+ editor.focus();
428
+ },
429
+ setReadOnly: (readOnly) => editor.updateOptions({ readOnly }),
430
+ focus: () => editor.focus(),
431
+ dispose: () => {
432
+ change.dispose();
433
+ editor.dispose();
434
+ model.dispose();
435
+ registry.delete(kind);
436
+ publishJsonSchemas();
437
+ },
438
+ };
439
+ }
@@ -0,0 +1,22 @@
1
+ // Build entry for the lazy integration rules editor. Keeping Monaco contributions out
2
+ // of integrations.js means the editor bundle is fetched only when the panel opens.
3
+ import "monaco-editor/editor/contrib/bracketMatching/browser/bracketMatching";
4
+ import "monaco-editor/editor/contrib/clipboard/browser/clipboard";
5
+ import "monaco-editor/editor/contrib/codeAction/browser/codeActionContributions";
6
+ import "monaco-editor/editor/contrib/contextmenu/browser/contextmenu";
7
+ import "monaco-editor/editor/contrib/find/browser/findController";
8
+ import "monaco-editor/editor/contrib/folding/browser/folding";
9
+ import "monaco-editor/editor/contrib/format/browser/formatActions";
10
+ import "monaco-editor/editor/contrib/gotoError/browser/gotoError";
11
+ import "monaco-editor/editor/contrib/hover/browser/hoverContribution";
12
+ import "monaco-editor/editor/contrib/linesOperations/browser/linesOperations";
13
+ import "monaco-editor/editor/contrib/multicursor/browser/multicursor";
14
+ import "monaco-editor/editor/contrib/placeholderText/browser/placeholderText.contribution";
15
+ import "monaco-editor/editor/contrib/snippet/browser/snippetController2";
16
+ import "monaco-editor/editor/contrib/suggest/browser/suggestController";
17
+ import "monaco-editor/editor/contrib/wordHighlighter/browser/wordHighlighter";
18
+ import "monaco-editor/editor/contrib/wordOperations/browser/wordOperations";
19
+ import "monaco-editor/editor/browser/coreCommands";
20
+
21
+ export { createIntegrationRulesEditor } from "./integration-rules-editor";
22
+ export type { IntegrationRulesEditor, EditorValidation, RulesFormat, RulesKind } from "./integration-rules-editor";
@@ -0,0 +1,228 @@
1
+ /// <reference lib="dom" />
2
+
3
+ // JSON Schema shared by the Monaco JSON language service and the plain-text fallback.
4
+ export type RuleAccount = { id: string; platform: string };
5
+
6
+ export type JsonSchema = {
7
+ type?: "array" | "object" | "string" | "integer" | "number" | "boolean";
8
+ title?: string;
9
+ description?: string;
10
+ required?: string[];
11
+ properties?: Record<string, JsonSchema>;
12
+ additionalProperties?: boolean;
13
+ items?: JsonSchema;
14
+ minItems?: number;
15
+ enum?: unknown[];
16
+ const?: unknown;
17
+ minLength?: number;
18
+ minimum?: number;
19
+ anyOf?: JsonSchema[];
20
+ oneOf?: JsonSchema[];
21
+ allOf?: JsonSchema[];
22
+ if?: JsonSchema;
23
+ then?: JsonSchema;
24
+ errorMessage?: string;
25
+ };
26
+
27
+ export type SchemaIssue = { path: Array<string | number>; message: string; keyword: string };
28
+
29
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
30
+ Boolean(value) && typeof value === "object" && !Array.isArray(value);
31
+
32
+ const accountEnum = (accounts: RuleAccount[]): JsonSchema => ({
33
+ type: "string",
34
+ enum: accounts.map((account) => account.id),
35
+ errorMessage: accounts.length
36
+ ? "Account does not exist. Add it under Accounts first."
37
+ : "Add an account under Accounts first.",
38
+ });
39
+
40
+ const platformEnum = (accounts: RuleAccount[]): JsonSchema => ({
41
+ type: "string",
42
+ enum: [...new Set(accounts.map((account) => account.platform))],
43
+ errorMessage: "Use the platform of the selected account.",
44
+ });
45
+
46
+ function target(accounts: RuleAccount[]): JsonSchema {
47
+ return {
48
+ type: "object",
49
+ additionalProperties: false,
50
+ required: ["platform", "account", "room"],
51
+ properties: {
52
+ platform: platformEnum(accounts),
53
+ account: accountEnum(accounts),
54
+ room: { type: "string", minLength: 1, description: "Target room ID." },
55
+ },
56
+ allOf: accounts.map((account) => ({
57
+ if: { required: ["account"], properties: { account: { const: account.id } } },
58
+ then: { properties: { platform: { const: account.platform, errorMessage: `Account "${account.id}" uses platform "${account.platform}".` } } },
59
+ })),
60
+ };
61
+ }
62
+
63
+ const transformSchema: JsonSchema = {
64
+ anyOf: [
65
+ { type: "object", additionalProperties: false, required: ["op"], properties: { op: { const: "prefix-source" } } },
66
+ { type: "object", additionalProperties: false, required: ["op"], properties: { op: { const: "trim" } } },
67
+ { type: "object", additionalProperties: false, required: ["op"], properties: { op: { const: "quote-preview" } } },
68
+ {
69
+ type: "object",
70
+ additionalProperties: false,
71
+ required: ["op", "max"],
72
+ properties: { op: { const: "truncate" }, max: { type: "integer", minimum: 1 } },
73
+ },
74
+ ],
75
+ };
76
+
77
+ export function buildRulesSchema(accounts: RuleAccount[]): JsonSchema {
78
+ return {
79
+ $schema: "http://json-schema.org/draft-07/schema#",
80
+ title: "Integration rules",
81
+ type: "array",
82
+ items: {
83
+ type: "object",
84
+ additionalProperties: false,
85
+ required: ["id", "version", "from", "to"],
86
+ properties: {
87
+ id: { type: "string", minLength: 1, description: "Rule name, unique with its version." },
88
+ version: { type: "integer", minimum: 1, description: "Bump the version to replace this rule." },
89
+ from: {
90
+ type: "object",
91
+ additionalProperties: false,
92
+ required: ["platform", "account", "room"],
93
+ properties: {
94
+ platform: { const: "chatroom", errorMessage: "The source platform must be chatroom." },
95
+ account: { const: "center", errorMessage: "The source account must be center." },
96
+ room: { type: "string", minLength: 1, description: "Room ID to watch." },
97
+ event: {
98
+ enum: ["message.created", "message.forward_requested"],
99
+ description: "Event to match; all supported events when omitted.",
100
+ },
101
+ },
102
+ },
103
+ transforms: { type: "array", items: transformSchema },
104
+ to: { type: "array", minItems: 1, items: target(accounts) },
105
+ onMissingParent: { enum: ["quote_or_unthreaded", "drop"] },
106
+ onUnsupported: { enum: ["text_with_notice", "drop"] },
107
+ },
108
+ },
109
+ } as JsonSchema;
110
+ }
111
+
112
+ export function buildInboundSchema(accounts: RuleAccount[]): JsonSchema {
113
+ return {
114
+ $schema: "http://json-schema.org/draft-07/schema#",
115
+ title: "Inbound routes",
116
+ type: "array",
117
+ items: {
118
+ type: "object",
119
+ required: ["from", "to"],
120
+ properties: {
121
+ from: {
122
+ type: "object",
123
+ required: ["platform", "account", "room"],
124
+ properties: {
125
+ platform: platformEnum(accounts),
126
+ account: accountEnum(accounts),
127
+ room: { type: "string", minLength: 1, description: "Room ID on the external platform." },
128
+ event: { type: "string", description: "Optional external event filter." },
129
+ },
130
+ allOf: accounts.map((account) => ({
131
+ if: { required: ["account"], properties: { account: { const: account.id } } },
132
+ then: { properties: { platform: { const: account.platform, errorMessage: `Account "${account.id}" uses platform "${account.platform}".` } } },
133
+ })),
134
+ },
135
+ to: {
136
+ type: "object",
137
+ required: ["room"],
138
+ properties: { room: { type: "string", minLength: 1, description: "Chat room ID that receives the message." } },
139
+ },
140
+ },
141
+ },
142
+ } as JsonSchema;
143
+ }
144
+
145
+ function matchesType(value: unknown, type: JsonSchema["type"]): boolean {
146
+ switch (type) {
147
+ case undefined: return true;
148
+ case "object": return isRecord(value);
149
+ case "array": return Array.isArray(value);
150
+ case "string": return typeof value === "string";
151
+ case "integer": return typeof value === "number" && Number.isInteger(value);
152
+ case "number": return typeof value === "number" && Number.isFinite(value);
153
+ case "boolean": return typeof value === "boolean";
154
+ }
155
+ }
156
+
157
+ function sameValue(left: unknown, right: unknown): boolean {
158
+ return Object.is(left, right);
159
+ }
160
+
161
+ export function validateAgainstSchema(
162
+ value: unknown,
163
+ schema: JsonSchema,
164
+ path: Array<string | number> = [],
165
+ issues: SchemaIssue[] = [],
166
+ ): SchemaIssue[] {
167
+ const fail = (message: string, keyword: string, at = path) => {
168
+ issues.push({ path: at, message: schema.errorMessage || message, keyword });
169
+ };
170
+ if (!matchesType(value, schema.type)) {
171
+ fail(`Expected ${schema.type ?? "a supported value"}.`, "type");
172
+ return issues;
173
+ }
174
+ if (schema.const !== undefined && !sameValue(value, schema.const)) {
175
+ fail(`Must be ${JSON.stringify(schema.const)}.`, "const");
176
+ }
177
+ if (schema.enum && !schema.enum.some((item) => sameValue(item, value))) {
178
+ fail(`Must be one of: ${schema.enum.map((item) => JSON.stringify(item)).join(", ")}.`, "enum");
179
+ }
180
+ if (typeof value === "string" && schema.minLength !== undefined && value.length < schema.minLength) {
181
+ fail("Must not be empty.", "minLength");
182
+ }
183
+ if (typeof value === "number" && schema.minimum !== undefined && value < schema.minimum) {
184
+ fail(`Must be at least ${schema.minimum}.`, "minimum");
185
+ }
186
+ if (Array.isArray(value)) {
187
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
188
+ fail(`Add at least ${schema.minItems} item.`, "minItems");
189
+ }
190
+ if (schema.items) value.forEach((item, index) => validateAgainstSchema(item, schema.items!, [...path, index], issues));
191
+ }
192
+ if (isRecord(value)) {
193
+ for (const key of schema.required ?? []) {
194
+ if (!Object.hasOwn(value, key)) fail(`Missing required field "${key}".`, "required", [...path, key]);
195
+ }
196
+ for (const [key, child] of Object.entries(value)) {
197
+ const childSchema = schema.properties?.[key];
198
+ if (childSchema) validateAgainstSchema(child, childSchema, [...path, key], issues);
199
+ else if (schema.additionalProperties === false) fail(`Unknown field "${key}".`, "additionalProperties", [...path, key]);
200
+ }
201
+ }
202
+ for (const branch of schema.allOf ?? []) validateAgainstSchema(value, branch, path, issues);
203
+ if (schema.if && schema.then && validateAgainstSchema(value, schema.if, path, []).length === 0) {
204
+ validateAgainstSchema(value, schema.then, path, issues);
205
+ }
206
+ for (const keyword of ["anyOf", "oneOf"] as const) {
207
+ const branches = schema[keyword];
208
+ if (!branches?.length) continue;
209
+ const runs = branches.map((branch) => validateAgainstSchema(value, branch, path, []));
210
+ const passed = runs.filter((run) => run.length === 0).length;
211
+ if (keyword === "anyOf" ? passed === 0 : passed !== 1) {
212
+ if (keyword === "oneOf" && passed > 1) {
213
+ fail("Matches more than one allowed shape.", keyword);
214
+ } else {
215
+ const best = runs.filter((run) => run.length > 0).sort((left, right) => left.length - right.length)[0];
216
+ if (best) issues.push(...best);
217
+ else fail("Does not match any allowed shape.", keyword);
218
+ }
219
+ }
220
+ }
221
+ return issues;
222
+ }
223
+
224
+ export function formatPath(root: string, path: Array<string | number>): string {
225
+ let text = root;
226
+ for (const part of path) text += typeof part === "number" ? `[${part}]` : `.${part}`;
227
+ return text;
228
+ }
@@ -0,0 +1 @@
1
+ import "monaco-editor/languages/features/json/json.worker";